Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include a private JSP from a Servlet

Tags:

java

jsp

servlets

I have my Servlet responding on the everything "/" url-pattern. Inside I need to sometimes render html, so I'd like to .include a JSP page, but I'd like that .jsp to be inaccessible externally. Also, how can I pass a model object into it.

like image 229
Hafthor Avatar asked Nov 19 '10 20:11

Hafthor


2 Answers

I'd like to .include a JSP page, but I'd like that .jsp to be inaccessible externally.

Put it in /WEB-INF folder. The client cannot access it, but the RequestDispatcher can access it.

request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

Also, how can I pass a model object into it.

Set it as request attribute.

request.setAttribute("bean", bean); // It'll be available as ${bean} in JSP.

See also:

  • Servlets tag info page (contains Hello World example and useful links)
  • Hidden features of JSP/Servlet
  • Design patterns webbased applications

That said, be aware that mapping a servlet on / takes over the job of servletcontainer's builtin DefaultServlet for serving static content. You'll have to handle all static files like JS/CSS/images yourself. Consider choosing a more specific url-pattern like /pages/* or *.do for JSP views. Bring eventually a Filter in front as outlined in this answer.

like image 97
BalusC Avatar answered Oct 17 '22 20:10

BalusC


It's easy:

  1. Put your JSP file inside WEB-INF folder.
  2. In your servlet, perform a getServletContext().getRequestDispatcher("/WEB-INF/path/your.jsp").forward(request, response);
like image 42
Pablo Santa Cruz Avatar answered Oct 17 '22 20:10

Pablo Santa Cruz