I designed a sample login page to verify the username and password. If the user gives the correct credentials, the page will move on some other page, otherwise return the message from servlet to the same login page.
Here I have attached sample code :
FirstJSP.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">` <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title>` </head> <body> <form action="Login" method="post"> <input type="text" name="Name"/><br> <input type="password" name=Pass><br><br><br> <input type="submit" value="submit"/><br> <%if(request.getAttribute("message")!=("")) out.println(request.getAttribute("message")); else out.println("");%> <h1>Hi This is JSP sample code </h1> <font color="blue" size="25"> <marquee>Please login to Work with JSP</marquee></font> <%java.text.DateFormat df = new java.text.SimpleDateFormat("MM/dd/yyyy"); %> <h1>Current Date: <%= df.format(new java.util.Date()) %> </h1> </form> </body> </html>
And servlet code, Login.java:
package com.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet { private static final long serialVersionUID = 1L; public Login() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("Name"); String password = request.getParameter("Pass"); response.setContentType("text/html"); if(username.equals("sugan") && password.equals("raj")) { response.getWriter().println("<html><body><Marquee>Welcome to JSP!!!</marquee></body></html>"); } else { String message = "OOps!!! Invalid Username/Password"; request.setAttribute("message", message); request.getRequestDispatcher("/FirstJSP.jsp").forward(request, response); } } }
It works fine, but when loading the login page, it automatically displays Null . Then, if the user gives the wrong credentials, he displays the actual message. How to disable Null message at runtime?
source share