32

I noticed a common pattern is to put JSP pages in WEB-INF folder (as opposed to WAR root). What's the difference? Why is that preferred?

3 Answers 3

38

Files in WEB-INF are not visible to the users. It's a bit safer that way.

If (a contrived example) you are including db.jsp, but by itself it throws an exception, a malicious user can open http://yoursite.com/db.jsp and get some insight on your application (worst - the database credentials) from the exception message.

1
  • 4
    I don't get it... Won't you get just an HTML response when you open the URL of JSP instead of the JSP code? I may be missing something Commented May 3, 2016 at 12:38
10

I don't think it's a good design pattern, but I believe I can explain the reasoning.

Servlet containers won't serve any content in WEB-INF. By putting your JSPs there, you prevent anyone from directly accessing a JSP by navigating to it in the browser by name. This might be considered good practice, if some of your JSPs are just fragments of code/markup, and not meant to be used directly, and perhaps open some security hole you haven't though of.

It's still possible to get the container to see and use the JSPs as expected even in WEB-INF.

6
  • If it's not a good design pattern, what are the alternative solutions to the problems you explained? Commented Jul 26, 2011 at 6:09
  • 3
    I disagree. I think it is a very good pattern as it solves a real issue in a simple, robust and easily understandable way.
    – pap
    Commented Jul 26, 2011 at 10:21
  • 7
    I agree with @pap. As 1) it enforces you to place a controller in front of the JSPs (Servlet, Action, etc.) and 2) it does hide Java specifics (.jsp ending).
    – home
    Commented Jul 26, 2011 at 14:02
  • 13
    That's not a design pattern at all.
    – BalusC
    Commented Jul 26, 2011 at 14:48
  • Placing JSP files under WEB-INFis a good and officially recommened design pattern as it enforces an MVC approach. You can still use "public" JSP files in very simple applications. Commented Jul 29, 2015 at 7:53
5

An extra-plus when using a Controller (or Front-Servlet) is that you decouple the URL path from the physical location of the JSP-files in your project.

As example here a simple request-mapping from a Spring Controller:

@RequestMapping(value = "/item/edit", method = RequestMethod.GET)
public String getItemEdit(@RequestParam(value = "id", required = false) final String id) {
    return "itemeditform";
}

The ViewResolver takes care of mapping the URL to the place where your JSPs reside.

Not the answer you're looking for? Browse other questions tagged or ask your own question.