Include a private JSP from a Servlet
Asked Answered
G

2

9

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.

Gobioid answered 19/11, 2010 at 20:19 Comment(0)
A
16

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:


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.

Apiece answered 19/11, 2010 at 20:22 Comment(6)
I refer putting resources in their own sub folder like (WEB-INF/jsp)Vanburen
@rsp: You can indeed always categorize it further the way you want :)Apiece
Wasn't my choice on the / servlet - no directories, no extensions. Your answer worked once I added a /WEB-INF/jsp/* mapping to org.apache.jasper.servlet.JspServletGobioid
You're welcome. As to the extra mapping: that's weird. It should by default work out of the box. Was the servletcontainer's builtin JspServlet in servletcontainer's own web.xml changed to ignore INCLUDE and FORWARD dispatches or so?Apiece
web.xml had nothing but my catch-all servlet - without the /WEB-INF/jsp/* mapping, it would keep invoking my cath-all servlet and then SO.Gobioid
Ok. Thx for all the help BalusC - I tried to get the filter working, but for now my eek servlet works.Gobioid
A
2

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);
Anisaanise answered 19/11, 2010 at 20:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.