开发者

Interpreting request as JSP instead of through servlet

开发者 https://www.devze.com 2023-01-15 09:01 出处:网络
This should be relatively simple to do but I\'ve yet to find a description of how to do it. My setup is a simple web app that processes every request through a servlet (I\'ll call it MyEverythingServ

This should be relatively simple to do but I've yet to find a description of how to do it.

My setup is a simple web app that processes every request through a servlet (I'll call it MyEverythingServlet for this question). Here's a slightly modified version of my web.xml:

<servlet>
    <servlet-name>MyEverythingServlet</servlet-name>
    <servlet-class>blah.blah.blah.MyEverythingServlet</servlet-cl开发者_Go百科ass>
</servlet>

<servlet-mapping>
    <servlet-name>MyEverythingServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Right now, the servlet is pretty simple and either does some work (when work.do is part of the path) and if a .txt file is specified in the path, we'll do some validation and then load the file and send the text as the response:

response.getOutputStream().print( content );

What I'd like to do is either:

  • Inside the servlet, if the request is a URL to a .jsp file, I'd like to be able to have the container interpret the JSP scriptlet parts/taglib stuff before I write the String to the response.
  • Change my web.xml to have it process .jsp files outside of MyEverythingServlet.


  • Inside the servlet, if the request is a URL to a .jsp file, I'd like to be able to have the container interpret the JSP scriptlet parts/taglib stuff before I write the String to the response.

There's no direct API available which processes JSP files programmatically like that. In theory, you'd like to have the JSP in public webcontent and forward the request to the JSP. You can do this with RequestDispatcher#forward().

if (request.getServletPath().endsWith(".jsp")) {
    request.getRequestDispatcher(request.getServletPath()).forward(request, response);
} else {
    // Write "plain" to response as you did.
}

You may only want to do some checks on the correctness of the paths, but this should at least give you the generic idea. There is however a little problem: the servlet will be invoked recursively since it's mapped on /*. You'd rather replace this MyEverythingServlet by a Filter which just delegates the remnant of the job to the appserver's builtin default servlet. Having a Servlet to listen on /* is already a design-smell indication that it should have been a Filter from the beginning on ;)

  • Change my web.xml to have it process .jsp files outside of MyEverythingServlet.

You can't have a "negative" url-pattern in web.xml. Best what you can do is to let the servlet listen on a more specific url-pattern like *.txt or /static/* and keep the JSP files there outside.

0

精彩评论

暂无评论...
验证码 换一张
取 消