我正在尝试使用Jersey 2和JSP创建一个Web应用程序的简单示例,并将其部署在Glassfish 4上。但是,我一直在尝试访问我唯一的资源时遇到404错误。
首先,项目结构:
以下是重要的类和文件:
web.xml
我将Jersey设置为过滤器而不是servlet,因为我读过它需要以这种方式定义才能使它与JSP一起工作。
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>jersey</filter-name>
<filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.xxx.sample-jersey2</param-value>
</init-param>
<init-param>
<param-name>jersey.config.servlet.filter.forwardOn404</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>jersey</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--<welcome-file-list>-->
<!--<welcome-file>index.html</welcome-file>-->
<!--<welcome-file>index.htm</welcome-file>-->
<!--<welcome-file>movies.jsp</welcome-file>-->
<!--</welcome-file-list>-->
</web-app>
movies.jsp
非常简单:
<html>
<body>
<h2>Listing Movies</h2>
</body>
</html>
自定义ResourceConfig(我甚至不确定我需要)
package com.xxx.jersey2.config;
import org.glassfish.jersey.filter.LoggingFilter;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;
public class CustomResourceConfig extends ResourceConfig {
public CustomResourceConfig() {
packages("com.xxx");
register(LoggingFilter.class);
register(JspMvcFeature.class);
// it may be also jersey.config.server.mvc.templateBasePath
property("jersey.config.server.mvc.templateBasePath", "/WEB-INF/jsp");
// ... more properties as needed ...
}
}
我的电影控制器:
package com.xxx.jersey2.web;
import com.xxx.jersey2.model.Movie;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.glassfish.jersey.server.mvc.Viewable;
@Path("movies")
public class MoviesController {
@GET
@Path("/list")
public Viewable getMovies() {
List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie("Million Dollar Baby", "Hillary Swank"));
movies.add(new Movie("Toy Story", "Buzz Light Year"));
movies.add(new Movie("Hunger Games", "Jennifer Lawrence"));
return new Viewable("movies.jsp");
}
}
如果我尝试访问https://localhost:8181/sample-jersey2/
,则呈现简单index.jsp
(仅显示Hello World消息)。但是,尝试访问https://localhost:8181/sample-jersey2/movies/list/
会给我一个404错误。
对此有任何想法将不胜感激。 最好的问候
答案 0 :(得分:2)
你的方向正确。请在web.xml中注册您的自定义资源配置。
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.xxx.jersey2.config.CustomResourceConfig</param-value>
</init-param>
您可以删除init param jersey.config.server.provider.packages,因为您已在资源配置中执行此操作。最后一件事是将新的Viewable(“movies.jsp”)更改为新的Viewable(“/ movies.jsp”)。希望它能奏效。