问题
To improve my java skills, I'm trying to build a simple j2ee framework (MVC).
I built it to handle every request in a FrontServlet. Here is the mapping that I used :
web.xml :
<servlet>
<servlet-name>Front</servlet-name>
<servlet-class>test.FrontServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Front</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
My problem is that when I forward the request from the FrontServlet to a JSP, obviously, the JSP request is handle by the FrontServlet and the view isn't rendered.
- How can I resolve this problem by keeping the url-pattern "/*" ?
- Is there a way to render a JSP in a Servlet without performance losses ?
Thanks in advance for your reply !
- Solution 1 (@Bryan Kyle)
I'm trying to follow your advise. I created this filter :
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
HttpServletRequest req = (HttpServletRequest) request;
if(!req.getRequestURL().toString().endsWith("jsp"))
{
// I changed the servlet url-pattern to "/front.controller"
req.getRequestDispatcher("/front.controller").forward(req, response);
/*chain.doFilter(req, resp);*/
}
}
<filter>
<filter-name>Filter</filter-name>
<filter-class>test.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- Is it right?
Thanks !
回答1:
A Filter
is an inappropriate solution for a front controller approach.
You want to refine the url-pattern
of your servlet so that it matches e.g. /pages/*
or *.do
. You don't want your front controller to kick in on irrelevant requests like CSS/JS/images/etc. To take /pages/*
as an example, assuming that you've a JSP in /WEB-INF/foo.jsp
, then the following in a servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF" + request.getPathInfo() + ".jsp").forward(request, response);
}
should display the JSP in question on http://localhost:8080/contextname/pages/foo.
See also:
- Design patterns in Java web applications
- Hidden features of JSP/Servlet
回答2:
I think the problem here might be that you're using a Servlet
instead of a ServletFilter
.
A ServletFilter, as the name suggests filters requests by providing pre- and post-processing on the request. You'd probably want to use a Filter if you needed to do something like the following:
- Provide security checks across an entire application
- Set request properties that are picked up by a servlet or jsp
- Compress a response
- Log timing information
- Etc.
Have a look at the documentation about Servlet Filters.
来源:https://stackoverflow.com/questions/5096023/display-forwarded-jsp-with-url-pattern