宿舍管理系统之登录功能
实现宿舍管理系统的登录功能,用户输入账号、密码和勾选用户角色点击登录,前端页面将用户输入的账号、密码等信息采用异步的方式提交到服务器上。后端将用户的输入的信息与数据库中的用户表进行对比查找,根据查找的结果来判断用户输入的信息是否正确。
1、准备工作
(1)编写实体类
实体类的属性对应表的字段。
表结构
实体类代码
package com.lwg.pojo;
public class User {
private int userId;
private String userName;
private String password;
private String nature;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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;
}
public String getNature() {
return nature;
}
public void setNature(String nature) {
this.nature = nature;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", nature='" + nature + '\'' +
'}';
}
}
(2)编写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>
<!-- 控制台打印执行的sql语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/> <!--数据库依赖-->
<property name="url" value="${url}"/> <!--数据库连接地址-->
<property name="username" value="${username}"/> <!--数据库名字-->
<property name="password" value="${password}"/> <!--数据库密码-->
</dataSource>
</environment>
</environments>
<mappers>
<!-- 加载映射文件,写映射文件的路径-->
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
(3)创建并编写UserMapper接口,实现与UserMapper.xml映射文件的对应。
package com.lwg.dao;
import com.lwg.pojo.User;
import java.util.List;
import java.util.Map;
public interface UserMapper {
User selectByUser(User user);//登录功能只使用到这个方法。
List<User> selectUserNames();
int updatePassword(Map<Object,Object> map);
int insertUser(User user);
List<User> selectUserNameByUserName(String name);
User selectUserId(String userName);
}
(4)创建编写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.lwg.dao.UserMapper">
<resultMap id="UserMap" type="User">
<id column="user_id" property="userId" />
<result column="user_name" property="userName" />
</resultMap>
<insert id="insertUser">
insert into USER(user_name,password,nature) values (#{userName},#{password},1)
</insert>
<update id="updatePassword">
update USER set password=#{password} where user_id=#{userId}
</update>
<select id="selectByUser" resultMap="UserMap">
select * from USER where user_name=#{userName} and password=#{password} and nature=#{nature}
</select>
<select id="selectUserNames" resultMap="UserMap">
SELECT * FROM USER WHERE nature='0'
</select>
<select id="selectUserNameByUserName" resultMap="UserMap">
select * from USER where user_name=#{name} and nature='1'
</select>
<select id="selectUserId" resultMap="UserMap">
select * from USER where user_name=#{userName}
</select>
</mapper>
(5)工具类的引入
引入SqlSessionFactoryUtils工具类,是MyBatis的工具类,引用配置文件的类。
package com.lwg.uitl;
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 {
public static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
引入VerifyCodeUtils工具类,生成随机验证码
package com.lwg.uitl;
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 VerifyCodeUtils {
// 可自定义验证码字符源
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNOPQRSTUVWXYZ";
/**
* 使用系统默认字符源生成验证码
* @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 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 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();
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);
Paint linearPaint = new LinearGradientPaint(0, 0, w, h, fractions, colors);
Paint linearPaint2 = new LinearGradientPaint(0, 0, w, h, new float[]{0.3f, .6f, .8f, .9f}, new Color[]{Color.BLUE, Color.BLACK, Color.GREEN, Color.BLUE});
//设置图片背景为白色
g2.setPaint(Color.WHITE);
g2.fillRect(0, 0, w, h);
//设置图片渐变背景
g2.setPaint(linearPaint);
g2.fillRoundRect(0, 0, w, h, 5, 5);
g2.setPaint(linearPaint2);
int fontSize = (int) (Math.min(w/verifySize, h));
Font font = new Font("微软雅黑", Font.BOLD, 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 / verifySize) * i, h/2 + fontSize /2);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
public static void main(String[] args) throws IOException{
File dir = new File("F:/verifies");
int w = 200, h = 80;
for(int i = 0; i < 100; i++){
String verifyCode = generateVerifyCode(4);
File file = new File(dir, verifyCode + ".jpg");
outputImage(w, h, file, verifyCode);
}
}
}
2、编写dao层,编写sql语句
<select id="selectByUser" resultMap="UserMap">
select * from USER where user_name=#{userName} and password=#{password} and nature=#{nature}
</select>
3、编写service层,创建并UserService类
package com.lwg.service;
import com.lwg.dao.UserMapper;
import com.lwg.pojo.User;
import com.lwg.uitl.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import javax.jws.soap.SOAPBinding;
import java.util.List;
import java.util.Map;
public class UserService {
static SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
public static User selectUser(User user){
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User selectByUser = mapper.selectByUser(user);
sqlSession.close();
return selectByUser;
}
}
4、编写view层,创建并编写UserServlet类
package com.lwg.view;
import com.alibaba.fastjson.JSON;
import com.lwg.pojo.Dormitory;
import com.lwg.pojo.User;
import com.lwg.service.DormitoryService;
import com.lwg.service.HouseparentService;
import com.lwg.service.UserService;
import javax.servlet.ServletException;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/json;charset=utf-8");
String operation = req.getParameter("operation");
if("change".equals(operation)){
int userId = Integer.parseInt(req.getParameter("userId"));
String newPassWord = req.getParameter("newPassWord");
Map<Object,Object> map=new HashMap<>();
map.put("password",newPassWord);
map.put("userId",userId);
int result = UserService.updataPassword(map);
String msg="";
if(result>0){
HttpSession session = req.getSession();
session.invalidate();
msg="密码修改成功,请重新登录";
}
else {
msg="密码修改失败";
}
Map<String,String> resultMap=new HashMap<>();
resultMap.put("msg",msg);
String jsonString = JSON.toJSONString(resultMap);
resp.getWriter().write(jsonString);
return;
}
if("register".equals(operation)){
String userName = req.getParameter("userName");
String password = req.getParameter("password");
String code = req.getParameter("code");
HttpSession session = req.getSession();
String registerCode = (String) session.getAttribute("registerCode");
if(registerCode.equals(code)){
User user=new User();
user.setUserName(userName);
user.setPassword(password);
int result = UserService.addUser(user);
String msg="";
if(result>0){
msg="注册成功,请登录";
req.setAttribute("msg",msg);
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
else {
msg="注册失败,请重试";
req.setAttribute("registerMsg",msg);
req.getRequestDispatcher("register.jsp").forward(req,resp);
}
}
else {
String msg="验证码不正确,请重新输入";
req.setAttribute("registerMsg",msg);
req.getRequestDispatcher("register.jsp").forward(req,resp);
}
return;
}
if("verification".equals(operation)){
String paramName = req.getParameter("paramName");
List<User> users = UserService.selectUserName(paramName);
boolean resutl=true;
if(users.size()>0){
resutl=false;
}
String jsonString = JSON.toJSONString(resutl);
resp.setContentType("text/json;charset=utf-8");
resp.getWriter().write(jsonString);
return;
}
String id = req.getParameter("id");
String jsonString="";
if(id.equals("1")){
List<User> users = UserService.selectAllHouseparentUser();
jsonString = JSON.toJSONString(users);
}
if(id.equals("2")){
int dormitoryId=0;
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
String nature = user.getNature();
if("0".equals(nature)){
List<Integer> list = HouseparentService.selectDormitoryId(user.getUserId());
if(list.size()!=0){
dormitoryId=list.get(0);
}
}
List<Dormitory> dormitories = DormitoryService.selectAllDormitory(dormitoryId);
jsonString = JSON.toJSONString(dormitories);
}
resp.getWriter().write(jsonString);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
}
5、编写前端页面
<%--
Created by IntelliJ IDEA.
User: 35173
Date: 2022/6/6
Time: 11:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>登录</title>
<%@include file="easyuiHeads.jsp"%>
<style>
a{
text-decoration: none;
}
</style>
</head>
<body>
<div class="easyui-dialog" data-options="title:'宿舍管理系统',width:380, height:330,closable:false,">
<div style="margin-top: 10px;padding-left: 95px;height: 18px;color: #ff0000;" id="msg_login">
${msg}
</div>
<form style="margin: auto;margin-top:10px;position: absolute;left: 60px;" id="form_login" method="post" action="${pageContext.request.contextPath}/loginServlet">
<input style="" type="text" name="userName" class="easyui-textbox" data-options="prompt:'用户名'," value="${cookie.userName.value}"><br /><br />
<input type="text" name="password" class="easyui-passwordbox" data-options="prompt:'密码'," value="${cookie.password.value}"><br /><br />
<input class="easyui-radiobutton" data-options="label:'系统管理员',labelAlign:'left',labelPosition:'after'" name="nature" value="-1" <c:if test="${cookie.nature.value eq '-1'}">checked="checked"</c:if> >
<input class="easyui-radiobutton" data-options="label:'宿舍管理员',labelAlign:'left',labelPosition:'after'" name="nature" value="0" <c:if test="${cookie.nature.value eq '0'}">checked="checked"</c:if>>
<input class="easyui-radiobutton" data-options="label:'学生',labelAlign:'left',labelPosition:'after'" name="nature" value="1" <c:if test="${cookie.nature.value eq '1'}">checked="checked"</c:if>><br /><br />
<input class="easyui-checkbox" data-options="label:'记住我',labelPosition:'after'" name="remember" value="1"><br />
<a href="javascript:void(0)" class="easyui-linkbutton" data-options="width:200,onClick:signIn" style="margin-left: 30px;margin-top: 20px;margin-bottom: 10px;">登录</a><br />
<a href="register.jsp">学生注册</a>
</form>
</div>
<script>
$(document).ready(function () {
$('.textbox').css({
"margin-left": "42px",
})
})
function signIn() {
$('#form_login').form('submit');
}
$('#form_login').form({
success:function (data) {
var msg=JSON.parse(data);
var code=msg.code;
var fealSituation=msg.fealSituation;
var nature=msg.nature;
if(code=="200"){
if(nature =="1" && fealSituation=="400"){
$.messager.alert({
title:'提示',
msg:'您的账号还没绑定学号,请绑定!',
fn:function () {
$(location).attr("href","${pageContext.request.contextPath}/realName.jsp");
}
})
return;
}
$(location).attr("href","${pageContext.request.contextPath}/index.jsp");
}
else {
var mess=document.getElementById("msg_login");
var text=msg.msg;
mess.innerText=text;
}
}
})
</script>
</body>
</html>
6、实现拦截功能
当用户未登录时,无法浏览网页,跳转到登录页面。使用拦截器拦截所有的访问请求,判断session里面是否有登录信息,如有则放行所有请求,如无,则拦截用户请求,只放行登录页面和请求样式图片资源请求这些。
package com.lwg.view;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebFilter("/*")
public class SignFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest= (HttpServletRequest) request;
String[] strings=new String[]{"/register.jsp","/login","/easyui/","/easyuiHeads.jsp","/codeServlet","/userServlet"};
String requestURL = httpServletRequest.getRequestURL().toString();
for (String s:strings
) {
if(requestURL.contains(s)){
chain.doFilter(request,response);
return;
}
}
HttpSession session = httpServletRequest.getSession();
Object user = session.getAttribute("user");
if(user==null){
httpServletRequest.setAttribute("msg","你还未登录,请登录");
httpServletRequest.getRequestDispatcher("login.jsp").forward(httpServletRequest,response);
}
else {
chain.doFilter(request,response);
}
}
@Override
public void destroy() {
}
}
效果图
{
if(requestURL.contains(s)){
chain.doFilter(request,response);
return;
}
}
HttpSession session = httpServletRequest.getSession();
Object user = session.getAttribute(“user”);
if(user==null){
httpServletRequest.setAttribute(“msg”,“你还未登录,请登录”);
httpServletRequest.getRequestDispatcher(“login.jsp”).forward(httpServletRequest,response);
}
else {
chain.doFilter(request,response);
}
}
@Override
public void destroy() {
}
}
效果图