springboot2.0+jsp+登入攔截器

hike97發表於2018-09-28

最近接觸springboot說不推薦jsp,之前一直用傳統web專案,所以自己研究了一下springboot+web整合。

首先參考https://blog.csdn.net/apathecrazyfan/article/details/79638731這篇文章進行springboot+jsp專案的搭建,後來將尚矽谷的springboot視訊做的springboot+thymeleaf專案改造成jsp的。專案結構如下:

//web部分

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com._7k7k</groupId>
	<artifactId>springboot-web-jsp-sample</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>springboot-web-jsp-sample</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<!--Web 專案所以新增spring MVC Web模組支援-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!--jsp頁面使用jstl標籤-->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
		</dependency>
		<!--Provided  start-->
		<!--War包部署到外部的Tomcat中已經包含了這些,
        所以需要新增以下依賴
        否則會和內嵌的Tomcat 容器發生衝突
        -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<scope>provided</scope>
		</dependency>
		<!--用於編譯jsp-->
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- redis新增 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

 登入功能及攔截功能的實現如下:

@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {
    @Resource
    private StudentService studentService;

    @GetMapping("login")
    public ModelAndView loginView() {
        return new ModelAndView("admin/login");
    }

    //登陸
    @PostMapping(value = "login")
    public String login(@RequestParam("username") String userName,
                        @RequestParam("password") String passWord,
                        HttpSession session){
//        System.out.println("使用者名稱:"+userName);
//        System.out.println("密碼:"+passWord);
        Student student = studentService.loginValidate(userName, passWord);
        if (student!=null){
            session.setAttribute("loginUser",student);
            return "admin/main";
        }else {
            request.setAttribute("msg","使用者名稱或密碼錯誤");
            return "admin/login";
        }

    }
    //退出
    @RequestMapping("/logout")
    public String  logout(){
        //移除session
        request.getSession().invalidate();
        return "redirect:/admin/login";
    }
}

登入攔截器:loginInterceptor

package com.atguigu.springboot.component;

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

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

public class LoginHanderInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Object user = request.getSession().getAttribute( "loginUser" );
        if (user == null){
            System.out.println( "攔截" );
            request.setAttribute( "msg","沒有許可權,請重新登入" );
            request.getRequestDispatcher( "/admin/login" ).forward( request,response );
            return false;
        }else {
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

攔截器註冊:之前用的springboot1.5.6 ,後來用了2.0.5 攔截器變為實現 WebMvcConfigurer介面, 之前繼承WebMvcConfigurationSupport 各種出錯

package com.atguigu.springboot.config;

import com.atguigu.springboot.component.LoginHanderInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class MyMvcConfig implements WebMvcConfigurer  {
    //註冊攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor( new LoginHanderInterceptor())
                .addPathPatterns( "/**" ).excludePathPatterns("/", "/index.jsp","/admin/login","/static/**" );
    }
    //自定義靜態資源
//    @Override
//    public void addResourceHandlers(ResourceHandlerRegistry registry) {
//        registry.addResourceHandler( "/static/**" )
//                .addResourceLocations( "classpath:/static/" );
//    }
    /**
     * 不經過controller,實現頁面跳轉
     * registry.addViewController( "requestMapping路徑" ).setViewName( "頁面地址" );
     */
//    @Override
//    public void addViewControllers(ViewControllerRegistry registry) {
//        registry.addViewController( "/admin/login" ).setViewName( "/index.jsp");
//    }
}

注:本人將靜態資源放在webapp下的static下,靜態檔案引用就成功了,具體原因不知。

最後成功實現攔截,結果如下:

相關文章