花花世界花花姐  

1.建一个web文件,在里面分三层,分别是实体层;DAO层,DAO层里面包含BaseDAO(数据访问层)和DAO层;还有一个servlet层,处理数据逻辑层!

一、实体层,建立两个实体,一个members,和一个product:

 1 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方法就好了
 1 package com.chinasofti.jsptest.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.List;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import com.chinasoft.jsptest.entity.Product;
13 import com.chinasofti.jsptest.dao.ProductDAO;
14 
15 public class ProductSevlet extends HttpServlet {
16 
17     /**
18      * Constructor of the object.
19      */
20     public ProductSevlet() {
21         super();
22     }
23 
24     public void destroy() {
25         super.destroy(); // Just puts "destroy" string in log
26         // Put your code here
27     }
28 
29     public void doGet(HttpServletRequest request, HttpServletResponse response)
30             throws ServletException, IOException {
31             ProductDAO dao = new ProductDAO();
32             List<Product> ms= dao.getSelect();
33             request.setAttribute("Model", ms);
34             request.getRequestDispatcher("../Product.jsp").forward(request, response);
35               
36     }
37 
38     /**
39      * The doPost method of the servlet. <br>
40      *
41      * This method is called when a form has its tag value method equals to post.
42      * 
43      * @param request the request send by the client to the server
44      * @param response the response send by the server to the client
45      * @throws ServletException if an error occurred
46      * @throws IOException if an error occurred
47      */
48     public void doPost(HttpServletRequest request, HttpServletResponse response)
49             throws ServletException, IOException {
50 
51         response.setContentType("text/html");
52         PrintWriter out = response.getWriter();
53         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
54         out.println("<HTML>");
55         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
56         out.println("  <BODY>");
57         out.print("    This is ");
58         out.print(this.getClass());
59         out.println(", using the POST method");
60         out.println("  </BODY>");
61         out.println("</HTML>");
62         out.flush();
63         out.close();
64     }
65 
66     /**
67      * Initialization of the servlet. <br>
68      *
69      * @throws ServletException if an error occurs
70      */
71     public void init() throws ServletException {
72         // Put your code here
73     }
74 
75 }
ProducAction.java
 1 package com.chinasofti.jsptest.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.List;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import com.chinasoft.jsptest.entity.Menbers;
13 import com.chinasofti.jsptest.dao.MenbersDAO;
14 
15 public class UserList extends HttpServlet {
16 
17     /**
18      * Constructor of the object.
19      */
20     public UserList() {
21         super();
22     }
23 
24     /**
25      * Destruction of the servlet. <br>
26      */
27     public void destroy() {
28         super.destroy(); // Just puts "destroy" string in log
29         // Put your code here
30     }
31 
32     /**
33      * The doGet method of the servlet. <br>
34      *
35      * This method is called when a form has its tag value method equals to get.
36      * 
37      * @param request the request send by the client to the server
38      * @param response the response send by the server to the client
39      * @throws ServletException if an error occurred
40      * @throws IOException if an error occurred
41      */
42     public void doGet(HttpServletRequest request, HttpServletResponse response)
43             throws ServletException, IOException {
44         
45         MenbersDAO dao= new MenbersDAO();
46         List <Menbers> ms = dao.getselect();
47         request.setAttribute("Model", ms);
48         request.getRequestDispatcher("../UserList.jsp").forward(request, response);
49     }
50 
51     /**
52      * The doPost method of the servlet. <br>
53      *
54      * This method is called when a form has its tag value method equals to post.
55      * 
56      * @param request the request send by the client to the server
57      * @param response the response send by the server to the client
58      * @throws ServletException if an error occurred
59      * @throws IOException if an error occurred
60      */
61     public void doPost(HttpServletRequest request, HttpServletResponse response)
62             throws ServletException, IOException {
63 
64         response.setContentType("text/html");
65         PrintWriter out = response.getWriter();
66         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
67         out.println("<HTML>");
68         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
69         out.println("  <BODY>");
70         out.print("    This is ");
71         out.print(this.getClass());
72         out.println(", using the POST method");
73         out.println("  </BODY>");
74         out.println("</HTML>");
75         out.flush();
76         out.close();
77     }
78 
79     /**
80      * Initialization of the servlet. <br>
81      *
82      * @throws ServletException if an error occurs
83      */
84     public void init() throws ServletException {
85         // Put your code here
86     }
87 
88 }
UserList.java

jsp界面,所有的显示界面

 1 <form method="post" action="<%=request.getContextPath() %>/servlet/goset">
 2         <input type="hidden" name="type" value="login">
 3         <table border="0" align="center">
 4             <tr>
 5                 <td>用户名</td>
 6                 <td><input type="text" name="name"></td>
 7             </tr>
 8             <tr>
 9                 <td>密码</td>
10                 <td><input type="password" name="pwd"></td>
11             </tr>
12 
13             <tr>
14                 <td colspan="2" align="center"><input type="submit" value="登录" />&nbsp;&nbsp;
15 
16 
17                     <input type="reset" value="取消" /></td>
18             </tr>
19         </table>
20     </form>
go30-1.jsp
1  <h1 align="center">  <%=title%>  </h1>
2      <h3 align="center">  <%=retn%>  </h3>
go30-2.jsp
 1 <h1 align="center">  <%=retn%>  </h1>
 2     <form  method="post">
 3     <table border="0" align="center" >
 4       <tr> <td>用户名</td><td> <input type="text" name="name"></td></tr>
 5       <tr><td>密码</td><td > <input type="password" name="pwd"> </td></tr>
 6 
 7       <tr><td colspan="2" align="center"> 
 8           <input type="submit" value="登录" />&nbsp;&nbsp;
 9 
10           <input type="reset" value="取消" />
11       </td></tr>    
12     </table>
13     </form>
go30-3.jsp
 1 <h1 align="center">
 2         <%=retn%>
 3     </h1>
 4     <form method="post" action="<%=request.getContextPath() %>/servlet/goset">
 5         <input type="hidden" name="type" value="register">
 6         <table border="0" align="center">
 7             <tr>
 8                 <td>用户名</td>
 9                 <td><input type="text" name="name"></td>
10             </tr>
11             <tr>
12                 <td>密码</td>
13                 <td><input type="password" name="pwd"></td>
14             </tr>
15             <tr>
16                 <td>邮箱</td>
17                 <td><input type="text" name="email"></td>
18             </tr>
19             <tr>
20                 <td>出生日期</td>
21                 <td><input type="text" name="born"></td>
22             </tr>
23             <tr>
24                 <td>性别</td>
25                 <td><input type="radio" name="sex" value="男"><input
26                     type="radio" name="sex" value="女"></td>
27             </tr>
28 
29             <tr>
30                 <td colspan="2" align="center"><input type="submit" value="注册" />&nbsp;&nbsp;
31 
32                     <input type="reset" value="取消" /></td>
33             </tr>
34         </table>
35     </form>
go30-4.jsp
 1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 2 
 3 
 4 
 5 
 6  <table>
 7     <tr width="300">
 8     <td width="100">id</td>
 9     <td width="100">name</td>
10     <td width="100">money</td>
11     </tr>
12     <c:forEach var="m" items= "${Model}">
13     <tr>
14     <td>${m.id}</td>
15     <td>${m.name}</td>
16     <td>${m.email}</td>
17 
18     </tr>
19     </c:forEach>
20     
21     </table>
Product.jsp
 1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 2 
 3 
 4 
 5 
 6 <table>
 7     <tr width="500">
 8     <td width="100">id</td>
 9     <td width="100">name</td>
10     <td width="100">pwd</td>
11     <td width="100">email</td>
12      <td width="100">born</td>
13     <td width="100">sex</td>
14     </tr>
15     <c:forEach var="m" items= "${Model}">
16     <tr>
17     <td >${m.id}</td>
18     <td >${m.name}</td>
19     <td >${m.pwd}</td>
20     <td >${m.email}</td>
21      <td >${m.born}</td>
22     <td >${m.sex}</td> 
23     
24     </tr>
25     </c:forEach>
26     
27     </table>
UserLise.jsp

 

posted on 2016-07-10 14:39  花花世界花花姐  阅读(210)  评论(0编辑  收藏  举报