1. Why JSP Best Practices needed?
Best practices are always as per business needs and always contextual. Best practices of today’s can be the worst practices of tomorrow’s. There are so many questions that arise in your mind when we ask ourselves about the best practices of JSP ( Java Server Page). Conceptually, a JSP page is converted to a servlet before it’s called on to serve requests. This means that a JSP page can do anything a servlet can do, but it doesn’t mean JSP is appropriate for all tasks.
In MVC (Model View Controller) architecture, JSP plays a vital role in View, and never choose jsp as controller in MVC, although you can use JSP as controller too.
2. Use JSP as Presentation for Best practices
Use JSP as a presentation layer, not for business layers, no business logic should be in side JSP. Only presentation logic, for instance, displaying of date is the presentation logic so use JSTL or any another tag library on JSP to display proper format as per business demand.
3. Favour JSTL and Avoid Using Scripting
Avoiding scripting elements (raw Java code in JSP) is always a good idea for JSP best practics perspectives. Using scripting elements exposes you to, at least, the following problems:
- Syntax errors are very easy to make and extremely hard to locate
- Scripting code can be reused only through copy/paste.
- For non-programmer changed of code for look-and-feel aspects of the pages, scripting code is very distracting and easy to corrupt by mistake.
4. Break common pages
For consistent look and feel , break the page into multiple pages as per your design, i.e. header , footer, menu, left navigation should be in separate JSP file so that , it can be include efficiently wherever needed.
5. choosing Appropriate Include
JSP provides two ways to include content in a page: the include directive (
<%@ include file="" %>) and the include action (
<jsp:include page=" />). Use following thumb rule:
- Use the include directive (<% include %>) for a file that rarely changes, which is typically true for things such as headers and footers.
- Use the include directive (<% include %>) if the included file must set response headers.
- Use either the standard include action (
) or the JSTL import action ( ) for a file that is likely to change.
6. Consider Internationalization from Start, if planning
Use JSTL i18n actions to create a link to the correct page for the current locale.
visit Oracle Java JSP (Java Server Page) official site
Happy learning JSP best practices 🙂