SpringMVC interceptor Sample code that implements the login authentication interceptor

  • 2020-06-12 09:05:12
  • OfStack

This example realizes the authentication interception when landing and USES SpringMVC interceptor to realize

When the user clicks to the homepage of the website, it should be blocked. The user can only enter the homepage after logging in, or enter the login page

The core code

The first is index.jsp, which shows links


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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%>" rel="external nofollow" >
  
  <title> Home 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" rel="external nofollow" >
  -->
 </head>
 
 <body>
   <div style="margin:0 auto;padding-top:100px;font-size:18px;" align="center">
     <p><a href="loginpage.html" rel="external nofollow" > landing </a></p>
     <p><a href="user/home.html" rel="external nofollow" > The user center </a></p>
     <p><a href="exception.html" rel="external nofollow" > An exception </a></p>
   </div>
 </body>
</html>

controller class


package com.jikexueyuan.demo.springmvc.lesson4.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

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

import com.jikexueyuan.demo.springmvc.lesson4.constant.Global;
import com.jikexueyuan.demo.springmvc.lesson4.exception.MyException;
import com.jikexueyuan.demo.springmvc.lesson4.model.User;
import com.jikexueyuan.demo.springmvc.lesson4.service.LoginService;

/**
 *  This is an example of how to define it. Okay MVC3 Layer annotations, used @Resource To inject, and to use @RequestMapping , @RequestParam  , @SessionAttributes
 */

@Controller
public class LoginController extends BaseController {

  @Resource
  LoginService service;
  
  @Resource
  HttpServletRequest request;
  
  @RequestMapping("/exception")
  public void exception() throws MyException{
    throw new MyException(" test springmvc Exception capture in ");
  }
  
  @RequestMapping("/loginpage")
  public String toLoginPage(){
    return "/WEB-INF/jsp/login.jsp";
  }
  
  @RequestMapping("/user/home")
  public String toUserHome(){
    return "/WEB-INF/jsp/userhome.jsp";
  }
  
  @RequestMapping("/logout")
  public String logout(){
    request.getSession().removeAttribute(Global.USER_SESSION_KEY);
    return "redirect:/";
  }
  
  @RequestMapping(value = "/doLogin", method = RequestMethod.POST)
  public String doLogin(@RequestParam String userName, @RequestParam String password){
    
    try {
      User user = service.doLogin(userName, password);
      request.getSession().setAttribute(Global.USER_SESSION_KEY, user);
      return "redirect:/user/home.html";
    } catch (Exception e) {
      return "/WEB-INF/jsp/login.jsp";
    }
    
  }
  
}

When the user center is clicked, the interception is triggered and configured as follows

Add the interception configuration to ES21en-ES22en.xml to intercept all URL requests containing /user/, which of course will trigger when requesting the user center


<mvc:interceptors>
    <mvc:interceptor>
      <!--  Intercept all URL Contained in the /user/ The request of  -->
      <mvc:mapping path="/user/**"/>
      <bean class="com.jikexueyuan.demo.springmvc.lesson4.interceptor.LoginInterceptor"></bean>
    </mvc:interceptor>
  </mvc:interceptors>

Then there is the specific interceptor class that bean points to. If session saves user information as null, then it jumps to the login page.


package com.jikexueyuan.demo.springmvc.lesson4.interceptor;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jikexueyuan.demo.springmvc.lesson4.constant.Global;

public class LoginInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    Object user = request.getSession().getAttribute(Global.USER_SESSION_KEY);
    if (user == null) {
      System.out.println(" Not logged in yet, redirect to the login page ");
      response.sendRedirect("/loginpage.html");
      return false;
    }
    
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    System.out.println("postHandle");
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    System.out.println("afterCompletion");
  }

}

At this point, the simple springmvc interceptor is complete.


Related articles: