春季启动:创建引用的uri

时间:2018-08-22 14:40:22

标签: java spring-boot

当前,我们正在使用以下简单代码构建uri引用:

@RestController
@RequestMapping("/fitxers")
public class DocumentController {

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    private ResponseEntity<String> createReferenceURI(String fileName) {

        String uri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/fitxers/download/")
                .path(fileName)
                .toUriString();

        HttpHeaders headersResp = new HttpHeaders();
        headersResp.setLocation(URI.create(uri));
        return new ResponseEntity<String>(uri, headersResp, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    void getStreamingFile(HttpServletResponse response, String id) throws IOException {}
}

我敢肯定,必须有另一种更优雅的方式来获得它。

我们正在创建spring-boot服务。

有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

只需编写一个过滤器,就像这样:

@Component
public class HeadersFilter implements Filter {
    @Override
    public void destroy() {

        System.out.println("Filter will be destroyed");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws
            IOException, ServletException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader(HttpHeaders.LOCATION, ((RequestFacade) request).getRequestURL().toString());
        chain.doFilter(request, response);     
    }

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

        System.out.println("Filter initialized");
    }
}