SSM (Spring, SpringMVC, MyBatis) user login

Reference tutorial: https://blog.csdn.net/u014427391/article/details/51419521

Web page access process:

1. The website link can only be accessed when the user has successfully logged in;

2. Otherwise, jump to the login page or registration page;

3. Log in successfully and jump to the success page

4. If the login fails, it will remain on the login page

dispatcher-servlet.xml adds the following configuration:

<!-- Interceptor-->  
    <mvc:interceptors>  
        <!-- Multiple interceptors, executed sequentially -->  
        <mvc:interceptor>  
            <mvc:mapping path="/**"/>  
            <bean class="com.qs.interceptor.LoginInterceptor"></bean>  
        </mvc:interceptor>  
    </mvc:interceptors>

 Create the package com.qs.interceptor in the java code and create the class LoginInterceptor

package com.qs.interceptor;

import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;  
  
import org.springframework.web.servlet.HandlerInterceptor;  
import org.springframework.web.servlet.ModelAndView;  
/** 
 * Login authentication interceptor
 */  
public class LoginInterceptor implements HandlerInterceptor{  
  
    /** 
     * Call this method after the Handler is executed
     */  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception exc)  
            throws Exception {  
          
    }  
  
    /** 
     * After the Handler is executed, this method is called before ModelAndView returns
     */  
    public void postHandle(HttpServletRequest request, HttpServletResponse response,  
            Object handler, ModelAndView modelAndView) throws Exception {  
    }  
  
    /** 
     * This method is called before the Handler executes
     */  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
            Object handler) throws Exception {  
         // Get the requested URL   
        String url = request.getRequestURI();  
         // URL:login.jsp is public; this demo is publicly accessible except for login.jsp, other URLs are Intercept control   
        if (url.indexOf("login")>=0 ){  
             return  true ;  
        }  
        //获取Session  
        HttpSession session = request.getSession();  
        String username = (String)session.getAttribute("username");  
          
        if(username != null){  
            return true;  
        }  
        // If the conditions are not met, jump to the login interface   
        request.getRequestDispatcher("/WEB-INF/views/login.jsp" ).forward(request, response);  
          
        return false;  
    }  
  
}
View Code

Add the LoginControl class to the controller package

package com.qs.controller;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginControl {
	@RequestMapping(value="/login")  
    public String login(HttpSession session,String username,String password) throws Exception{        
        //Save information in Session  
        session.setAttribute("username", username);
        //Set the session expiration time in seconds
        session.setMaxInactiveInterval(30*60);//30 minutes
        // redirect  
        return "redirect:test";   
    }  
      
    @RequestMapping(value="/logout")  
    public String logout(HttpSession session) throws Exception{  
        //Clear Session  
        session.invalidate();          
        return "redirect:login";  
    }
}

 Create any class in the controller package to place the jump of the test success page [can also be placed in the loginControl class above]

@RequestMapping("/test")  
    public String test(Model model) {  
    	String message = "SpringMVC";  
        //Add Attribute to model  
        model.addAttribute("message",message);
        System.out.println("test");
        return "test";
    }

 Add login.jsp and test.jsp to src/main/webapp/WEB-INF/views [test.jsp is the success page]

<body>
    <form action="login" method="post">  
        用户名:<input type="text" name="username" /><br>  
        密码:<input type="text" name="password" /><br>  
        <input type="submit" value="登录" />  
      </form>
  </body>

The above is the main code of login.jsp

The code of test.jsp is as follows:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>  
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'test.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
     Current user: ${username}
    <c:if test="${username!=null}">  
        <a href="logout">退出</a>  
    </c:if>
    ${message}
  </body>
</html>

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326710919&siteId=291194637