Author AhahaGe

day01主要实现了登录的功能,按理应该先实现注册的功能。

    主要分为以下几个部分:

  1.     Mysql数据库
  2.     登录(login)jsp和登录成功(main)jsp页面
  3.     util包下的JDBCUtil数据库连接类
  4.     web.xml中配置servlet

    step1:建数据库和表,并插入原始数据

  1. show databases; 
  2. set charset utf8; 
  3. create database story; 
  4. use story;  
  5. mysql> create table user(  
  6.     -> id int primary key auto_increment, 
  7.     -> name char(20), 
  8.     -> password char(30)); 
  9. insert into user(name,passwordvalues ('a','a'); 
  10. insert into user(name,passwordvalues ('b','b'); 
  11. //下面这句给name加unique属性
  12. alter table user add unique(name); 

    step2:写login.jsp

    jsp里主要包含一个用来登录的form,以及其中需要的用户名,密码,按钮,验证码暂时不用(还不会写那个生成验证码的servelt)

 
  
  1. <%@ page language="java" contentType="text/html; charset=utf-8" 
  2.     pageEncoding="utf-8"%> 
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  4. <html> 
  5. <head> 
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
  7. <title>login jsp</title> 
  8. </head> 
  9.     <body> 
  10.         <div><h1>story user login</h1></div> 
  11.          
  12.         <form action="login" method="post"> 
  13.             <div> 
  14.                 username:<input type="text" name="username"/> 
  15.             </div> 
  16.             <div> 
  17.                 password:<input type="password" name="password"/> 
  18.             </div> 
  19.             <div> 
  20.                 validateCode:<input type="text" name="validateCode"/> 
  21.             </div> 
  22.             <div> 
  23.                 <input type="submit" name="login" value="login"/> 
  24.                 <input type="button" name="register" value="register"/> 
  25.             </div> 
  26.         </form> 
  27.          
  28.         <!-- display wrong message --> 
  29.         <div style="font-size:20;color:red">${sessionScope.error}</div> 
  30.     </body> 
  31.      
  32. </html> 

    需要关注以下几点:

  •     table没有div灵活,就都用div了,css设置不来,先丑一点
  •     charset要改成utf-8
  •     login按钮的type要是submit,不然点了没效果
  •     错误信息的显示style为红色,内容从session中取
  •     method=post, action写了一个loginValidate的servlet

    step3:网站的欢迎页面用一个servlet, servlet的作用是直接跳到login.jsp

    web.xml中welcome-file-list

 
  
  1. <welcome-file-list> 
  2.     <welcome-file>index</welcome-file> 
  3. </welcome-file-list> 

    jsp页面的位置:

    jsp页面的位置

    WEB-INF下的页面不能直接访问,就用了一个servlet来跳转

 
  
  1. <servlet> 
  2.     <servlet-name>index</servlet-name> 
  3.     <jsp-file>/WEB-INF/jsp/login.jsp</jsp-file> 
  4. </servlet> 
  5. <servlet-mapping> 
  6.     <servlet-name>index</servlet-name> 
  7.     <url-pattern>/index</url-pattern> 
  8. </servlet-mapping> 

    这样输入http://localhost:8080/story的时候就直接跳转到WEB-INF下的login.jsp下面。

    step4.写login servlet用来处理登录逻辑,类名是LoginServlet

 
  
  1. package servlet; 
  2.  
  3. import java.io.IOException; 
  4. import java.sql.Connection; 
  5. import java.sql.ResultSet; 
  6. import java.sql.SQLException; 
  7. import java.sql.Statement; 
  8.  
  9. import javax.servlet.ServletException; 
  10. import javax.servlet.annotation.WebServlet; 
  11. import javax.servlet.http.HttpServlet; 
  12. import javax.servlet.http.HttpServletRequest; 
  13. import javax.servlet.http.HttpServletResponse; 
  14. import javax.servlet.http.HttpSession; 
  15.  
  16. import util.JDBCUtil; 
  17.  
  18. /** 
  19.  * Servlet implementation class LoginServlet 
  20.  * used to deal with login request 
  21.  */ 
  22. @WebServlet(description = "used to deal with user login operation", urlPatterns = { "/LoginServlet" }) 
  23. public class LoginServlet extends HttpServlet { 
  24.     private static final long serialVersionUID = 1L; 
  25.         
  26.     /** 
  27.      * @see HttpServlet#HttpServlet() 
  28.      */ 
  29.     public LoginServlet() { 
  30.         super(); 
  31.         // TODO Auto-generated constructor stub 
  32.     } 
  33.  
  34.     /** 
  35.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  36.      */ 
  37.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
  38.         doPost(request,response); 
  39.     } 
  40.  
  41.     /** 
  42.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  43.      */ 
  44.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
  45.         //set the response type and should in the first line 
  46.         response.setContentType("text/html;charset=utf-8"); 
  47.          
  48.         //get session  
  49.         HttpSession session = request.getSession(); 
  50.          
  51.         //get the parameter transmitted from client request 
  52.         String username = request.getParameter("username"); 
  53.         String password = request.getParameter("password"); 
  54.          
  55.         Connection conn = null
  56.         Statement stmt = null
  57.         ResultSet rs = null
  58.         String sql = "select id,name,password from test where name='"+username+"'"
  59.         try { 
  60.             //get connection 
  61.             conn = JDBCUtil.getConnection(); 
  62.             //create statement 
  63.             stmt = conn.createStatement()  ; 
  64.             //execute sql and get result 
  65.             rs = stmt.executeQuery(sql); 
  66.             while(rs.next()){ 
  67.                 //compare client name and password with the database 
  68.                 if(rs.getString(2).equals(username)){ 
  69.                     if(rs.getString(3).equals(password)){ 
  70.                          
  71.                         //close connection 
  72.                         if(conn!=null){ 
  73.                             rs.close(); 
  74.                             stmt.close(); 
  75.                             conn.close(); 
  76.                         } 
  77.                          
  78.                         //if match, set the username attribute into session and empty error attribute 
  79.                         //redirect it to the main page 
  80.                         session.setAttribute("username", username); 
  81.                         session.setAttribute("error"null); 
  82.                         response.sendRedirect(request.getContextPath()+"/main"); 
  83.                         return
  84.                     } 
  85.                 } 
  86.             } 
  87.             //if don't match, set the error attribute and redirect to login page 
  88.             session.setAttribute("error""username or password is incorrect!"); 
  89.             response.sendRedirect(request.getContextPath()+"/index"); 
  90.         } catch (SQLException e) { 
  91.             e.printStackTrace(); 
  92.         } 
  93.          
  94.     } 
  95.  

    类中需要注意的几点:

  •   response.setContentType("text/html;charset=utf-8");设置响应的类型,并且要放在第一句 
  •   String username = request.getParameter("username"); 引号中的username要与jsp中的name属性相同
  •   String sql = "select id,name,password from test where name='"+username+"'";字符字段值用''引起来
  •   rs.getString(2),api中规定计数从1开始,这个1指代的是上面的sql中的select出来的第一列,不是数据库表中的第一列
  •   session.setAttribute("error"null); 登录成功之后要清空error信息,不然点击浏览器后退+F5还会一直出现登录出错的信息
  •   response.sendRedirect(request.getContextPath()+"/login");重定向到指定的页面,getContextPath获取应用的根目录,来解决相对路径的问题 

 

   在写好servlet后在web.xml中部署:

 
  
  1. <servlet> 
  2.     <servlet-name>login</servlet-name> 
  3.     <servlet-class>servlet.LoginServlet</servlet-class> 
  4. </servlet> 
  5. <servlet-mapping> 
  6.     <servlet-name>login</servlet-name> 
  7.     <url-pattern>/login</url-pattern> 
  8. </servlet-mapping> 

    step5:写JDBCUtil类并导入jar包

    在add jar中不会出来在本地文件中,因此删了,直接拷入lib目录下,再在项目中刷新一下

 
  
  1. //load driver class 
  2. Class.forName("org.gjt.mm.mysql.Driver"); 
  3. //get connection 
  4. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/story"
  5.                     "root""AhahaGe1989"); 

    step6:写main.jsp

    获取并显示登录成功后放入session中的用户名

 
  
  1. <label>Welcome ${sessionScope.username}</label> 
  2. <h1>Welcome to story...</h1> 

    部署main的web.xml部分

 
  
  1. <servlet> 
  2.     <servlet-name>main</servlet-name> 
  3.         <jsp-file>/WEB-INF/jsp/main.jsp</jsp-file> 
  4. </servlet> 
  5. <servlet-mapping> 
  6.     <servlet-name>main</servlet-name> 
  7.     <url-pattern>/main</url-pattern> 
  8. </servlet-mapping> 

    step7,部署在tomcat上运行

    输入正确的a,a跳转到main页面

    login_jsp

    login_success

    如果用错误的a,b登录,显示

    login_fail


     修改记录:

    3/14/2012 修改了数据库表名从test到user,相应的修改LoginServlet中的sql语句

    3/14/2012 修改了字段值用单引号引起到字符字段值用单引号引起

    3/14/2012 修改了welcome-file-list的地址从loign到index,相应的servlet-mapping中的url-pattern也修改到index

    3/14/2012修改了loginServlet在url-pattern中的地址从validateLogin到login,相应的修改login.jsp中action为login

    3/14/2012增加了close session

    3/14/2012更新了附件的源码


    附件是源码