[JavaWeb] 登录页面记住密码,账号或密码错误

 ✨✨个人主页:沫洺的主页

📚📚系列专栏: 📖 JavaWeb专栏📖 JavaSE专栏 📖 Java基础专栏📖vue3专栏 

                           📖MyBatis专栏📖Spring专栏📖SpringMVC专栏📖SpringBoot专栏

                           📖Docker专栏📖Reids专栏📖MQ专栏📖SpringCloud专栏     

💖💖如果文章对你有所帮助请留下三连✨✨

🌈登录页面优化

🎨代码优化

使用Java Web 三层架构模式(Web+Service +Dao/Mapper)优化代码框架

具体优化:

  • 📌遵循三层架构的分层思想模式,目的是为了“高内聚低耦合”
  • 📌Web表现层主要是指与用户交互的界面。用于接收用户输入的数据和显示处理后用户需要的数据
  • 📌Service业务逻辑层是通过数据访问层拿到存在数据库里的原始数据,然后再对数据进行逻辑上的处理,比如说验证。
  • 📌Dao数据访问层的代码都是对数据库数据的“增删改查”,将存储在数据库中的数据提交给业务层,同时将业务层处理的数据保存到数据库。
  • 📌util包: 对MyBatis获取工厂进行工具封装到util包下,方便开发,提高代码复用性
  • 📌对前端代码进行调整, 通过jsp对el表达式进行展示,与Web层结合实现具体功能

🎨Web层

🔎LoginServlet

package com.moming.web;

import com.moming.pojo.User;
import com.moming.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    UserService userService= new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //1.接收用户信息
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //获取复选框数据
        String remeber = request.getParameter("remeber");
        //调用service层获取结果
        User user = userService.login(username, password);
        response.setContentType("text/html;charset=utf-8");
        if(user!=null){
            //判断用户是否勾选记住密码
            //创建cookie对象
            //Cookie c_username = new Cookie("username", username);
            //URLEncoder.encode(username,"utf-8")解决账号是中文乱码
            Cookie c_username = new Cookie("username", URLEncoder.encode(username,"utf-8"));
            Cookie c_password = new Cookie("password", password);
            //访问此路径下的都带cookie
            c_username.setPath("/moming");
            c_password.setPath("/moming");
            if("1".equals(remeber)){
                //设置cookie存活时间一天
                c_username.setMaxAge(60*60*24);
                c_password.setMaxAge(60*60*24);
            }else {
                //销毁cookie
                c_username.setMaxAge(0);
                c_password.setMaxAge(0);
            }
            //发送cookie
            response.addCookie(c_username);
            response.addCookie(c_password);
            //将登录成功的user对象存储到session中
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            //存在,登录成功,跳转Servlet
            String contextPath = request.getContextPath();
            //重定向
            response.sendRedirect(contextPath+"/successServlet");
        }else {
            //不存在,登录失败,跳转的登录页面
            request.setAttribute("msg", "用户名或密码错误");
            //转发
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

🔎SuccessServlet

package com.moming.web;

import com.moming.pojo.User;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //获取session数据
        User user =(User) session.getAttribute("user");
        request.setAttribute("msg", "登录成功,欢迎"+user.getUsername());
        request.getRequestDispatcher("/success.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

🎨Service层

🔎UserService

package com.moming.service;

import com.moming.mapper.UserMapper;
import com.moming.pojo.User;
import com.moming.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class UserService {
    //通过工具类获取工厂对象
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    public User login(String username,String password){
        //获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //获取mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用dao层
        User user = mapper.selectUser(username, password);
        sqlSession.close();
        return user;
    }
}

🎨util工具包

🔎SqlSessionFactoryUtils

package com.moming.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 SqlSessionFactoryUtils() {
    }

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //1.加载mybatis的核心配置文件,获取SqlSessionFactory
            //定义配置文件的路径
            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;
    }
}

🎨前端代码

🔎login.css

* {
    margin: 0;
    padding: 0;
}

html {
    height: 100%;
    width: 100%;
    overflow: hidden;
    margin: 0;
    padding: 0;
    background: url(../imgs/img.png) no-repeat 0px 0px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    -moz-background-size: 100% 100%;
}

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

#loginDiv {
    width: 37%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: rgba(255, 255, 255, 0.27);
    box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
    border-radius: 5px;
}

p {
    margin-top: 20px;
    margin-left: 20px;
}

#username{
    margin-left: 15px;
    border-radius: 5px;
    border-style: hidden;
    height: 30px;
    width: 140px;
    outline: none;
    padding-left: 10px;
}
#password{
    margin-left: 15px;
    border-radius: 5px;
    border-style: hidden;
    height: 30px;
    width: 140px;
    outline: none;
    padding-left: 10px;
}
#remeber{
    margin-left: 15px;
    border-radius: 5px;
    border-style: hidden;
    height: 15px;
    width: 40px;
    outline: none;
    padding-left: 10px;
}
#username{
    width: 200px;
}
#password{
    width: 202px;
}
.button {
    border-color: cornsilk;
    background-color: #5a88c8;
    color: aliceblue;
    border-style: hidden;
    border-radius: 5px;
    width: 100px;
    height: 31px;
    font-size: 16px;
}

#subDiv {
    text-align: center;
    margin-top: 30px;
}
#loginMsg{
    text-align: center;
    color: black;
}
#errorMsg{
    text-align: center;
    color:red;
}

🔎login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link href="css/login.css" rel="stylesheet">
</head>

<body>
<div id="loginDiv">
    <form action="/moming/loginServlet" method="post" id="form">
        <h1 id="loginMsg">登录页面</h1>
        <div id="errorMsg">${msg}</div>
        <p>账号:<input id="username" name="username"  type="text"></p>
        <p>密码:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>
        <p>记住密码:<input id="remeber" name="remeber" value="1" ${cookie.username.value!=null?'checked':''} type="checkbox"></p>
        <div id="subDiv">
            <input type="submit" class="button" value="登录">
            <a href="register.html">没有账号?点击注册</a>
        </div>
    </form>
</div>
<script>
    let v = decodeURI('${cookie.username.value}');
    document.getElementById("username").value=v;
</script>
</body>
</html>

🔎success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>${msg}</h1>
</body>
</html>

💦总结说明

对于登录页面的优化有一个注意点就是将原来的login.html改为了login.jsp页面,目的是为了支持el表达式,通过优化代码了解JavaWeb三层架构模式,同时了解CookieSession的区别与使用方式,实现记住密码和页面数据共享,还有就是重定向转发的使用,下一步就是对注册页面的优化

  • 5
    点赞
  • 65
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沫洺

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值