Servlet系列学习笔记7 --- Cookie + Session + MVC实现免登录实例
目录
一、实现效果
二、项目结构
三、模型
public class User {
private int id;
private String account; //账号
private String password; //密码
private String name; //姓名
private String sex; //性别
private int age; //年龄
private long phone; //手机号码
private int qq; //QQ
private String email; //邮箱
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public int getQq() {
return qq;
}
public void setQq(int qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
四、数据访问
import java.util.ArrayList;
import java.util.List;
import model.User;
public class UserDao extends BaseDao{
public User loginSeach(String account,String password){
User user = new User();
String sql = "select * from loginMsg where account = ? and password = ?";
con = super.getConnection();
try{
ps = con.prepareStatement(sql);
ps.setString(1, account);
ps.setString(2, password);
super.rs = ps.executeQuery();
if(rs.next()){
System.out.println("【查询到了】");
sql = "select * from users where id = ?";
ps = con.prepareStatement(sql);
ps.setInt(1, rs.getInt("id"));
rs = ps.executeQuery();
if(rs.next()){
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
if(rs.getInt("sex") == 1){
user.setSex("男");
}else{
user.setSex("女");
}
user.setAge(rs.getInt("age"));
user.setPhone(rs.getLong("phone"));
user.setQq(rs.getInt("qq"));
user.setEmail(rs.getString("email"));
}
}else{
user = null;
}
}catch(Exception e) {
throw new RuntimeException(e);
}finally{
super.closeAll(rs, ps, con);
}
return user;
}
}
五、数据控制
5.1 登录检验
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.UserDao;
import model.User;
public class LoginService extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(5);
String account = request.getParameter("account");
String password = request.getParameter("password");
if(judge(account,password)){
UserDao ud = new UserDao();
User user = ud.loginSeach(account, password);
if(user!=null){
session.setAttribute("user", user);
Cookie cAccount = new Cookie("account",account);
Cookie cPassword = new Cookie("password",password);
cAccount.setMaxAge(30);
cPassword.setMaxAge(30);
response.addCookie(cAccount);
response.addCookie(cPassword);
response.sendRedirect("index.jsp");
}else{
request.setAttribute("error","账号或密码错误");
response.sendRedirect("login.jsp");
}
}else{
System.out.println("【账号或密码不符合格式】");
request.setAttribute("error","账号或密码不符合格式");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
//后台验证格式是否错误
public boolean judge(String account,String password){
String regex = "[0-9A-Za-z]{6,12}$";
boolean AccReg = account.matches(regex);
boolean PassReg = password.matches(regex);
if(AccReg == true && PassReg == true){
return true; //匹配成功
}else{
return false; //匹配失败
}
}
}
5.2 访问检验
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.UserDao;
import model.User;
@WebServlet("/visit")
public class VisitService extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession(true);
session.setMaxInactiveInterval(5);
if(session.isNew()){
Cookie[] cookies = null;
try{
cookies = request.getCookies();
}catch(Exception e){
response.sendRedirect("login.jsp");
}
if(cookies == null||cookies.length == 0){
response.sendRedirect("login.jsp");
}else{
String account="",password="";
for (int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].getName() + " : " + cookies[i].getValue() + " ");
if ("account".equals(cookies[i].getName())) {
account = cookies[i].getValue();
cookies[i].setMaxAge(5);
}else if ("password".equals(cookies[i].getName())) {
password = cookies[i].getValue();
cookies[i].setMaxAge(5);
}
}
UserDao ud = new UserDao();
User user = ud.loginSeach(account, password);
if(user!=null){
session.setAttribute("user", user);
response.sendRedirect("index.jsp");
}else{
response.sendRedirect("login.jsp");
}
}
}else{
response.sendRedirect("index.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
六、页面视图
6.1 登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>用户登录界面</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="loginService" method="post">
用户名:<input type="text" name="account"/><br/>
密 码:<input type="password" name="password"/>
${request.getAttribute("erroy")}
<input type="submit" value="提交"/>
</form>
</body>
</html>
6.2 数据展示页面
<%@ page language="java" import="model.User" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>首页</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<table border="1" cellspacing="0" cellpadding="10">
<tr>
<th>ID编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>手机号码</th>
<th>QQ</th>
<th>邮箱</th>
</tr>
<tr>
<td><%=((User)session.getAttribute("user")).getId()%></td>
<td><%=((User)session.getAttribute("user")).getName()%></td>
<td><%=((User)session.getAttribute("user")).getSex()%></td>
<td><%=((User)session.getAttribute("user")).getAge()%></td>
<td><%=((User)session.getAttribute("user")).getPhone()%></td>
<td><%=((User)session.getAttribute("user")).getQq()%></td>
<td><%=((User)session.getAttribute("user")).getEmail()%></td>
</tr>
</table>
<div>Cookie有效时间30秒,Session有效时间5秒.</div>
<div>等待5秒之后,Session过期,当再次访问visit控制器时,不需要登录也能获取到用户信息</div>
</body>
</html>