配置Jersey + Jetty + JSP [英] Configuring Jersey + Jetty + JSP
问题描述
如何配置此项目以便能够呈现JSP文件?我希望以/ rest开头的URL以路由到jersey资源,并让/ * URLS提供JSP文件。我在这个项目中没有任何web.xml。
How do I configure this project so that it will be able to render JSP files? I would want to have URLS starting with /rest to route to jersey resources and have /* URLS serve JSP files. I don't have any web.xml in this project.
├───src
│ └───main
│ └───java/Main.java
│ └───resources/HelloResource.java
└───WEB-INF
└───jsp/NewFile.jsp
HelloResource.java
HelloResource.java
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/hello")
public class HelloResource {
@GET
@Produces("text/plain")
public String handleGreeting() {
return "Hello World";
}
@Path("/test")
@GET
@Produces("text/json")
public String test() {
return "just test";
}
}
Main.java
Main.java
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import com.sun.jersey.spi.container.servlet.ServletContainer;
public class Main {
public static void main(String[] args) throws IOException {
Server server = new Server(Integer.valueOf(System.getenv("PORT")));
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.SESSIONS);
context.setContextPath("/");
server.setHandler(context);
ServletContainer container = new ServletContainer();
ServletHolder h = new ServletHolder(container);
h.setInitParameter("com.sun.jersey.config.property.packages",
"resources");
h.setInitParameter(
"com.sun.jersey.config.property.JSPTemplatesBasePath",
"/WEB-INF/jsp");
h.setInitParameter(
"com.sun.jersey.config.property.WebPageContentRegex",
"/(images|js|styles|(WEB-INF/jsp))/.*");
context.addServlet(h, "/*");
try {
server.start();
server.join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐答案
您应该使用context.addServlet(h,/ *)更改行,如下所示:
You should change the line with context.addServlet(h, "/*") as follows:
context.addServlet(h, "/rest/*");
您可以删除WebPageContentRegex和JSPTemplatesBasePath init参数 - 在这种情况下它们是无用的。并将JSP移出WEB-INF / jsp目录。
You can remove WebPageContentRegex and JSPTemplatesBasePath init params - they are useless in this case. And move your JSP's out of the WEB-INF/jsp directory.
如果您使用的是maven,您的项目结构应如下所示:
If you are using maven, your project structure should look as follows:
└───src
└───main
├───java/Main.java
│ └───resources/HelloResource.java
└───webapp/NewFile.jsp
└───WEB-INF/web.xml (optional)
这篇关于配置Jersey + Jetty + JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!