Spring mvc login tutorial

Let us discuss spring mvc login example in eclipse.

Example Explanation:

Use http://localhost:8080/SpringMVCExample4/ url to start the application. Enter username “jai” and password “123”. Click on login button. Request will be handled by DispatcherServlet. It delegates the request to the LoginController controller. The LoginController controller resolve the request with help of RequestMapping annotation, executes the specific functionality and returns the ModelAndView object to the DispatcherServlet. The DispatcherServlet then take the help of InternalResourceViewResolver to get the actual view name. In our example it will return the “/WEB-INF/jsp/welcome.jsp” if username and password are correct otherwise returns “/WEB-INF/jsp/errorPage.jsp”. The DispatcherServlet then insert the model data into view and render response.

Note: We are using HttpServletRequest and HttpServletResponse in request processing method to get the form parameters.

Example:

index.jsp



  
    Spring MVC login example.
  
  
  
    
UserName:

Password:

web.xml

  

   
   
      Login
      
         org.springframework.web.servlet.DispatcherServlet
      
      1
   

   
      Login
      *.html
   
 

Login-servlet.xml

  


   

   
      
      
   
 

LoginController.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
   @RequestMapping("/login")  
   public ModelAndView login(HttpServletRequest request,
		   HttpServletResponse response) {
	  String userName=request.getParameter("userName");  
      String password=request.getParameter("password");
      String message;
      if(userName != null && 
    		  !userName.equals("") 
    		  && userName.equals("jai") && 
    		  password != null && 
    		  !password.equals("") && 
    		  password.equals("123")){
    	  message = "Welcome " +userName + ".";
	      return new ModelAndView("welcome", 
	    		  "message", message);  
    	  	    	  
      }else{
    	  message = "Wrong username or password.";
    	  return new ModelAndView("errorPage", 
    			  "message", message);
      }
   }
}

welcome.jsp



  
    Spring MVC login example.
  
  
    

${message}

errorPage.jsp



  
    Spring MVC login example.
  
  
    

${message}


Output:

Spring example3-1
Enter Username = Jai and Password = 123
Spring example3-2
Click on login button.
Spring example3-3
 
Download this example.