如何使jersey和@webservlet一起工作

时间:2018-12-06 07:28:48

标签: java jsp networking jersey servlet-filters

directory structure

如何使jersey和@webservlet一起工作?

球衣ResourceConfig:

@ApplicationPath("/*")
public class ApplicationConfig extends ResourceConfig {
    public ApplicationConfig() {
        register(Greetings.class);
    }
}

球衣资源已在resourceConfig中注册:

@Path("/login")
public class Greetings {
    @GET
    public Response getHelloGreeting(@Context HttpServletRequest httpRequest) {
        System.out.println("In the Greetings resource");
        String url= "http://"+httpRequest.getServerName()+":"+httpRequest.getServerPort()+httpRequest.getContextPath();
        String newURL = url+"/login.jsp";
        System.out.println(newURL);
        return Response.seeOther(URI.create(newURL)).build();
    }
}

网络servlet

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

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            ServletContext servletContext = getServletContext();
            System.out.println("inside login servlet");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            System.out.println("request forwarded");
        }
    //other functions not important so deleted
}

情况1:在访问此内容时     http://localhost:8088/ResponseFilterweb/login

控制台日志:

In the Greetings resource  
http://localhost:8088/ResponseFilterweb/login.jsp             (no ui comes)

关于访问此     http://localhost:8088/ResponseFilterweb/hello

(nothing happens 404 error)

情况2:更改应用程序配置资源路径:

@ApplicationPath("/auth")
public class ApplicationConfig extends ResourceConfig {
    public ApplicationConfig() {
        register(Greetings.class);
    }
}

访问此内容
    http://localhost:8088/ResponseFilterweb/auth/login

In the Greetings resource  
http://localhost:8088/ResponseFilterweb/login.jsp             (Ui comes)

访问此内容
    http://localhost:8088/ResponseFilterweb/hello

inside login servlet                                          (Ui comes)
userid is
Encoded string 
request forwarded

疑问:
不知道为什么在第一种情况下会阻止login.jsp:

为什么http://localhost:8088/ResponseFilterweb/login不显示任何用户界面..我认为它应该出现?
为什么http://localhost:8088/ResponseFilterweb/hello不显示任何用户界面?

2 个答案:

答案 0 :(得分:1)

使用@ApplicationPath不能使用星号(*

  

如果使用/ *,则表示它过于贪婪,并说它应该一直匹配所有内容,并且默认servlet将永远不会被调用

改为使用@ApplicationPath("/")

  

如果使用/,则将替换容器的默认servlet

答案 1 :(得分:1)

如果您使用的是web.xml,则thisthis是您的解决方案,但是由于您不是,this可能是您唯一的选择。问题是,当您使用/*作为Jersey的servlet映射时,它将占用所有请求。因此,对/hello的请求将转到泽西岛,而不是LoginServlet。我链接的那些解决方案要做的是,如果在Jersey应用程序中找不到请求,它将导致Jersey转发该请求。另一个解决方案是将servlet映射更改为类似/api/*(这很常见),然后在API请求前加上/api