欲实现以下操作:
利用过滤器编写登录程序,设置cookie保存时间,在有效期内重复登录可直接利用登录以后的网址登录。
创建数据库test 在此库下创建表user1
代码如下:
package com.hbsi.dao
UserDao.java
package com.hbsi.dao; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.hbsi.domain.User; import com.hbsi.utils.DBManager; public class UserDao { public List<User> getAll(){ try{ QueryRunner runner = new QueryRunner(DBManager.getDataSource()); String sql = "select * from user1"; return (List<User>) runner.query(sql,new BeanListHandler(User.class)); }catch(Exception e){ throw new RuntimeException(); } } public User find(String username,String password){ try{ QueryRunner runner = new QueryRunner(DBManager.getDataSource()); String sql = "select * from user1 where username=? and password=?"; Object[] params = {username,password}; return (User) runner.query(sql, params, new BeanHandler(User.class)); }catch(Exception e){ throw new RuntimeException(); } } public User find(String username){ try{ QueryRunner runner = new QueryRunner(DBManager.getDataSource()); String sql = "select * from user1 where username=?"; return (User) runner.query(sql, username, new BeanHandler(User.class)); }catch(Exception e){ throw new RuntimeException(); } } }
User.java
package com.hbsi.domain; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
ZiDong.java
package com.hbsi.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hbsi.dao.UserDao; import com.hbsi.domain.User; public class ZiDong implements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; User user = (User) req.getSession().getAttribute("user"); if(user!=null){ chain.doFilter(req,resp); return; } String username = null; String password = null; Cookie[] cookies = req.getCookies(); for(int i=0;cookies!=null && i<cookies.length;i++){ if(cookies[i].getName().equals("username")){ username = cookies[i].getValue(); } if(cookies[i].getName().equals("password")){ password = cookies[i].getValue(); } } if(username==null && password==null){ chain.doFilter(req, resp); return; } UserDao dao = new UserDao(); User user1 = dao.find(username); String save_password = user1.getPassword(); if(!password.equals(save_password)){ chain.doFilter(req, resp); return; } req.getSession().setAttribute("user",user1); chain.doFilter(req, resp); } public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } }
Login.java
package com.hbsi.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.hbsi.dao.UserDao; import com.hbsi.domain.User; public class Login extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String password=request.getParameter("password"); int autoLoginTime=Integer.parseInt(request.getParameter("autoLoginTime")); UserDao dao=new UserDao(); User user=dao.find(username, password); if(user!=null){ request.getSession().setAttribute("user",user); Cookie cookie1=new Cookie("username",user.getUsername()); Cookie cookie2=new Cookie("password",user.getPassword()); cookie1.setMaxAge(autoLoginTime); cookie2.setMaxAge(autoLoginTime); cookie1.setPath("/DengLu"); cookie2.setPath("/DengLu"); response.addCookie(cookie1); response.addCookie(cookie2); response.sendRedirect("/DengLu/welcome.jsp"); }else{ request.setAttribute("message","用户名密码错误"); request.getRequestDispatcher("/cuowu.jsp").forward(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DBManager.java
package com.hbsi.utils; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DBManager { private static ComboPooledDataSource ds = null; static{ ds = new ComboPooledDataSource("mysql"); } public static DataSource getDataSource(){ return ds; } }
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property> <property name="user">root</property> <property name="password">root</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property> <property name="user">root</property> <property name="password">root</property> <property name="acquireIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </named-config> </c3p0-config>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>ZiDong</filter-name> <filter-class>com.hbsi.filter.ZiDong</filter-class> </filter> <filter-mapping> <filter-name>ZiDong</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>Login</servlet-name> <servlet-class>com.hbsi.servlet.Login</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet/Login</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
zhu.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'zhu.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/servlet/Login" method="post"> 用户名:<input type="text" name="username"><br/> 密码:<input type="password" name="password"><br/> 有效期:<input type="radio" name="autoLoginTime" value="${60*60}">1小时 <input type="radio" name="autoLoginTime" value="${10*60}">10分钟 <input type="radio" name="autoLoginTime" value="120">2分钟<br/> <input type="submit" value="登陆"> </form> </body> </html>
welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'welcome.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 欢迎用户${user.username}登陆 </body> </html>
cuowu.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cuowu.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 登陆错误,请检查用户名密码是否正确! </body> </html>
登陆成功提示界面:
关闭浏览器,然后再次打开浏览器输入网址:
http://localhost:8080/DengLu/welcome.jsp