简体   繁体   中英

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!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM