当前位置:Gxlcms > 数据库问题 > 用servlet和jsp做探索数据库

用servlet和jsp做探索数据库

时间:2021-07-01 10:21:17 帮助过:3人阅读

package com.chinasoft.jsptest.entity; 2 3 public class Menbers { 4 private int id; 5 private String name; 6 private String pwd; 7 private String email; 8 private String born; 9 private String sex; 10 11 public Menbers() { 12 super(); 13 // TODO Auto-generated constructor stub 14 } 15 16 public Menbers(String name, String pwd, String email, String born, 17 String sex) { 18 super(); 19 this.name = name; 20 this.pwd = pwd; 21 this.email = email; 22 this.born = born; 23 this.sex = sex; 24 } 25 26 public String getEmail() { 27 return email; 28 } 29 30 public void setEmail(String email) { 31 this.email = email; 32 } 33 34 public String getBorn() { 35 return born; 36 } 37 38 public void setBorn(String born) { 39 this.born = born; 40 } 41 42 public String getSex() { 43 return sex; 44 } 45 46 public void setSex(String sex) { 47 this.sex = sex; 48 } 49 50 public int getId() { 51 return id; 52 } 53 54 public void setId(int id) { 55 this.id = id; 56 } 57 58 public String getName() { 59 return name; 60 } 61 62 public void setName(String name) { 63 this.name = name; 64 } 65 66 public String getPwd() { 67 return pwd; 68 } 69 70 public void setPwd(String pwd) { 71 this.pwd = pwd; 72 } 73 } View Code 技术分享
 1 package com.chinasoft.jsptest.entity;
 2 
 3 public class Product {
 4     public int id ;
 5     public String name  ;
 6     public String money ;
 7     public int getId() {
 8         return id;
 9     }
10     public void setId(int id) {
11         this.id = id;
12     }
13     public String getName() {
14         return name;
15     }
16     public void setName(String name) {
17         this.name = name;
18     }
19     public String getMoney() {
20         return money;
21     }
22     public void setMoney(String money) {
23         this.money = money;
24     }
25     
26     
27     
28 
29 }
View Code

 二、DAO层  

1.BaseDAO

技术分享
  1 package com.chinasofti.jsptest.dao;
  2 
  3 import java.sql.Connection;
  4 import java.sql.DriverManager;
  5 import java.sql.PreparedStatement;
  6 import java.sql.ResultSet;
  7 import java.sql.SQLException;
  8 
  9 
 10 public class BaseDAO {
 11    //1.链接数据库
 12     String className="com.microsoft.sqlserver.jdbc.SQLServerDriver";
 13     String connectionString="jdbc:sqlserver://127.0.0.1;DatabaseName=JspTest";
 14     String username="sa";
 15     String userpwd="123456";
 16     
 17     private Connection conn;
 18     private PreparedStatement pst;
 19     private ResultSet rst;
 20 
 21   //2. 链接上表
 22     public BaseDAO(){
 23         try {
 24             Class.forName(className);
 25         } catch (ClassNotFoundException e) {
 26             // TODO Auto-generated catch block
 27             e.printStackTrace();
 28         }
 29     }
 30     public void getconnection(){
 31         try {
 32             conn=DriverManager.getConnection(connectionString,username,userpwd);
 33         } catch (SQLException e) {
 34             e.printStackTrace();
 35         }
 36     }
 37     
 38     public ResultSet ExecuteQuest(String sql){
 39         getconnection();
 40         return ExecuteQuest(sql,new Object[]{});
 41     }
 42      public ResultSet ExecuteQuest(String sql, Object[] params) {
 43          getconnection();
 44           try {
 45             pst=conn.prepareStatement(sql);
 46         } catch (SQLException e) {
 47             // TODO Auto-generated catch block
 48             e.printStackTrace();
 49         }
 50          for(int i=0;i<params.length;i++){
 51              try {
 52                  
 53                 pst.setObject(i+1, params[i]);
 54             } catch (SQLException e) {
 55                 // TODO Auto-generated catch block
 56                 e.printStackTrace();
 57             }
 58          }
 59          try {
 60             rst=pst.executeQuery();
 61         } catch (SQLException e) {
 62             // TODO Auto-generated catch block
 63             e.printStackTrace();
 64         } 
 65          return rst;
 66     }
 67      
 68 
 69     public int ExecuteUpdate(String sql){
 70         getconnection();
 71         return ExecuteUpdate(sql,new Object[]{});
 72       }
 73       public int ExecuteUpdate(String sql,Object[] params){
 74         getconnection();
 75         int result=0;
 76         try {
 77             pst=conn.prepareStatement(sql);
 78         } catch (SQLException e) {
 79             e.printStackTrace();
 80         }
 81         for(int i=0;i<params.length;i++){
 82             try {
 83                 pst.setObject(i+1, params[i]);
 84             } catch (SQLException e) {
 85                 // TODO Auto-generated catch block
 86                 e.printStackTrace();
 87             }    
 88         }
 89         try {
 90             result=pst.executeUpdate();
 91         } catch (SQLException e) {
 92             // TODO Auto-generated catch block
 93             e.printStackTrace();
 94         }
 95         return result;  
 96       }
 97       
 98       
 99     public void CloseAll(){
100             try{
101                 if(!rst.isClosed()){
102                     rst.close();
103                 }
104                 if(!pst.isClosed()){
105                     pst.close();
106                 }
107                 if(!conn.isClosed()){
108                     conn.close();
109                 }
110             }catch(Exception e){
111                 System.out.println(e.getMessage());
112             }
113         }
114 
115     
116 }
View Code

2.DAO

技术分享
 1 package com.chinasofti.jsptest.dao;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 import com.chinasoft.jsptest.entity.Menbers;
 8 
 9 public class MenbersDAO {
10     //1.new一个
11    private BaseDAO dao = new BaseDAO();
12    //2.增加ExecuteUpdate;
13    public void Add(Menbers meb){
14       String  sql = "insert into [test]([id],[name],[pwd],[email],[born],[sex]) values (?,?,?,?,?,?)";
15       Object[] params=new Object[]{meb.getId(),meb.getName(),meb.getPwd(),meb.getEmail(),meb.getBorn(),meb.getSex()};
16       dao.ExecuteUpdate(sql,params); 
17    }
18    //3.删除ExecuteUpdate;
19    public void Delete(Menbers meb){
20        String sql = "delete from [test] where [id]=?";
21        Object[] params = new Object[]{meb.getId()};
22        dao.ExecuteUpdate(sql,params); 
23    }
24    //4.修改ExecuteUpdate;
25    public void Update(Menbers meb){
26        String sql="update [tset] set [name]=?,[pwd]=? WHERE [id]=?";
27         Object [] params=new Object[]{meb.getName(),meb.getPwd(),meb.getId()};
28         dao.ExecuteUpdate(sql,params);
29    }
30    //5.查找全部ExecuteQuest;
31    public List<Menbers> getselect(){
32        List<Menbers> result=new ArrayList<Menbers>();
33        String sql="SELECT [id],[name],[pwd] ,[email],[sex]FROM [test]";
34        ResultSet rst=dao.ExecuteQuest(sql);
35        try{
36         while(rst.next()){
37                 Menbers temp=new Menbers();
38                 temp.setId(rst.getInt(1));
39                 temp.setName(rst.getString(2));
40                 temp.setPwd(rst.getString(3));
41                 temp.setEmail(rst.getString(4));
42                 temp.setSex(rst.getString(5));
43                 result.add(temp);
44             }
45     } catch (SQLException e) {
46         // TODO Auto-generated catch block
47         e.printStackTrace();
48     }
49        dao.CloseAll();
50        return result; 
51    }
52    //6.按照ID查找ExecuteQuest;
53      public Menbers getSelectid(int id){
54          Menbers result=null;
55          String sql="SELECT [id],[name],[pwd] FROM [test] WHERE [id]=?";
56          Object[] params=new Object[]{id};
57          ResultSet rst=dao.ExecuteQuest(sql,params);
58          try {
59              if(rst.next()){        
60                  result = new Menbers();
61                  result.setId(rst.getInt(1));
62                  result.setName(rst.getString(2));
63                  result.setPwd(rst.getString(3));
64              }
65          } catch (SQLException e) {
66              // TODO Auto-generated catch block
67              e.printStackTrace();
68          }
69          dao.CloseAll();
70          return result;
71      }
72    //7.按照name查找ExecuteQuest;
73      public Menbers getSelectname(String name){
74          Menbers result=null;
75          String sql="SELECT [id],[name],[pwd] FROM [test] WHERE [name]=?";
76          Object[] params=new Object[]{name};
77          ResultSet rst=dao.ExecuteQuest(sql,params);
78          try {
79              if(rst.next()){
80                  result = new Menbers();
81                  result.setId(rst.getInt(1));
82                  result.setName(rst.getString(2));
83                  result.setPwd(rst.getString(3));
84              }
85          } catch (SQLException e) {
86              // TODO Auto-generated catch block
87              e.printStackTrace();
88          }
89          dao.CloseAll();
90          return result;
91      }
92     
93     
94 }
MembersDAO 技术分享
 1 package com.chinasofti.jsptest.dao;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import com.chinasoft.jsptest.entity.Product;
 9 
10 
11 
12 public class ProductDAO {
13         private  BaseDAO dao = new BaseDAO();
14         //1.增加
15         public void Add(Product put){
16             String sql ="insert into [Product]([name],[money]) values(?,?)";
17             Object[] params = new Object[]{put.getName(),put.getMoney()}; 
18             dao.ExecuteUpdate(sql, params);
19         }
20     //2.删除
21         public void delete(int id){
22             String sql ="delete [Product] where [id]=?";
23             Object[] params = new Object[]{id}; 
24             dao.ExecuteUpdate(sql, params);
25         }
26        //3.更改
27         public void Update (Product put){
28             String sql ="update [Product] set [name]=?,[money]=? where [id]=?";
29             Object[] params = new Object[]{put.getName(),put.getMoney(),put.getId()}; 
30             dao.ExecuteUpdate(sql, params);
31         }
32       //4.查找全部
33         public List <Product > getSelect(){                
34             List <Product> result=new ArrayList<Product>();
35             String sql ="select [id] ,[name],[money] from [Product]  ";
36             ResultSet rst = dao.ExecuteQuest(sql);
37             try {
38                 while (rst.next()){
39                     Product pro = new Product();
40                      pro.setId(rst.getInt(1));
41                      pro.setName(rst.getString(2));
42                      pro.setMoney(rst.getString(3));
43                     result.add(pro);
44                 }
45             } catch (SQLException e) {
46                 // TODO Auto-generated catch block
47                 e.printStackTrace();
48             }
49             dao.CloseAll();
50             return result;
51         } 
52         //5.根据name查找
53         public Product getname(String name){
54             Product pro = null;
55             Object [] params = new Object[]{name};
56             String sql ="select [name],[money],[id] from [Product] where[name]=? ";
57             ResultSet rst = dao.ExecuteQuest(sql,params);
58             try {
59                 while (rst.next()){
60                     pro = new Product();
61                      pro.setId(rst.getInt(1));
62                      pro.setName(rst.getString(2));
63                      pro.setMoney(rst.getString(3));
64                 }
65             } catch (SQLException e) {
66                 // TODO Auto-generated catch block
67                 e.printStackTrace();
68             }
69             dao.CloseAll();
70             return pro;
71             
72         } 
73         
74     
75         
76     
77 }
ProductDAO

三、servlet层 需要建servlet类,里面会直接生成servlet/xxxx地址。这样在访问的时候,就直接访问这个地址

1.登录注册的逻辑判断层,主要注意request的用法;还有就是跳转jsp以后,jsp用post方法提交到的action地址,是servlet映射的地址!这个在WebRoot-web-inf-web.hml可以找到

技术分享
  1 package com.chinasofti.jsptest.servlet;
  2 
  3 import java.io.IOException;
  4 
  5 import javax.servlet.ServletException;
  6 import javax.servlet.http.HttpServlet;
  7 import javax.servlet.http.HttpServletRequest;
  8 import javax.servlet.http.HttpServletResponse;
  9 
 10 import com.chinasoft.jsptest.entity.Menbers;
 11 import com.chinasofti.jsptest.dao.MenbersDAO;
 12 
 13 @SuppressWarnings("serial")
 14 public class goset extends HttpServlet {
 15 
 16     /**
 17      * Constructor of the object.
 18      */
 19     public goset() {
 20         super();
 21     }
 22 
 23     /**
 24 
 25      */
 26     public void destroy() {
 27         super.destroy(); // Just puts "destroy" string in log
 28         // Put your code here
 29     }
 30 
 31     /**
 32      * 
 33      * 
 34      * This method is called when a form has its tag value method equals to get.
 35      * 
 36      * @param request
 37      *            the request send by the client to the server
 38      * @param response
 39      *            the response send by the server to the client
 40      * @throws ServletException
 41      *             if an error occurred
 42      * @throws IOException
 43      *             if an error occurred
 44      */
 45     public void doGet(HttpServletRequest request, HttpServletResponse response)
 46             throws ServletException, IOException {
 47         request.getRequestDispatcher("../go30-1.jsp").forward(request, response);//指向你要过去的JSP,进行逻辑判断以后,以post方法,进行下面的逻辑判断
 48     }
 49 
 50     /**
 51      * 
 52      * 
 53      * This method is called when a form has its tag value method equals to
 54      * post.
 55      * 
 56      * @param request
 57      *            the request send by the client to the server
 58      * @param response
 59      *            the response send by the server to the client
 60      * @throws ServletException
 61      *             if an error occurred
 62      * @throws IOException
 63      *             if an error occurred
 64      */
 65     public void doPost(HttpServletRequest request, HttpServletResponse response)
 66             throws ServletException, IOException {
 67         request.setCharacterEncoding("utf-8");
 68         String name = request.getParameter("name");
 69         String pwd = request.getParameter("pwd");
 70         String emai = request.getParameter("email");
 71         String born = request.getParameter("born");
 72         String sex = request.getParameter("sex");
 73         String type = request.getParameter("type");
 74         if ("login".equals(type)) {
 75             MenbersDAO dao = new MenbersDAO();
 76             Menbers m = dao.getSelectname(name);
 77             if (m != null && m.getPwd().equals(pwd)) {
 78                 request.setAttribute("title", "登陆成功");
 79                 request.setAttribute("retn", "欢迎你," + name + "。");
 80                 request.getRequestDispatcher("../go30-2.jsp").forward(request,
 81                         response);//指向你要过去的JSP
 82             } else if (m != null && !m.getPwd().endsWith(pwd)) {
 83                 request.setAttribute("title", "登陆失败");
 84                 request.setAttribute("retn", "用户名或密码错误!请重新登录 ");
 85                 request.getRequestDispatcher("../go30-3.jsp").forward(request,
 86                         response);//指向你要过去的JSP
 87             } else {
 88                 request.setAttribute("retn", "你不是公司员工,请入职以后再登入");
 89                 request.getRequestDispatcher("../go30-4.jsp").forward(request,
 90                         response);//指向你要过去的JSP
 91             }
 92         } else if ("register".equals(type)) {
 93             Menbers m = new Menbers(name, pwd, emai, born, sex);
 94             MenbersDAO dao = new MenbersDAO();
 95             dao.Add(m);
 96             request.getRequestDispatcher("../go30-4.jsp").forward(request,
 97                     response);//指向你要过去的JSP
 98         }
 99 
100     }
101 
102     /**
103      * 
104      * @throws ServletException
105      *             if an error occurs
106      */
107     public void init() throws ServletException {
108         // Put your code here
109     }
110 
111 }
goset.java 2.显示全部界面,只用看get方法就好了 技术分享

人气教程排行