如何使所有扩展类型请求的控制器?

时间:2019-01-14 19:35:26

标签: spring-boot

具有spring boot项目和默认控制器:

@Controller
public class GenericController
{
    @RequestMapping(value= {"/**.html", "/"})
    public String httpRequest(Model model, HttpServletRequest request)
    {

但仅适用于/*.html路由。如何使用任何文件夹源捕获所有.html路由?例如:/abc.html/abc/def.html/abc/def/ghi.html等。

我了解:

并尝试:

@RequestMapping(value= {"/**/*.html", "/"})

但是当调用http://localhost/abc/def/ghi.html返回http状态404时不起作用。

2 个答案:

答案 0 :(得分:0)

我不知道您为什么要这么做,但是您可以破解path params来为您这样做。但这是一种肮脏的方式,可能会与其他mappings发生冲突。

通过使用如下所示的路径参数,您可以执行/abc.html/abc/def.html/abc/def/ghi.html

@RequestMapping(value = { "/**.html" , "/{path2}/**.html" ,"/{path}/{path2}/**.html" })
public String httpRequest(Model model) {
    //You can also check which path variables are present and work accordingly 
    System.out.println("index");
    return "index";
}

如果您想为您的API创建单个入口点,那么我建议您阅读有关GraphQL

的信息。

答案 1 :(得分:0)

另一种方法可以使用过滤器,该过滤器根据传入的URI重定向您的响应:

@Component
@Order(1)
public class AFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if(httpServletRequest.getRequestURI()...){ // use regex ?
            HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

            ((HttpServletResponse) servletResponse).sendRedirect("/some/path/to/your/thingy");
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

和一些控制器:

@RequestMapping(value = "/some/path/to/your/thingy", method = RequestMethod.GET)
public ResponseEntity<Object> aMethod() throws Exception {

    return ResponseEntity.ok("ok");
}