Cookie:
使用Cookie机制实现十天内免登陆:
Servlet程序:
package com.bjpowernode.javaweb.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 检查登录时服务器是否接收到前端页面发送的Cookie,
* 若收到则直接登录,登录成功则跳转到成功页面,登录失败则跳转到失败页面,
* 若没收到则再跳转到登录页面
* @author qjj
*
*/
public class CheckLoginStatusServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//从request中获取所有的Cookie
Cookie[] cookies = request.getCookies();
String username = null;
String password = null;
if(cookies != null){
//遍历Cookie
for(Cookie cookie : cookies){
String cookieName = cookie.getName();
String cookieValue = cookie.getValue();
if("username".equals(cookieName)){
username = cookieValue;
}else if("password".equals(cookieName)){
password = cookieValue;
}
}
} if(username != null && password != null){
//接收到Cookie
//连接数据库验证用户名和密码
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean loginSuccess = false;
String realName = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "248xiaohai");
String sql = "select id,username,password,realname from t_user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs.next()){
loginSuccess = true;
realName = rs.getString("realname");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//登录成功跳转到成功页面,失败跳转到失败页面
if(loginSuccess){
//这里的成功页面已响应的方式发送到前端,是因为有动态参数realname的存在,之后学了JSP就不用这么写了
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>欢迎页面</title>");
out.print("</head>");
out.print("<body>");
out.print("欢迎");
out.print(realName);
out.print("访问");
out.print("</body>");
out.print("</html>");
}else{
response.sendRedirect(request.getContextPath() + "/login_error.html");
}
}else{
//没接收到Cookie,则跳转到登录页面
response.sendRedirect(request.getContextPath() + "/login.html");
}
} }
package com.bjpowernode.javaweb.servlet; import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* 登录页面的响应,登录成功先判断是否选择十天内免登录,若选择则先向浏览器发送Cookie,
* 然后跳转到成功页面
* 若登录失败,则跳转到失败页面
* @author qjj
*
*/
public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置字符编码方式
request.setCharacterEncoding("UTF-8");
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//连接数据库验证用户名和密码
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
boolean loginSuccess = false;
String realName = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "248xiaohai");
String sql = "select id,username,password,realname from t_user where username=? and password=?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs.next()){
loginSuccess = true;
realName = rs.getString("realname");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//登录成功跳转到成功页面,失败跳转到失败页面
if(loginSuccess){
//登陆成功之后,获取用户是否选择了十天内免登陆
String tenDayAutoLoginFlag = request.getParameter("tenDayAutoLoginFlag");
if("ok".equals(tenDayAutoLoginFlag)){
//创建Cookie对象
Cookie cookie1 = new Cookie("username",username);
Cookie cookie2 = new Cookie("password",password);
//设置有效时间
cookie1.setMaxAge(60 * 60 * 24 * 10);
cookie2.setMaxAge(60 * 60 * 24 * 10);
//设置关联路径
cookie1.setPath(request.getContextPath());
cookie2.setPath(request.getContextPath());
//发送Cookie给浏览器
response.addCookie(cookie1);
response.addCookie(cookie2);
} response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("<html>");
out.print("<head>");
out.print("<title>欢迎页面</title>");
out.print("</head>");
out.print("<body>");
out.print("欢迎");
out.print(realName);
out.print("访问");
out.print("</body>");
out.print("</html>");
}else{
response.sendRedirect(request.getContextPath() + "/login_error.html");
}
}
}
前端HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>登录页面</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="/prj-servlet-20/login" method="post">
用户名
<input type="text" name="username">
<br>
密码
<input type="password" name="password">
<br>
<input type="checkbox" name="tenDayAutoLoginFlag" value="ok">十天内免登陆<br>
<input type="submit" value="登录">
</form> </body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<title>登录失败</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> 登录失败,用户名不存在或者密码错误,请<a href="/prj-servlet-20/login.html">重新登录</a> </body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 设置isLogin为欢迎页面 -->
<welcome-file-list>
<welcome-file>isLogin</welcome-file>
</welcome-file-list> <servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.bjpowernode.javaweb.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping> <servlet>
<servlet-name>isLogin</servlet-name>
<servlet-class>com.bjpowernode.javaweb.servlet.CheckLoginStatusServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>isLogin</servlet-name>
<url-pattern>/isLogin</url-pattern>
</servlet-mapping>
</web-app>