The server side session is been shared among all requests from the same client session. The session lives as long as the user accesses the site for the first time until the session is been expired (not used over 30 minutes (which is configureable)), or it is been explicitly invalidated. With your approach, open the same page in a new browser tab. You would still see the error messages while the form in the new page isn't entered/submitted at all. This is not good for user experience.
The normal practice is to store the error messages in the request scope and forward the request to the same page instead of redirecting to it. This is easy if you use a fullworthy Servlet class instead of a JSP file for processing and validating. E.g.
/WEB-INF/register.jsp
<form method="post" action="register">
<p><label for="username">Username</label>
<input type="text" id="username" name="username" value="${fn:escapeXml(param.username)}">
<span class="error">${messages.username}</span>
<p><label for="password">Password</label>
<input type="password" id="password" name="password">
<span class="error">${messages.password}</span>
<p><label for="confirm">Confirm password <span class="required">*</span></label>
<input type="password" id="confirm" name="confirm">
<span class="error">${messages.confirm}</span>
<p><input type="submit" value="Register">
<p>${messages.result}</p>
</form>
com.example.RegisterServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages); // Will be available by ${messages}.
String username = request.getParameter("username");
if (username == null || username.trim().isEmpty()) {
messages.put("username", "Please enter username");
}
// ...
request.getRequestDispatcher("/WEB-INF/register.jsp").forward(request, response);
}
Map this servlet as follows in web.xml
:
<servlet>
<servlet-name>registerServlet</servlet-name>
<servlet-class>com.example.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registerServlet</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
Open it by http://example.com/context/register and go ahead.
See also