Search code examples
javajspservletsjakarta-eeforward

Servlets that forward to JSPs


I'm coding a Java EE WebApp which uses several JSP files. Until now, I use to write the addresses like this:

http://www.example.com/login.jsp

But I prefer they would be like:

http://www.example.com/login

So I made a Servlet for each JSP file, and they that look like this:

public class ForwardLoginServlet extends HttpServlet {

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

        String url = context.getInitParameter("loginURL"); // this will return the login.jsp filename
        forwardToURL(url, request, response);
    }
    // More stuff here (doget, do post,...)
}

It works perfecty, but my question is: is there any another way to do this without creating a new Servlet for every JSP? It's not very fast to write a JSP an then write the Servlet for it...

Thanks!


Solution

  • If you only need to map url to jsp then you can specify it in web.xml

      <servlet>
        <servlet-name>login</servlet-name>
        <jsp-file>/WEB-INF/views/login.jsp</jsp-file>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>