Spring Security hello world example
Spring Security allows developer to integrate security features with J2EE web application easily, it highjacks incoming HTTP request via servlet filters, and implements “user defined” security checking.
In this tutorial, we show you how to integrate Spring Security 3.0 with Spring MVC web application to secure URL access. After implemented Spring security, to view the content of the page, users need to key in correct “username” and “password”.
Technologies used :
- Spring 3.0.5.RELEASE
- Spring Security 3.0.5.RELEASE
- Eclipse 3.6
- JDK 1.6
- Maven 3
Spring Security 3.0 requires Java 5.0 Runtime Environment or higher
1. Directory Structure
Review the final directory structure of this tutorial.

2. Spring Security Dependencies
To use Spring security 3.0, you need “spring-security-core.jar“, “spring-security-web.jar” and “spring-security-config.jar“. Spring libraries are available in Maven central repository.
File : pom.xml
<properties> <spring.version>3.0.5.RELEASE</spring.version> </properties> <dependencies> <!-- Spring 3 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- Spring Security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>${spring.version}</version> </dependency> </dependencies> </project>
3. Spring MVC Web Application
A simple Spring MVC to return a “hello.jsp” page, via URI “/welcome“. Later use Spring security to secure this URL access.
File : HelloController.java
package com.mkyong.common.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/welcome") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { model.addAttribute("message", "Spring Security Hello World"); return "hello"; } }
File : hello.jsp
<html> <body> <h1>Message : ${message}</h1> </body> </html>
File : mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> <context:component-scan base-package="com.mkyong.common.controller" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
4. Spring Security : User Authentication
Create a separate Spring configuration file to define Spring security related stuffs. It tells, only user with correct username “mkyong” and password “123456″ is allow to access URI “/welcome“.
Below Spring configuration should be self-explanatory.
File : spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd"> <http auto-config="true"> <intercept-url pattern="/welcome*" access="ROLE_USER" /> </http> <authentication-manager> <authentication-provider> <user-service> <user name="mkyong" password="123456" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> </beans:beans>
5. Integrate Spring Security
To integrate Spring security with web application, just declare “DelegatingFilterProxy” as servlet filter to intercept incoming request.
File : web.xml
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Spring MVC Application</display-name> <!-- Spring MVC --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/mvc-dispatcher-servlet.xml, /WEB-INF/spring-security.xml </param-value> </context-param> <!-- Spring Security --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
6. Demo
That’s all. But wait, where’s the login form? No worry, if you do not define login form, Spring will create a simple login form automatically.
Read this “Spring Security form login example” to understand how to create a custom login form in Spring Security.
1. Access “http://localhost:8080/SpringMVC/welcome“, Spring Security will intercept the request and redirect to “http://localhost:8080/SpringMVC/spring_security_login” automatically. And display the Spring predefined authentication form.
URL : http://localhost:8080/SpringMVC/spring_security_login

2. Error messages will be displayed if wrong username and password are provided.
URL : http://localhost:8080/SpringMVC/spring_security_login?login_error

3. If correct username and password are provided, Spring security will redirect to the original requested URL and display the content of the page.
URL : http://localhost:8080/SpringMVC/welcome

Download Source Code
References
- Spring Security Features
- Spring 3 MVC hello world example
- Spring Security form login example (authentication)

Hello Mykong…
Your tutorials are awesome….and gives easy start….i personally benifitted from first visiting your site to understand first here, and then study in-depth afterwards.
Thanks lot for all your efforts…
Hi, I am very new to Spring MVC. Please can you provide the good sample example about Spring Web flow with Controllers.
Thanks is Advance.
i cant run it im having this error
WARNING: No mapping found for HTTP request with URI [/Spring3MVC] in DispatcherServlet with name ‘mvc-dispatcher’
i would appreciate your help
thanks
The following annotation in the source code says that you need to type /welcome after the base url in the browser
@RequestMapping(“/welcome”)
So type
http://localhost:8080/SpringMVC/welcome
thanks for your answer. Ive tried that but Im still having the same problem:
HTTP Status 404 -
type Status report
message
descriptionThe requested resource () is not available.
GlassFish Server Open Source Edition 3.1.2.2
Hi Youg,
I have one doubt regarding this post. I imported this project into my workspace, and i executed it.
Only for the first time it went through the authentication process, from second time onwards without authentication it was showing my hello.jsp.What is happening exactly?
can u please clear my doubt. thank you
Its like Spoon feeding … Excellent
Thanks mkyong.
very nice and neat tutorial.
Easy to understand and execute.
Hi,
I have a simple question. What’s happend if in my application require to hide user and password for been viewed in the request. It’s there is such a configuration in spring to enable https ?
Thanks,
Marcello.
Hi mkyong
Thank you Very much. Based on your tutorial, i created the same one with details steps
in my blog. Here is the url
http://emrpms.blogspot.in/2012/11/spring-security-hello-world-example.html
nice and easy to understand…thanx for post
Hi yong…
My English so bad… So, I am sorry…
I have a problem…
I import the project to eclipse… But I take error (about “kind4″) So, I exist the similar maven project on eclipse (eclipse juno)… I run it on server(Apache Tomcat) I take error (the following)…
No mapping found for HTTP request with URI [/com.mkyong.common_SpringMVC_war_1.0-SNAPSHOT/] in DispatcherServlet with name ‘mvc-dispatcher’
You want to add “s” to the verbs you conjugate at the 3rd person.
In your first sentence: Spring Security allowS developer to integrate security features with J2EE web application easily, it highjackS incoming HTTP request via servlet filters, and implementS “user defined” security checking.
That’s 3 you forgot in one sentence. I’ve seen that on many tutorials and thought I’d let you know :)
Thanks for the tutorials and keep up the good work :)
Thanks Adrien, for the grammar correction :)
Hi,
You shouldn’t add /WEB-INF/mvc-dispatcher-servlet.xml to the config for the ContextLoaderListener. It would potential lead to beans getting initialized twice since the same beans will also be initialized from the DispatcherServlet.
The best tutorial on a given topic.
Thank you !!!
Thanks for this tutorial
Can you give us examples of using annotations in spring security i.e. @secured @preauthorize etc
if you add the / at the end of the url… i.e “http://localhost:8080/SpringMVC/welcome/” …. I don’t get the login form instead it shows the hell.jsp which is protected resource.
I am also facing same problem
Thanks !!! Very nice and easily understandable tutorial. Thanks !!!
I got following exception
SEVERE: Exception starting filter springSecurityFilterChain
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named ‘springSecurityFilterChain’ is defined
Same error
Same
I had the same problem, this fixed it: http://stackoverflow.com/a/12125135
Hi Yonng, it was great article, very simple and stright forward. i am able to run the application sucessfully. but i am having one doubt? when you type the following url
i am getting the page with username and password fields. i just wanted to know how this thing happend. we have not mentioned those things anyware in application. can u please clear my doubt if it is very basic also. thank you
Vijay,
If you dont define a custom login page,spring security will create one dynamically for you.
Regards,
Rippon
Hi Mkyong! Thanks for the superb article. One article I saw elsewhere said it would take days to figure out and use spring security in my own applications. I am very grateful to you
thanks a lot
and , if ssh2(struts2 spring3 hibernate3) project add spring security 3,some one will feel better ^!^ cause by I use ssh2 in project and learning…
Hi, thanks for your effort because this is a great post, for me appears an error:
No mapping found for HTTP request with URI [/com.mkyong.common_SpringMVC_war_1.0-SNAPSHOT] in DispatcherServlet with name ‘mvc-dispatcher’
I have checked the web.xml and it´s exactly as in your example. Then ¿why it doesn´t works for me?
Thanks in advance
Is Spring bean declared in “mvc-dispatcher-serlvet.xml” ?
You can add thw welcome property in web.xml :
/WEB-INF/pages/login.jsp
/WEB-INF/pages/login.html
this will load the right jsp
good luck
The examples are missing a @Controller annotation on the HelloController class. Add the annotation and everything should work fine.
Hi Mkyong,
Thanks for the great and simple applications.
It would be more better, if you provide jar files too, along with source code.
Regards
Sekhar
Almost all tutorial are Maven project. During compile or build phase, it will get all project dependencies automatically.
Hello Professor,
I’ve been working in an application using Stuts2 as a dispatcher, when I arrived to fix the security I heard about Spring Security, I’ve tried your tutorials and they was very interesting.
I’m now in a bad situation, cause all the tutorials are using spring as dispatcher and there is no sample using Struts2.
could you please advice me ?
Thanks you very much for you great work
Kind Regards
Please refer to Struts2 tutorials.
Thank you very much my Professor
Can you add the database connection configuration with Spring Security !!!??
Refer to this – Spring security form login using database.
Thank you very much .
My new question : if i want to use Spring applicationContext with Hibernate Template .. how can i do it ??
Please refer to this Spring tutorials, hibernate section.
You didnt understand me
i meant how to use all of them with spring security ( HibernateTimplate , Application Context )
No different, just a normal spring + hibernate integration, please refer to the Spring tutorial above.
Very nice, clean Spring Security tutorial. Much of the stuff out there is just too hard to follow. This one isn’t. Thanks!