Application of user password encryption and interceptor

Keywords: JSON Spring Java JQuery

Front-end code

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>register</title>
</head>
<body>
<script>
    function test(){
        var formObject = {};
        var form = $("#myForm").serializeArray();
        $.each(form,function(i,item){
            formObject[item.name] = item.value;
        });
        var data=JSON.stringify(formObject);
        alert(data);
        $.ajax({
			url:'${pageContext.request.contextPath}/registerUser.action',
			type:'post',
            // Data indicates the data sent
			data:data,
            // Define the data format of sending request as JSON string
            contentType : "application/json;charset=UTF-8",
            //The data format of the defined callback response is JSON string, which can be omitted
            dataType : "json",
            //Results of successful response
            success : function(data){
                if(data != null){
                    alert("User information"+data.id+"User name"+data.name+data.age);
                }
                else
				{
                    alert("Add failure");
                }
            },
            error : function(data){
                if(data != null){
                    alert("login has failed");
                }
            }
        })
    }
</script>
	<%--<form action="${pageContext.request.contextPath}/registerUser.action" id="form1" method="post">--%>
<form id="myForm">
		ID Number:<input type="text" name="id" /><br />
		//Secret Code: < input type = "text" name = "password" / > < br / >
	    //Age: < input type = "text" name = "age" / > < br / >
		<input type="button" value="register" id="formDemo" onclick="test()"/>
	</form>
</body>
</html>

The background code encrypts the user.password passed from the front end

//	Form uses json to transfer data from front to back
	@RequestMapping(value="/registerUser.action",method = RequestMethod.POST)
	@ResponseBody
	public User registerUser(@RequestBody User user)
	{
		User user1 = userMapper.selectByPrimaryKey(user.getId());
		if(user1==null)
		{
			//Encrypt Password DigestUtils is spring
			String PasswordSecret= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
			user.setPassword(PasswordSecret);
			userMapper.insert(user);
			user1 = userMapper.selectByPrimaryKey(user.getId());
			String s = user1.toString();
			return user1;
		}else {
			return null;
		}

	}

Log in after registration
Front end login code

<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="${pageContext.request.contextPath}/js/jquery.js"></script>
<title>User login</title>
</head>
<body>
<script>
    function login(){
        var formObject = {};
        var form = $("#login").serializeArray();
        $.each(form,function(i,item){
            formObject[item.name] = item.value;
        });
        var data=JSON.stringify(formObject);
        alert(data);
        $.ajax({
            url:'${pageContext.request.contextPath}/login.action',
            type:'post',
            // Data indicates the data sent
            data:data,
            // Define the data format of sending request as JSON string
            contentType : "application/json;charset=UTF-8",
            //The data format of the defined callback response is JSON string, which can be omitted
            dataType : "json",
            //Results of successful response
            success : function(data){
                if(data != null){
                    alert("Landing successfully");
                    window.location.href = "${pageContext.request.contextPath}/ToMain.action";
                }
                else
                {
                    alert("Login failed 1");
                }
            }
        })
    }
</script>
    ${msg}
	<form id="login">
		//User name: < input type = "text" name = "Id" / > < br / >
		//Secret Code:
                 <input type="password" name="password"/><br />
		<input type="button" value="Sign in" onclick="login()"/>
	</form>


</body>
</html>

Background login verification code

//Verify user login information code
	@RequestMapping(value="/LoignUser.action",method = RequestMethod.GET)
	@ResponseBody
	public String TestLoginUser(String name)
	{
		String NameSecret=DigestUtils.md5DigestAsHex(name.getBytes());
        UserExample userExample=new UserExample();
        userExample.or().andNameEqualTo(NameSecret);
		List<User> users = userMapper.selectByExample(userExample);
		return  users.toString();
	}

Interceptor
The Interceptor in Spring MVC is similar to the Filter in Servlet. It is mainly used to intercept user requests and handle them accordingly. For example, through the Interceptor, we can verify the authority, record the log of request information, and judge whether the user is logged in.
Technological process

Multiple interceptor execution process

First, intercept the login, and intercept the users who are not logged in.

First, configure the interceptor in spring MVC

		<!--SpringMVC Interceptor-->
		<mvc:interceptors>
			<!-- Multiple interceptors -->
			<mvc:interceptor>
				<mvc:mapping path="/**"/>
				<!-- Custom interceptor class -->
				<!--Excluded paths-->
				<!--<mvc:exclude-mapping path="/ToEditUser.action"/>-->
				<bean class="com.lzm.interceptor.Interceptor1"/>
			</mvc:interceptor>
		</mvc:interceptors>

Interceptor class

package com.lzm.interceptor;


import com.lzm.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Interceptor1 implements HandlerInterceptor{

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		String requestURI = request.getRequestURI();
		if(!requestURI.contains("login")){
			User user = (User) session.getAttribute("user");
			if (null == user) {
//	/No login, turn to login interface
				request.getRequestDispatcher("/Tologin.action").forward(request,response);
				return false;
			}
		}
		return true;
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("Method 1");
		
	}
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("1 after page rendering");
		
	}



}

Posted by programmer79 on Fri, 01 Nov 2019 11:09:42 -0700