Servlet系列学习笔记7 --- Cookie + Session + MVC实现免登录实例

目录

一、实现效果

二、项目结构

三、模型

四、数据访问

五、数据控制

       5.1 登录检验

       5.2 访问检验

六、页面视图

       6.1 登录页面

       6.2 数据展示页面


一、实现效果

二、项目结构

       

三、模型

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>

 

已标记关键词 清除标记
相关推荐
\contentsline {chapter}{Contents}{2}{section*.1} {1}Java基础}{17}{chapter.1} {1.1}基本语法}{17}{section.1.1} {1.2}数字表达方式}{17}{section.1.2} {1.3}补码}{19}{section.1.3} {1.3.1}总结}{23}{subsection.1.3.1} {1.4}数据类型}{23}{section.1.4} {1.4.1}整数与浮点数}{23}{subsection.1.4.1} {1.4.1.1}浮点数原理}{24}{subsubsection.1.4.1.1} {1.4.2}格式化输出浮点数}{24}{subsection.1.4.2} {1.4.3}\texttt {char}}{24}{subsection.1.4.3} {1.4.4}转义字符}{25}{subsection.1.4.4} {1.4.5}Boolean 布尔值}{25}{subsection.1.4.5} {1.5}基本类型变量的初始值}{26}{section.1.5} {1.6}数据类型转换}{26}{section.1.6} {1.7}方法}{26}{section.1.7} {1.8}运算符}{27}{section.1.8} {1.8.1}自增运算}{28}{subsection.1.8.1} {1.8.1.1}Postincrement}{28}{subsubsection.1.8.1.1} {1.8.1.2}Preincrement}{28}{subsubsection.1.8.1.2} {1.8.1.3}复合赋值运算}{28}{subsubsection.1.8.1.3} {1.8.2}逻辑运算}{29}{subsection.1.8.2} {1.8.3}条件运算符}{29}{subsection.1.8.3} {1.8.4}移位运算符}{30}{subsection.1.8.4} {1.9}流程控制}{31}{section.1.9} {1.9.1}\texttt {if\ldots esle\ldots }}{31}{subsection.1.9.1} {1.9.2}\texttt {switch}}{31}{subsection.1.9.2} {1.9.3}\texttt {while}}{32}{subsection.1.9.3} {1.9.4}\texttt {for}}{32}{subsection.1.9.4} {1.9.5}foreach}{32}{subsection.1.9.5} {1.9.6}go-to}{33}{subsection.1.9.6} {1.9.7}\texttt {do-while}}{33}{subsection.1.9.7} {1.10}数组(array)}{34}{section.1.10} {1.10.1}数组变量的声明}{34}{subsection.1.10.1} {1.10.2}数组变量的初始化}{34}{subsection.1.10.2} {1.10.3}数组对象的引用}{35}{subsection.1.10.3} {1.10.4}数组对象的复制}{35}{subsection.1.10.4} {1.10.5}扩充数组对象长度}{36}{subsection.1.10.5} {1.10.6}Problems}{37}{subsection.1.10.6} {1.11}简单算法}{38}{section.1.11} {1.11.1}打乱算法}{38}{subsection.1.11.1} {1.11.2}排序算法}{38}{subsection.1.11.2} {1.11.2.1}选择排序}{38}{subsubsection.1.11.2.1} {1.11.2.2}冒泡排序}{39}{subsubsection.1.11.2.2} {1.11.2.3}插入排序}{40}{subsubsection.1.11.2.3} {1.11.3}递归调用}{41}{subsection.1.11.3} {1.12}Java API}{41}{section.1.12} {1.13}Linux命令}{41}{section.1.13} {1.13.1}基本查看、移动}{41}{subsection.1.13.1} {1.13.2}权限}{42}{subsection.1.13.2} {1.13.3}打包备份与恢复}{42}{subsection.1.13.3} {1
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页