zoukankan      html  css  js  c++  java
  • 小峰servlet/jsp(3)登陆功能实现

    一、User模型:

    User.java:

     1 package com.java1234.model;
     2 
     3 public class User {
     4 
     5     private int id;
     6     private String userName;
     7     private String password;
     8     
     9     
    10     
    11     public User() {
    12         super();
    13         // TODO Auto-generated constructor stub
    14     }
    15     
    16     
    17     public User(String userName, String password) {
    18         super();
    19         this.userName = userName;
    20         this.password = password;
    21     }
    22 
    23 
    24     public int getId() {
    25         return id;
    26     }
    27     public void setId(int id) {
    28         this.id = id;
    29     }
    30     public String getUserName() {
    31         return userName;
    32     }
    33     public void setUserName(String userName) {
    34         this.userName = userName;
    35     }
    36     public String getPassword() {
    37         return password;
    38     }
    39     public void setPassword(String password) {
    40         this.password = password;
    41     }
    42     
    43     
    44 }
    View Code

     二、封装jdbc连接数据库:

     1 package com.java1234.util;
     2 
     3 import java.sql.Connection;
     4 import java.sql.DriverManager;
     5 
     6 public class DbUtil {
     7 
     8     private String dbUrl="jdbc:mysql://localhost:3306/db_jsp";
     9     private String dbUserName="root";
    10     private String dbPassword="123456";
    11     private String jdbcName="com.mysql.jdbc.Driver";
    12     
    13     public Connection getCon()throws Exception{
    14         Class.forName(jdbcName);
    15         Connection con=DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
    16         return con;
    17     }
    18     
    19     public void closeCon(Connection con)throws Exception{
    20         if(con!=null){
    21             con.close();
    22         }
    23     }
    24     
    25     public static void main(String[] args) {
    26         DbUtil dbUtil=new DbUtil();
    27         try {
    28             dbUtil.getCon();
    29             System.out.println("连接成功");
    30         } catch (Exception e) {
    31             e.printStackTrace();
    32         }
    33     }
    34 }
    View Code

    三、userDao:

     1 package com.java1234.dao;
     2 
     3 import java.sql.Connection;
     4 import java.sql.PreparedStatement;
     5 import java.sql.ResultSet;
     6 
     7 import com.java1234.model.User;
     8 
     9 public class UserDao {
    10 
    11     public User login(Connection con,User user)throws Exception{
    12         User resultUser=null;
    13         String sql="select * from t_user where userName=? and password=?";
    14         PreparedStatement pstmt=con.prepareStatement(sql);
    15         pstmt.setString(1, user.getUserName());
    16         pstmt.setString(2, user.getPassword());
    17         ResultSet rs=pstmt.executeQuery();
    18         if(rs.next()){
    19             resultUser=new User();
    20             resultUser.setUserName(rs.getString("userName"));
    21             resultUser.setPassword(rs.getString("password"));
    22         }
    23         return resultUser;
    24     }
    25             
    26 }
    View Code

     四、loginServlet.java:

     1 package com.java1234.web;
     2 
     3 import java.io.IOException;
     4 import java.sql.Connection;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 import javax.servlet.http.HttpSession;
    11 
    12 import com.java1234.dao.UserDao;
    13 import com.java1234.model.User;
    14 import com.java1234.util.DbUtil;
    15 
    16 public class LoginServlet extends HttpServlet{
    17 
    18     /**
    19      * 
    20      */
    21     private static final long serialVersionUID = 1L;
    22     
    23     DbUtil dbUtil=new DbUtil();
    24     UserDao userDao=new UserDao();
    25 
    26     @Override
    27     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    28             throws ServletException, IOException {
    29         this.doPost(request, response);
    30     }
    31 
    32     @Override
    33     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    34             throws ServletException, IOException {
    35         String userName=request.getParameter("userName");
    36         String password=request.getParameter("password");
    37         
    38         Connection con=null;
    39         try {
    40             User user=new User(userName,password);
    41             con=dbUtil.getCon();
    42             User currentUser=userDao.login(con, user);
    43             if(currentUser==null){
    44                 request.setAttribute("error", "用户名或密码错误");
    45                 request.setAttribute("userName", userName);
    46                 request.setAttribute("password", password);
    47                 request.getRequestDispatcher("login.jsp").forward(request, response);
    48             }else{
    49                 HttpSession session=request.getSession();
    50                 session.setAttribute("currentUser", currentUser);
    51                 response.sendRedirect("main.jsp");
    52             }
    53         } catch (Exception e) {
    54             e.printStackTrace();
    55         }
    56     }
    57     
    58     
    59 }
    View Code

    前台登陆界面login.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
     2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     3 <html>
     4 <head>
     5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     6 <title>Insert title here</title>
     7 </head>
     8 <body>
     9 <form action="login" method="post">
    10 <table>
    11     <tr>
    12         <th colspan="2">用户登录</th>
    13     </tr>
    14     <tr>
    15         <td>用户名:</td>
    16         <td><input type="text" id="userName" name="userName" value="${userName }"/></td>
    17     </tr>
    18     <tr>
    19         <td>密码:</td>
    20         <td><input type="password" id="password" name="password" value="${password }"/></td>
    21     </tr>
    22     <tr>
    23         <td><input type="submit" value="登录"/></td>
    24         <td><font color="red">${error }</font></td>
    25     </tr>
    26 </table>
    27 </form>
    28 </body>
    29 </html>
    View Code

    登陆成功后跳转到main.jsp:

     1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
     2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
     3 <html>
     4 <head>
     5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     6 <title>Insert title here</title>
     7 </head>
     8 <body>
     9 主页!当前登录用户:${currentUser.userName } &nbsp;&nbsp;<a href="logout">注销</a>
    10 </body>
    11 </html>
    View Code

    五、注销方法:

    LogoutServlet.java:

     1 package com.java1234.web;
     2 
     3 import javax.servlet.ServletException;
     4 import javax.servlet.http.HttpServlet;
     5 import javax.servlet.http.HttpServletRequest;
     6 import javax.servlet.http.HttpServletResponse;
     7 
     8 
     9 public class LogoutServlet extends HttpServlet{
    10     /**
    11      * 
    12      */
    13     private static final long serialVersionUID = 1L;
    14 
    15     @Override
    16     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    17             throws ServletException, IOException {
    18         this.doPost(request, response);
    19     }
    20 
    21     @Override
    22     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    23             throws ServletException, IOException {
    24         request.getSession().invalidate();
    25         response.sendRedirect("login.jsp");
    26     }
    27     
    28     
    29 }
    View Code

    六、loginServlet.java/LogoutServlet.java两个servlet在web.xml中的配置:

    web.xml配置:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
     3   <display-name>HeadFirstJspServletChap05</display-name>
     4   <welcome-file-list>
     5     <welcome-file>index.html</welcome-file>
     6     <welcome-file>index.htm</welcome-file>
     7     <welcome-file>index.jsp</welcome-file>
     8     <welcome-file>default.html</welcome-file>
     9     <welcome-file>default.htm</welcome-file>
    10     <welcome-file>default.jsp</welcome-file>
    11   </welcome-file-list>
    12 
    13   <servlet>
    14       <servlet-name>loginServlet</servlet-name>
    15       <servlet-class>com.java1234.web.LoginServlet</servlet-class>
    16   </servlet>
    17   
    18   <servlet-mapping>
    19       <servlet-name>loginServlet</servlet-name>
    20       <url-pattern>/login</url-pattern>
    21   </servlet-mapping>
    22   
    23   <servlet>
    24       <servlet-name>logoutServlet</servlet-name>
    25       <servlet-class>com.java1234.web.LogoutServlet</servlet-class>
    26   </servlet>
    27   
    28   <servlet-mapping>
    29       <servlet-name>logoutServlet</servlet-name>
    30       <url-pattern>/logout</url-pattern>
    31   </servlet-mapping>
    32   
    33   <filter>
    34       <filter-name>loginFilter</filter-name>
    35       <filter-class>com.java1234.filter.LoginFilter</filter-class>
    36   </filter>
    37   
    38   <filter-mapping>
    39       <filter-name>loginFilter</filter-name>
    40       <url-pattern>/*</url-pattern>
    41   </filter-mapping>
    42   
    43   <listener>
    44       <listener-class>
    45           com.java1234.listener.SessionAttributeListener
    46       </listener-class>
    47   </listener>
    48 </web-app>
    View Code

    七、Servlet过滤器:

    过滤用户请求;

    添加登陆过滤器,LoignFilter.java:

     1 package com.java1234.filter;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.Filter;
     6 import javax.servlet.FilterChain;
     7 import javax.servlet.FilterConfig;
     8 import javax.servlet.ServletException;
     9 import javax.servlet.ServletRequest;
    10 import javax.servlet.ServletResponse;
    11 import javax.servlet.http.HttpServletRequest;
    12 import javax.servlet.http.HttpSession;
    13 
    14 public class LoginFilter implements Filter{
    15 
    16     public void destroy() {
    17         
    18     }
    19 
    20     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
    21             FilterChain filterChain) throws IOException, ServletException {
    22         HttpServletRequest request=(HttpServletRequest)servletRequest;
    23         HttpSession session=request.getSession();
    24         Object o=session.getAttribute("currentUser");
    25         String path=request.getServletPath();        //获取用户请求的路径 "/login"
    26         if(o==null&&path.indexOf("login")<0){
    27             request.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);
    28         }else{
    29             filterChain.doFilter(servletRequest, servletResponse);
    30         }
    31     }
    32 
    33     public void init(FilterConfig arg0) throws ServletException {
    34         
    35     }
    36 
    37 }
    View Code

     八、Servlet监听器:

    监听web事件,如application、session、request

     1 package com.java1234.listener;
     2 
     3 import javax.servlet.http.HttpSessionAttributeListener;
     4 import javax.servlet.http.HttpSessionBindingEvent;
     5 
     6 public class SessionAttributeListener implements HttpSessionAttributeListener{
     7 
     8     //session中添加attribute时候会监听到
     9     public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
    10         System.out.println("添加的属性名: "+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
    11     }
    12 
    13     public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
    14         System.out.println("删除的属性名: "+httpSessionBindingEvent.getName()+",属性值:"+httpSessionBindingEvent.getValue());
    15     }
    16 
    17     public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
    18         
    19     }
    20 
    21 }
    View Code

    配置listener见上面的web.xml;

    登陆成功后,就能看到console打印:

    servlet中跳转的两种方式:

    response.sendRedirect("target.jsp");          //客户端跳转/重定向

    request.getRequestDispatcher("target.jsp").forward(request, response);    //服务器端跳转/转发

  • 相关阅读:
    GoogLeNet解读
    caffe使用自己的数据做分类
    YOLO2解读,训练自己的数据及相关转载以供学习
    转:SSD详解
    c/c++输入处理,制定变量参数和值
    转载:给bash的提示符设置不同的颜色 一个很常用的功能,效果如下:
    绛河 初识WCF4
    初识WCF3
    初识WCF2
    初识WCF1
  • 原文地址:https://www.cnblogs.com/tenWood/p/6505291.html
Copyright © 2011-2022 走看看