目录
需求说明:
- 完成用户登录功能,如果用户勾选“记住用户” ,则下次访问登录页面自动填充用户名密码
- 完成注册功能,并实现验证码功能
书写案例(完整版)
准备文件
user
package com.itheima.pojo;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
验证码工具类 UserService
package com.itheima.service;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* @author wzq
* @date 2022-08-15 17:04
* @description:
* @version:
*/
public class UserService {
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
/*
* 登录的方法
* @param username
* @param password
* @return
* */
public User login(String username, String password) {
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3. 获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4. 调用方法
User user = mapper.select(username, password);
//5. 释放资源
sqlSession.close();
return user;
}
/*
* 注册的方法
* @return
* */
public boolean register(User user) {
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3. 获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4.判断用户名是否存在
User u = mapper.selectByUsername(user.getUsername());
if (u == null) {
//用户名不存在,注册
mapper.add(user);
sqlSession.commit();
}
sqlSession.close();
return u == null;
}
}
mapper 类 UserMapper
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/**
* 根据用户名和密码查询用户对象
* @param username
* @param password
* @return
*/
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
/**
* 根据用户名查询用户对象
* @param username
* @return
*/
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);
/**
* 添加用户
* @param user
*/
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
</mapper>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--起别名-->
<typeAliases>
<package name="com.itheima.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="hsp"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
用户登录
1.用户登录页面jsp提示
2.重定义的运用
解释:
JavaEE-重定向(redirect)response.sendRedirect("test.jsp");
重定向是一个客户端行为,用户请求到达服务器之后,服务器返回响应,HTTP状态码置为302,并将转发的页面保存在响应头中的Location属性中,告诉客户端应该向这个地址发出请求,然后客户端再次发出请求。
通俗来讲:
A找B借钱,B说我没有,你去找C借去吧,A收到B的消息,然后去找C借钱
由于在重定向中会使用到虚拟目录,直接写死虚拟目录可能会发生一些问题;
所以我们一般先使用request对象的getContextPath()方法获取虚拟目录;
String contextPath = request.getContextPath();
然后再使用重定向;
response.sendRedirect(contextPath + “不带虚拟路径的绝对路径”);
使用
//待用虚拟目录 request.getContextPath();
//或者: String contextPath=request.getContextPath()
3.1用户登录页面操作定义显示用户名
记住用户
自动填充用户名和密码
- 将用户名和密码写入Cookie中,并且持久化存储Cookie ,下次访问浏览器会自动携带Cookie
- 在页面获取Cookie数据后,设置到用户名和密码框中
- 登录成功
- 用户勾选记住用户复选框
浏览器上演示 记住用户 -- 获取Cookie
- 将用户名和密码写入Cookie中,并且持久化存储Cookie ,下次访问浏览器会自动携带Cookie
- 在页面获取Cookie数据后,设置到用户名和密码框中:
- ${cookie.key.value} // key指存储在cookie中的键名称
1.用户名和密码错误,没有cookie
2.不勾选记住我 ,没有cookie
3.正确,加勾选
4.再次点开,浏览器进入登录页面
if比较的书写(防止空指针)
记住用户value来判断是否点击记住我
用户登录和记住用户的代码
login.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/15
Time: 19:04
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
<form action="/brand-demo/loginServlet" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<div id="errorMsg">${login_msg} ${register_msg}</div>
<p>Username:<input id="username" name="username" value="${cookie.username.value}" type="text"></p>
<p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>
<p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.jsp">没有账号?</a>
</div>
</form>
</div>
</body>
</html>
loginServlet
package com.itheima.web;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//获取复选框数据
String remember = request.getParameter("remember");
//2. 调试service查询
User user = service.login(username, password);
//3.判断
if (user != null) {
//登录成功,跳转到查询索所有的BrandServlet
//判断用户是否勾选记住我
// if (remember.equals("1"))
if ("1".equals(remember)) {
//勾选了,发送Cookie对象
//1.创建Cookie对象
Cookie c_username = new Cookie("username", username);
Cookie c_password = new Cookie("password", password);
//设置Cookie的存活时间(一周)
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
//2.发送
response.addCookie(c_username);
response.addCookie(c_password);
}
//将登录成功后的user对象,存储到session ,数据共享,并且安全性
HttpSession session = request.getSession();
session.setAttribute("user",user);
// response.sendRedirect("/brand-demo/selectAllServlet");
// 虚拟目录 + 重定向
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/selectAllServlet");
}else {
//登录失败
//存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
// 跳转到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
注册功能:保存用户信息到数据库
if的boolean的书写格式
页面显示不出来错误原因
注册成功
注册案例 -- 展示验证码
为什么写验证码原因
在工具类中验证码调用方法
用时间来记录验证码的缓存
document.getElementById("changeImg").onclick = function () {
// new Date().getMilliseconds();
document.getElementById("checkCodeImg").src = "/brand-demo/checkCodeServlet?" + new Date().getMilliseconds();
}
<img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
<a href="#" id="changeImg" >看不清?</a>
点击图片也可以改变验证码
window.onload = function(){
//1.获取图片对象
var img = document.getElementById("checkCodeImg");
//2.绑定单击事件
img.onclick = function(){
//加时间戳
var date = new Date().getTime();
img.src = "/brand-demo/checkCodeServlet?"+date;
}
}
<img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
<a href="#" id="changeImg" >看不清?</a>
注册和验证码的代码
register.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/8/17
Time: 14:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="/brand-demo/registerServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg">${register_msg}</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
<a href="#" id="changeImg" >看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
document.getElementById("changeImg").onclick = function () {
// new Date().getMilliseconds();
document.getElementById("checkCodeImg").src = "/brand-demo/checkCodeServlet?" + new Date().getMilliseconds();
}
window.onload = function(){
//1.获取图片对象
var img = document.getElementById("checkCodeImg");
//2.绑定单击事件
img.onclick = function(){
//加时间戳
var date = new Date().getTime();
img.src = "/brand-demo/checkCodeServlet?"+date;
}
}
</script>
</body>
</html>
CheckCodeServlet
package com.itheima.web;
import com.itheima.util.CheckCodeUtil;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//生成验证码
ServletOutputStream os = response.getOutputStream();
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
// 存入Session
HttpSession session = request.getSession();
session.setAttribute("checkCodeGen",checkCode);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
RegisterServlet
package com.itheima.web;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 获取用户名和密码数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装成一个对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
//获取用户输入的验证码
String checkCode = request.getParameter("checkCode");
//获取程序生成的验证码,从Session获取
HttpSession session = request.getSession();
String checkCodeGen = (String) session.getAttribute("checkCodeGen");
//比对
if (!checkCodeGen.equalsIgnoreCase(checkCode)){
//错误提示
request.setAttribute("register_msg","验证码错误");
request.getRequestDispatcher("/register.jsp").forward(request, response);
//不允许注册,直接返回
return;
}
//2.调用service 注册
boolean flag = service.register(user);
//3.判断注册成功与否
if(flag){
//注册成功,跳转登陆页面
request.setAttribute("register_msg","注册成功,请登录");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}else {
//注册失败,跳转到注册页面
request.setAttribute("register_msg","用户名已存在");
request.getRequestDispatcher("/register.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}