Spring-Jersey : How to return static content?

前端 未结 1 1072
不知归路
不知归路 2020-12-04 00:37

Question :

  1. How do I expose my css/, images/, js/ and other static files?
  2. How do I return a JS
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 00:45

    "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

    
        Jersey
        org.glassfish.jersey.servlet.ServletContainer
        
            javax.ws.rs.Application
            com.component.ResourceRegister
        
        
        
            jersey.config.servlet.filter.forwardOn404
            true
        
    
    
    
        /*
        Jersey
    
    

    "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

    
        org.glassfish.jersey.ext
        jersey-mvc-jsp
        2.25
    
    

    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

    
        
            
            JSP Page
            
        
        
            

    ${it.hello} ${it.world}

    Controller

    @Path("/")
    public class HomeController {
    
        @GET
        @Produces(MediaType.TEXT_HTML)
        public Viewable index() {
            Map 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:

    • Complete example from Jersey project
    • MVC Templates documentation

    0 讨论(0)
提交回复
热议问题