SPRING MVC is commonly used framework for creating web applications in JAVA. Here we will see the common implementation of SPRING with MVC pattern. At the end of this tutorial we will have a spring mvc login example, which will help all the newbies to get started with Spring.
We will be creating the following project structure for this example-
Note: All the required jars should be kept in lib folder.
Step 1: Lets create a Dynamic Web Project to start with. Then we need to update web.xml file and dispatcher-servlet.xml file. These config files are required for any Spring web application. All the requests are being handled by these files. Dispatcher servlet file, as its name suggests, is used for dispatching the user request to the corresponding controller. However, you can give any name to this servlet file for e.g. <yourname>-servlet.xml. In this case, the files will be like-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>SpringMVC</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/view/login.jsp</welcome-file> </welcome-file-list> </web-app> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <context:annotation-config /> <context:component-scan base-package="com.code2java" /> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=".jsp" /> </bean> </beans> |
Step 2: Now, lets create the JSP pages one each for login page, success page and failure page. All the pages will be added under WEB-INF/view/ folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!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>code2java - Login with Spring MVC</title> </head> <body> <label>Welcome to www.code2java.com</label> <br> <h3>${error}</h3> <!-- redirecting to Spring Controller for authentication --> <form id="login" action="login.do" method="post" modelAttribute="user"> <table> <tr> <td><label>UserName : </label></td> <td><input name="userName"></input></td> </tr> <tr> <td><label>Password: </label></td> <td><input name="password" type="password"></input></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" /></td> </tr> </table> </form> </body> </html> |
1 |
<h2>Login Success</h2> |
1 |
<h2>Login Failed.</h2> |
Step 3: Its time to add controller class, create a LoginController.java class and add the controller method which will be called on submitting the login form on login.jsp page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
package com.code2java.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.code2java.model.User; import com.code2java.service.ILoginService; @Controller public class LoginController { /* LoginService object created using Autowiring */ @Autowired ILoginService loginService; /** * Controller method when user submits the login.jsp page * * @param user * @param result * @return */ @RequestMapping("/login") public ModelAndView login(@ModelAttribute("user") User user, BindingResult result) { /* * Spring's Validation utils to check for empty spaces in the userName. * And in case of error it will update the BindingResult. */ ValidationUtils.rejectIfEmptyOrWhitespace(result,"userName","userNameError"); /* * Spring's Validation utils to check for empty spaces in the password. * And in case of error it will update the BindingResult. */ ValidationUtils.rejectIfEmptyOrWhitespace(result,"password","passwordError"); /* Check for any errors */ if(!result.hasErrors()) { boolean success = loginService.validate(user); if(success) return new ModelAndView("success"); else return new ModelAndView("fail"); }else return new ModelAndView("login","error","Username or Password cannot be empty."); } } |
Step 4: Now, we need to create the model class, to store the user details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.code2java.model; public class User { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } |
Step 5: Now, we need to create the service to serve the request. We will create a Login Service interface and its implementation.
1 2 3 4 5 6 7 8 |
package com.code2java.service; import com.code2java.model.User; public interface ILoginService { public boolean validate(User user); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.code2java.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.code2java.dao.LoginDAO; import com.code2java.model.User; @Service("loginService") public class LoginServiceImpl implements ILoginService { @Autowired LoginDAO loginDao; @Override public boolean validate(User user) { return loginDao.authenticateUser(user); } } |
Step 6: Now we need to create a DAO class to validate the user. More specifically, this is required when you need to connect to database and fire the queries to get the result, else you can skip this and validate the user on service itself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.code2java.dao; import org.springframework.stereotype.Repository; import com.code2java.model.User; @Repository("loginDao") public class LoginDAO { public boolean authenticateUser(User user) { /* You can add your validation scope here, may be a DataBase Query */ if(user.getUserName().equals("code2java") && user.getPassword().equals("code2java")) { return true; }else return false; } } |
We are done with the implementation, now its time to execute the application. The expected outputs will be as-
Download the complete source SpringMVC.
Hope this will help,
Regards,
Nikhil Naoghare.
OH,GOOD BLOG.
Thanks Nikhil. This helped me!!