SpringBoot让@RequestMapping不能被外界访问只能通过服务期间跳转访问

先讲下原理,SpringBoot拦截请求一般用Interceptor和Filter,而Interceptor是拦截前端控制器dispatcherServlet传递给handler(一个@RequestMapping对应一个handler)的请求,包括服务期间跳转,属于Spring的范畴。而Filter拦截所有外界请求,属于tomcat范畴,不会拦截Spring范畴的服务期间跳转。所以应选Filter作为技术实现方案。

下面有测试代码例子:

@Controller
public class TestController {


    @RequestMapping("/test1")
    @ResponseBody
    public String test1() {

        return "test1";
    }

    @RequestMapping("/test2")
    public String test2() {

        return "test3";
    }

    @RequestMapping("/test3")
    @ResponseBody
    public String test3() {

        return "testEnd";
    }
}
package com.test.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter
public class TestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println(request.getRequestURI());
        if (request.getRequestURI().equals("/test3")) return;

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
package com.test.config;

import com.test.interceptor.TestInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

//@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
    }
}
package com.test;

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

@SpringBootApplication
@ServletComponentScan
public class App {

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值