1. 程式人生 > >eclipse中搭建springboot學習(4)---過濾器

eclipse中搭建springboot學習(4)---過濾器

在helloController新增登入的方法,過濾器不過濾登入路徑,當直接訪問hello路徑時,由於沒有登入會跳轉回登陸路徑。

package com.example.demo;

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

@Controller public class HelloController {          @ResponseBody     @RequestMapping("/hello")     public String hello() {         return "spring boot!!!!";     }          @ResponseBody     @RequestMapping("/login")     public String noLogin() {         return "登入頁面";     } }  

 MyFilter過濾器

package com.example.demo;

import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set;

import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName="myFilter") public class MyFilter implements Filter{     //不攔截的url路徑     private static final Set<String> ALLOWED_PATHS = Collections.unmodifiableSet(new HashSet<>(             Arrays.asList("/noLogin")));

    @Override     public void init(FilterConfig filterConfig) throws ServletException {         // TODO Auto-generated method stub              }

    @Override     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)             throws IOException, ServletException {         HttpServletRequest request = (HttpServletRequest) req;         HttpServletResponse response = (HttpServletResponse) res;         String path = request.getRequestURI().substring(request.getContextPath().length()).replaceAll("[/]+$", "");         boolean allowedPath = ALLOWED_PATHS.contains(path);

        if(allowedPath) {             chain.doFilter(request, response);         }else {              request.getRequestDispatcher("/noLogin").forward(request, response);         }     }

    @Override     public void destroy() {         // TODO Auto-generated method stub              }

}  

在DemoApplication 類中新增@ServletComponentScan 註解

package com.example.demo;

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication @ServletComponentScan  public class DemoApplication {

    public static void main(String[] args) {         SpringApplication.run(DemoApplication.class, args);     }          }

這時候就可以進行測試,由於本人8080埠被佔用,所以將埠號改為8089

修改埠號

server.port=8089