Spring MVC login example

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.

project_structure
project_structure

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-

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.

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.

Step 4: Now, we need to create the model class, to store the user details.

Step 5: Now, we need to create the service to serve the request. We will create a Login Service interface and its implementation.

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.

We are done with the implementation, now its time to execute the application. The expected outputs will be as-

spring-mvc-login-code2java
Login Page
spring-mvc-login-code2java
Empty Fields
login-spring-mvc-code2java-failed
Login Failed Page
login-spring-mvc-code2java-success
Login Success Page

Download the complete source SpringMVC.

Hope this will help,

Regards,

Nikhil Naoghare.

2 thoughts on “Spring MVC login example”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.