记住用户信息和信息错误提示
记住用户信息和信息错误提示
用户登录成功后,跳转到列表页面,并在页面上展示当前登录的用户名称用户登录失败后,跳转回登录页面,并在页面上展示对应的错误信息
逻辑如下。
(1) 前端通过表单发送请求和数据给Web层的LoginServlet
(2)在LoginServlet中接收请求和数据[用户名和密码]
(3) LoginServlet接收到请求和数据后,调用Service层完成根据用户名和密码查询用户对象
(4) 在Service层需要编写UserService类,在类中实现login方法,方法中调用Dao层的UserMapper
(5) 在UserMapper接口中,声明一个根据用户名和密码查询用户信息的方法
(6) Dao层把数据查询出来以后,将返回数据封装到User对象,将对象交给Service层(7)Service层将数据返回给Web层
(8)Web层获取到User对象后,判断User对象,如果为Null,则将错误信息响应给登录页面,如果不为Null,则跳转到列表页面,并把当前登录用户的信息存入Session携带到列表页面。
所以首先是dao层,也就是mapper层。我们需要用到这些方法
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user)
当然我们还需要这个实体包装类
package com.jgdabc.pojo;
/**
* 品牌实体类
*/
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Brand() {
}
public Brand(Integer id, String brandName, String companyName, String description) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.description = description;
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
mapper映射的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.jgdabc.mapper.UserMapper">
</mapper>
我们的工具类,我们会一直用到这个
package com.jgdabc.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//静态代码块会随着类的加载而自动执行,且只执行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
mybatis核心配置
<?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>
<settings>
<!-- 开启自动驼峰命名规则映射 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!--起别名-->
<typeAliases>
<package name="com.jgdabc.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///mysql?serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.jgdabc.mapper"/>
</mappers>
</configuration>
service 服务
package com.jgdabc.service;
import com.jgdabc.mapper.UserMapper;
import com.jgdabc.pojo.User;
import com.jgdabc.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class UserService {
public User login(String username,String password)
{
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//调用方法
User user = mapper.select(username, password);
sqlSession.close();
return user;
}
// service里面的注册功能
public boolean register(User user)
{
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User u = mapper.selectByUsername(user.getUsername());
if (u==null)
{
mapper.add(user);
sqlSession.commit();
}
sqlSession.close();
return u == null;
}
}
web层登录
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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">
<form action="/brand-demo01/loginServlet" method="post" id="form">
<h1 id="loginMsg">欢迎登录系统</h1>
<div id="errorMsg" style="color: red" tex >${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" type="password"value="${cookie.password.value}"></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>
Servlet登录
//1. 接收用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
//2. 调用MyBatis完成查询
//2.1 获取SqlSessionFactory对象
/* String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);*/
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4 调用方法
User user = userMapper.select(username, password);
//2.5 释放资源
sqlSession.close();
//获取字符输出流,并设置content type
response.setContentType("text/html;charset=utf-8");
// PrintWriter writer = response.getWriter();
//3. 判断user释放为null
if(user != null){
// 登陆成功
// writer.write("登陆成功");
if("1".equals(remember))
{
Cookie c_username = new Cookie("username", username);
Cookie c_password = new Cookie("password", password);
//设置存活时间
c_username.setMaxAge(60*60*24*7);
c_password.setMaxAge(60*60*24*7);
response.addCookie(c_username);
response.addCookie(c_password);
}
HttpSession session = request.getSession();
session.setAttribute("user",user);
String contextPath = request.getContextPath();
response.sendRedirect("selectAllServlet");
}else {
// //登录失败
request.setAttribute("login_msg","用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
web层注册,在这里我们可以去做一个验证码。
这是我们的工具类
package com.jgdabc.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* 生成验证码工具类
*/
public class CheckCodeUtil {
public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
*
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 使用系统默认字符源生成验证码
*
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
*
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources) {
// 未设定展示源的字码,赋默认值大写字母+数字
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
*
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
*
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
//文件不存在
if (!dir.exists()) {
//创建
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}
/**
* 输出指定验证码图片流
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建颜色集合,使用java.awt包下的类
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
// 设置边框色
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
// 设置背景色
g2.setColor(c);
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
// 设置线条的颜色
g2.setColor(getRandColor(160, 200));
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
// 噪声率
float yawpRate = 0.05f;
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
// 获取随机颜色
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
// 添加图片扭曲
shear(g2, w, h, c);
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
/**
* 随机颜色
*
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
然后我们用Servlet调用这个方法
package com.jgdabc.web.servlet;
import com.jgdabc.util.CheckCodeUtil;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
// 生成验证码
ServletOutputStream os = resp.getOutputStream();
String chexkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
// 存入Session
HttpSession session = req.getSession();
session.setAttribute("checkCodeGen",chexkCode);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
然后我们来看注册的前端
<%@ 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 style="text-align: center">欢迎注册</h1>
<span style="padding-left: 50px" >已有帐号?</span> <a href="login.jsp">登录</a>
</div>
<form id="reg-form" action="/brand-demo01/registerServlet" method="post" >
<table >
<tr >
<td width="100"style="height: 10px">用户名</td>
<td class="inputs">
<input name="username" type="text" id="username" style="margin-right: 65px">
<br>
<span id="username_err" class="err_msg" >${register_msg}</span>
<span id="username_err_1" class = err_msg_1 style="display: none;color: red">用户名已经存在</span>
</td>
</tr>
<tr>
<td width="60"style="height:50px">密码</td>
<td class="inputs">
<input name="password" type="password" id="password" style="margin-right: 65px">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td style="padding-bottom: 70px">验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode" style="margin-right: 65px">
<img id="checkCodeImg" src="/brand-demo01/checkCodeServlet" style="margin-right: 10px">
<a href="#" id="changeImg" >看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn" style="margin-right: 65px;margin-top: 10px" >
</div>
<br class="clear">
</form>
</div>
<script>
//给用户名输入框绑定一个失去焦点的事件
document.getElementById("username").onblur = function ()
{
//
//发送ajax请求
//
var username = this.value;
//创建核心对象
var xhttp;
if(window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 发送请求
xhttp.open("GET"," http://localhost:8080/brand-demo01/selectUserServlet?username="+username)
xhttp.send();
xhttp.onreadystatechange = function ()
{
if(this.readyState == 4 && this.status == 200)
{
// alert(this.responseText);
if(this.responseText=="false")
{
// alert(this.responseText)
document.getElementById("username_err_1").style.display='';
}else {
document.getElementById("username_err_1").style.display='none';
}
}
};
}
</script>
<script>
document.getElementById("changeImg").onclick = function () {
document.getElementById("checkCodeImg").src = "/brand-demo01/checkCodeServlet?"+new Date().getMilliseconds();
}
</script>
</body>
</html>
这里涉及一个异步请求方式
servlet层
//1. 接收用户数据
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkCode = request.getParameter("checkCode");
// System.out.println(checkCode);
HttpSession session = request.getSession();
String checkCodeGen = (String) session.getAttribute("checkCodeGen");
System.out.println(checkCodeGen);
boolean b = checkCodeGen.equalsIgnoreCase(checkCode);
User user = new User();
user.setUsername(username);
user.setPassword(password);
// request.setAttribute("register_msg","用户已经存在");
boolean flag = service.register(user);
//
// System.out.println(flag);
if(!b)
{
System.out.println("比对失败");
request.setAttribute("register_msg","验证码错误,请输入验证码");
request.getRequestDispatcher("/register.jsp").forward(request,response);
return;
}
// //封装用户对象
// User user = new User();
// user.setUsername(username);
// user.setPassword(password);
// boolean flag = service.register(user);
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);
}
- 点赞
- 收藏
- 关注作者
评论(0)