Day17JavaWeb [tourism project] development function: login with verification code***

learning target

  • (1) Improve login
  • (2) Registration function

MySessionUtils improvements

(1) A depends on B, removes B, and A reports errors, coupling

com \ wzx \ util \ MySessionUtils2.java

 public static <T> T getMapper(Class clz) {
    
    
       return (T) getSession().getMapper(clz);
    }

include tag***

  • (1) include instruction The include instruction is used to introduce other JSP pages in this JSP.
    <%@ include file="relativeURI"%>
    <jsp:include page="header.jsp"/>
    Insert picture description here
<!--引入尾部-->
<div id="footer">
    <%@include file="footer.jsp"%>
</div>

Login_Welcome Message Prompt

Insert picture description here

  • (1) What is the welcome message prompt?
    After the user logs in successfully, the user name displayed at the top of the page
  • (2) Where do you get the data?
    session object
  • (3) Where does the data come from?
    When the login is successful, it is saved in the session object
  • (4) How to take it out and display it?
    el expression and jstl

Insert picture description here
pom.xml

  <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

com\wzx\web\servlet\LoginServlet.java

		 if(code ==  1){
    
    
            info.setData("登录成功");

            //查找出用户数据
           User user = userService.findUserByName(u.getUsername());
           //保存到session中
            request.getSession().setAttribute("user",user);

src\main\webapp\header.jsp

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
        <!-- 登录状态  -->
        <div class="login">
<%--            将session中的用户数据取出来 --%>
<%--            判断用户对象是否为空  如果是提示请登录,否则显示用户信息--%>
    <c:if test="${user != null}">
                <span>欢迎回来,${user.name}</span>
            </c:if>
            <c:if test="${user == null}">
                <span>您未登录,请登录</span>
            </c:if>
            <a href="myfavorite.html" class="collection">我的收藏</a>
            <a href="javascript:;">退出</a>
        </div>

Logout function

  • (1) What is withdrawal?
    You can view the user's personal information in the login status.
    What is login? There are user objects in the session.
    Exit is to delete the session or the user object in the session
    (2) How to achieve?
  • Implementation steps:
    "Access servlet, destroy session
    " Jump to the login page

src\main\webapp\header.jsp
<a href="${pageContext.request.contextPath}/loginOutServlet">退出</a>

com\wzx\web\servlet\LoginOutServlet.java

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
         //查找session
        HttpSession session = request.getSession();
        //让session销毁或者过期
        session.invalidate();
         //重定向 login.jsp
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

Login Improvement_Verification Code Function

  • (1) Why is there a verification code?
    Prevent others from using the program to log in
  • (2) What is the verification code process?
    The background program ASevlet generates random characters code1
    random characters are stored in the session code1
    random characters and then converted into a picture response to the img tag.
    When the user submits the form, the input verification code is also submitted at the same time. code2
    background program B compares whether two random strings are equal. If they are equal, the verification code is wrong.

login.jsp

  <div class="verify">
                    <input name="check" type="text" placeholder="请输入验证码" autocomplete="off">
                    <span><img src="${pageContext.request.contextPath}/checkCode" alt="" onclick="changeCheckCode(this)"></span>
                    <script type="text/javascript">
                        //图片点击事件
                        function changeCheckCode(img) {
     
     
                            img.src="${pageContext.request.contextPath}/checkCode?"+new Date().getTime();
                        }
                    </script>
                </div>

Login.jsp
modify the post request, you need to add a verification code
data:"username="+un+"&password="+pw+"&check="+check,

src\main\java\com\wzx\web\servlet\LoginServlet.java

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        //从请求中获取check1码
        String check1 = request.getParameter("check");
        //从session中获取check2码
        String check2 = (String) request.getSession().getAttribute("CHECKCODE_SERVER");
        System.out.println(check1);
        System.out.println(check2);
        //从session中删除check2码
        request.getSession().removeAttribute("CHECKCODE_SERVER");
        //比较check1 与 check2
        //相同表示验证码不正确,将提示信息写到页面的错误提示
        if(check1 == null || !check1.equalsIgnoreCase(check2)){
    
    
            //验证码不看大小写
            ResponseInfo responseInfo = new ResponseInfo();
            responseInfo.setCode(-4);
            responseInfo.setData("登录失败,验证码出错");

            //json
            String json = new ObjectMapper().writeValueAsString(responseInfo);
            response.getWriter().println(json);
            return;
        }
        //省略验证账号密码

login.jsp

$.ajax({
    
    
                        url:"loginServlet",
                        async:true,
                        data:"username="+un+"&password="+pw+"&check="+check,
                        type:"post",
                        dataType:"json",
                        success:function (data) {
    
    
                           // alert(data)  {"code":1,"data":"登录成功"}
                            if(1 == data.code){
    
    
                                //跳转到主页 index.jsp
                                $("#errorMsg").html("");
                                window.location="index.jsp"
                            }else{
    
    
                                //显示在界面上
                                $("#errorMsg").html(data.data);
                            }
                        },
                        error:function () {
    
    
                            alert("服务器发生了错误")
                        }
                    });

Login improvement_serialize function***

data:$("#loginForm").serialize(),

  • (1) The jquery object serialize function
    splices the form data intokey1=val1&key2=val2
    表单对象.serialize()
  • (2) Simplify submission code
    (3) Ajax request function
$.post("registerServlet",$(this).serialize(),function (data) {
    
    
})

Guess you like

Origin blog.csdn.net/u013621398/article/details/108862125