Warm tip: This article is reproduced from serverfault.com, please click

Restful web Service alongside web application in servlet

发布于 2020-11-28 11:19:58

I am a newbie in java web application. I am using java 1.8, tomcat server 9.0.4, and jersey library in IntelliJ. I want to have a simple web page that shows a table of the database content when the get method is called and also a restful API from the same address when the post method alongside its parameters is called in order to fetch specific data from the same table. This is my web.xml config:

    <servlet>
        <servlet-name>Test API</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>api</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>Test API</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

and this is my project structure:

enter image description here

This is my API java code:

@Path("hello")
public class postRequest {

    @POST
    @Produces(MediaType.TEXT_PLAIN)
    public String doPost(@QueryParam("name") String name){
        return "Hello,I am " + name;
    }
}

and this is my web java code:

@WebServlet(name = "getRequest", urlPatterns = {"hello"})
public class getRequest extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
        dispatcher.forward(request, response);
    }
}

when I call the address localhost/hello?name=hana in postman the result shows up but when I open the localhost/hello in the browser just a blank page comes. I tried to add another servlet and servlet-mapping without asterisks but the webserver does not start and triggers an error. How can I change web.xml to accomplish that?

Questioner
fatemeh poormohammad
Viewed
1
Paul Samsotha 2020-11-28 21:00:29

The problem is the <url-pattern>/*</url-pattern> for the Jersey application. What this will do is make Jersey handle all requests. This leaves no chance for the servlet to get any requests. Jersey will not forward requests that it does not know1.

What you can do though is instead of using the Servlet, just make a Jersey resource method that injects the HttpServletRequest and HttpServletResponse. Then you can just use the same code as you did in the Servlet

@GET
@Path("redirect")
public void redirect(@Context HttpServletRequest request,
                     @Context HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/index.jsp");
    dispatcher.forward(request, response);
}

Just tested with this resource method and it works just fine.

Note: If you plan to serve an entire web application, this may not be the most efficient approach. What I would do is just change the url-pattern to something else like /api/* so that other servlets (such as the default servlet that handles the static content) can be reached. This way other static files like CSS and JS files can be handled the way they were meant to be served by the container.

The other option is to use the filter configuration for Jersey as mentioned in the link I have posted in the footnote. Personally, I prefer the former approach as the URLs of the web app and REST API are separated.


1. It is possible to configure Jersey to forward requests. It involves configuring Jersey to run as a servlet filter instead of a Servlet and also setting a configuration init-param. See Jersey /* servlet mapping causes 404 error for static resources.