Spring-Jersey : How to return static content?

可紊 提交于 2019-11-27 15:50:41
Paul Samsotha

"How do I expose my css/, images/, js/ and other static files?"

The jersey.config.servlet.filter.staticContentRegex property should work, but you need to specify all the possible patterns for all the types of files you want to serve. The easier way is to just use the property jersey.config.servlet.filter.forwardOn404, as pointed out in this answer. And yes with both choices, you need configure Jersey as a filter, rather than a servlet. So your web.xml might look like

<filter>
    <filter-name>Jersey</filter-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.component.ResourceRegister</param-value>
    </init-param>
    <!-- pass to next filter if Jersey/App returns 404 -->
    <init-param>
        <param-name>jersey.config.servlet.filter.forwardOn404</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

<filter-mapping>
    <url-pattern>/*</url-pattern>
    <filter-name>Jersey</filter-name>
</filter-mapping>

"How do I return a JSP page in my controller (not a String method) for my index view?"

First thing you need is the jsp mvc dependency

<dependency>
    <groupId>org.glassfish.jersey.ext</groupId>
    <artifactId>jersey-mvc-jsp</artifactId>
    <version>2.25</version>
</dependency>

Then you need to register the feature

public ResourceRegister () {
    ...
    register(JspMvcFeature.class);
}

Then you need to specify the template base path for all your jsp pages. For example I used /WEB-INF/jsp

public ResourceRegister () {
    ...
    property(JspMvcFeature.TEMPLATE_BASE_PATH, "/WEB-INF/jsp");
}

So for this case, all the jsp files should be located in /WEB-INF/jsp directory.

Example jsp and controller

index.jsp

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <title>JSP Page</title>
        <link href="css/styles.css" rel="stylesheet">
    </head>
    <body>
        <h1>${it.hello} ${it.world}</h1>
    </body>
</html>

Controller

@Path("/")
public class HomeController {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public Viewable index() {
        Map<String, String> model = new HashMap<>();
        model.put("hello", "Hello");
        model.put("world", "World");
        return new Viewable("/index", model);
    }
}

public ResourceRegister () {
    ...
    register(HomeController.class);
}

Here the /index in the Viewable points the index.jsp (we don't need the .jsp extension). Jersey knows how to find the file from the property we set above.

See Also:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!