Javatpoint Logo
Javatpoint Logo

Spring Security Project

In this tutorial, we will implement Spring Security with the Spring MVC framework. All the examples are Spring MVC and created using Maven project.

We are using Spring Security 5.0.0.RELEASE version and following are the maven dependencies, we used in all the examples.

To implement Spring Security in Spring application, we can configure it either by using XML or Java based configuration.

Let's see an example, in which we will use XML to configure the Spring Security.

Create a Maven Project

Click on File menu locate to New→Maven Project, as we did in the following screen shot.

Spring Security XML Example 1

Select Project Name and Location

Spring Security XML Example 2

Provide Project Name

Provide project name and select packaging type as war (Web Archive) as we did below.

Spring Security XML Example 3

Finish the project and it will create an empty directory structure of the project like below.

Spring Security XML Example 4

Initially, it is empty. So, let's create a Spring MVC application and integrate with Spring Security.

This is our project layout. It contains a controller, three XML files and two JSP files.

Spring Security XML Example 5

Spring Security Project Source Code

Our project name is springsecurity and contains the following source files.

Controller

HomeController.java

Spring Security Configuration

spring-security.xml

Servlet Dispatcher

spring-servlet.xml

Web Descriptor

web.xml

Project Dependencies

pom.xml

View Pages

home.jsp

privatePage.jsp

home.jsp

Output

This example is executed using Apache Tomcat v9.0. After running it produces the following output to the browser.

Initially, it renders home.jsp page that displays the following output.

Spring Security XML Example 6

We added spring security to admin page, if we enter /admin to the browser, application produces the below output.

Request URL : http://localhost:8080/springsecurity/admin

Spring Security XML Example 7

Now, this the actual magic that spring security provides to protect resources from unauthentic users.

This is spring security provided module, we did not create it. It also validate the user input.

Providing wrong credentials.

Spring Security XML Example 8

If we provide wrong login credentials, it will validate with the user name and password, we mentioned in spring-security.xml file.

After validating, if login credentials are incorrect, it throws an error message.

Spring Security XML Example 9

Well, in this example, we have seen the Spring Security's login module and how it validates corresponds to the provided user name and password.

In next, topic we will implement further logic like: render user after login successfully.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA