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 !
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 servletshould display the JSP in question on http://localhost:8080/contextname/pages/foo.
See also: