>http://www.mkyong.com/spring-security/spring-security-hello-world-example/
In this tutorial,we will show you how to integrate Spring Security with a Spring MVC web application to secure a URL access. After implementing Spring Security,to access the content of an “admin” page,users need to key in the correct “username” and “password”.
Technologies used :
- Spring 3.2.8.RELEASE
- Spring Security 3.2.3.RELEASE
- Eclipse 4.2
- JDK 1.6
- Maven 3
Spring Security 3.0 requires Java 5.0 Runtime Environment or higher
1. Project Demo
2. Directory Structure
Review the final directory structure of this tutorial.
3. Spring Security Dependencies
To use Spring security,you needspring-security-web
andspring-security-config
.
<properties> <jdk.version>1.6</jdk.version<spring.version>3.2.8.RELEASE</spring.version<spring.security.version>3.2.3.RELEASE</spring.security.version<jstl.version>1.2</jstl.version> </properties> <dependencies> <!-- Spring dependencies --> <dependency> <groupId>org.springframework</groupId<artifactId>spring-core</artifactId<version>${spring.version}</version</dependency> >spring-web>spring-webmvc> <!-- Spring Security --> >org.springframework.security>spring-security-web>${spring.security.version}>spring-security-config> <!-- jstl for jsp page --> >jstl>${jstl.version}</dependencies>
4. Spring MVC Web Application
A simple controller :
- If URL =
/welcome
or/
,return hello page. - If URL =
/admin
,return admin page.
Later,we will show you how to use Spring Security to secure the “/admin” URL with a user login form.
package com.mkyong.web.controller; import org.springframework.stereotype.Controller; .bind.annotation.RequestMapping.RequestMethod.servlet.ModelAndView; @Controller public class HelloController { @RequestMapping(value = { "/", "/welcome**" }= RequestMethod.GET) public ModelAndView welcomePage() { ModelAndView model = new ModelAndView); model.addObject("title""Spring Security Hello World""message""This is welcome page!"setViewName"hello"; return model; } = "/admin**"adminPage"This is protected page!""admin"; } }
Two JSP pages.
<%@page session="false"%> <html<body<h1>Title : ${title}</h1>Message : ${message}</body</html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@page session="true"%> <c:if test="${pageContext.request.userPrincipal.name != null}"> <h2>Welcome : ${pageContext.request.userPrincipal.name} | <a href="<c:url value"/j_spring_security_logout" />" > logout</a></h2</c:if mvc-dispatcher-servlet.xml