Java Servlet Best Practices. This post is about tips and techniques for JSP servlet best practices for developer architect. Servlet-based technologies designed to make web application development easier and more effective.
1. Overview of Java Servlet best practices
Servlet is used as controller or Front Controller (FC is J2EE design pattern) or module controller for delegating the request to the respective controller for processing of HTTP request.
In MVC (Module View Controller) architecture, M stands for Model (which process the business logic), V stands for View ( which is used on presentation layer to present model on UI) and C stands for Controller ( which control the flow and delegate the request) in the MVC Architecture. Here, Java Servlet is refere for C: Controller.
The first area of innovation has been happening in the presentation layer. Technologies such as Spring Framework, Struts, Java Server Pages (JSP), WebMacro, and Velocity give us more productive alternatives. I advise you to consider using a framework and provide some helpful tips in this section on selecting the right framework.
2. Use Servlet as Controller
Use Java Servlet always as Front Controller (FC), sub-controller, I mean to say, it should be controller somehow not used as View, however, no one restricting you to use Servlet as view. As per the best practices of Servlet, in the MVC (Model, View, and Controller ) architecture thumb rule is to use a Servlet as Controller, not as View.
3. Use Pre-Encoded Characters
It’s good to have always, use pre-encoded character in the Java Servlet best practices. Whether we use
OutputStream , thumb rule is to use a
PrintWriter for writing characters and an
OutputStream for writing bytes.
A PrintWriter has a downside, specifically, it has to encode every character from a char to a byte sequence internally. When you have content that’s already encoded—such as content in a file, URL, or database, or even in a String held in memory—it’s often better to stick with streams. In this way, you can enable a straight byte-to-byte transfer.
Whenever, charset mismatch between the stored encoding and the required encoding, there’s no need to first decode the content into a string and then encode it again to bytes on the way to the client. Here, pre-encoded plays an important role in the performance of servlet, use the pre-encoded characters and you can save a lot of overhead.
Performance on an average depends on the webserver container to container largely approx 20%.
4. Load Configuration Files from the Classpath
The configuration file should be per application location per configuration files in location
WEB-INF/classes under the resource path. It also works equally well for locating configuration files bundled within .war files and/or deployed across multiple back-end servlet containers.
5. HTTPSession usage
Keep the minimum to minimum user information in session i.e.
HttpSession , wherever mandatory. If you can distribute the session via any in-memory cache i.e. Redis distributed cache or any other in-memory cache, that would be always beneficial for scaling your application.
The question is, when should we use HttpSession? It is good question, consider following while using HttSession.
- Storing login status: The timeout is useful, and changes between browsers or machines should naturally require a new login.
- Storing user data pulled from a database : avoids storing sensitive data in local cache and transfer across-the-wire for database request.
- Storing temporary user data: Temporary data includes search results, form state, or a guest’s shopping-cart contents that don’t need to be preserved over the long term.
6. Don’t Use SingleThreadModel
Using of SingleThreadeModel is not be the best practices so think several times before using this. I mean to say, use this when you have sufficient compelling reason to have it. This interface was intended to make life easier for programmers concerned about thread safety, but the simple fact is that
SingleThreadModel does not help.
7. Use of Caching
Pre-cooked or ready to use data and caching of content can be key to providing your site visitors with a quality experience. So , use wherever required, specially in Restful Web Services.
// This content will expire in 24 hours. long t = System.currentTimeMillis() ; response.setDateHeader("Expires", t + 24*60*60*1000); response.setDateHeader("Date", new Date());
8. Choose the Right Servlet Framework
Choosing the framework is not so easy, especially, when you have a lot of options available. So, invest your time to do the proper analysis which must fulfill your requirement. As per my understanding is concerned, nothing is best or worst practices. Yesterday’s best practices may be worst practices for today, everything is contextual. As per the time, requirement and context also changing. Be careful to choose the servlet Framework, nowadays, Spring application framework can be but think twice whether your requirement and context fulfilled or not.
9. Tips for selecting a framework
Before choosing a servlet framework, it’s important that you should consider its feature list. Following are some of the features that frameworks provide. Not all frameworks support all these features, nor should this sort list be considered exhaustivly.
- Form validation: Frameworks commonly provide tools to validate form data, allowing the framework to sanity-check parameters before the servlet even sees the data, for example. Some allow for easy development of “form wizards” with Next/Previous buttons and maintained state.
- Error handling: Some frameworks include advanced or custom error handling, such as sending alert emails, logging errors to a special data store, or autoformatting errors to the user and/or administrator.
- Internationalization & Nationalization :
Nationalization(n10n) is always a challenge, but some frameworks have features and idioms that simplify the process.
- Integration with a template language: Some frameworks integrate with a specific template language. Others have a pluggable model to support many templates, although they’re often optimized for one template language. If you prefer a particular template language, make sure the framework supports it well or not.
- Security integration: The default servlet access control and security model works for simple tasks but isn’t extensible for more advanced needs. Some frameworks provide alternative security models, and many support pluggable security models.
- Support of designer/developer separation: One of the common goals in web application development is to effectively separate the developer’s responsiblities from the designer’s responsibilities. Choosing the right template language helps here, but the framework choice can have even more impact. Some enable the separation of concerns, some enforce it.
- Mechanisms to support web services: With the growing interest in web services, it’s common to see new frameworks centered around web services feature.
You can visit Oracle Java: Servlets and JSP Pages Best Practices for more details.
Thanks for visiting this post for Java Servlet best practices. you visit Java JSP Servlet Tutorials Page.
Your comments are welcome to improve this article. You can write your questions in the comment section here, to ask any question regarding Java Servlet best practices, I will try to answer those questions.
Happy Learning 🙂 for java Servlet best practices.