3. 修改web.xml,增加springSecurityFilterChain
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/app-security.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
4. 增加app-security.xml
<?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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/hello"
access="ROLE_ADMIN" />
<security:intercept-url pattern="/**" access="ROLE_USER" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_USER"
password="stevex" />
<security:user authorities="ROLE_USER, ROLE_ADMIN"
password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
5. 修改HomeController.java,增加hello函数
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
//produces="text/plain" 必须有,否则会有乱码
@RequestMapping(value = "/hello", method = RequestMethod.GET, produces="text/plain")
@ResponseBody
public String hello(){
logger.info("request coming!");
return "Hello Stevex, you are so hard!";
}
}
6. 运行应用进行测试
大功告成!
Spring Web MVC Security 下载地址:
具体下载目录在 /2014年资料/2月/28日/Spring Security 学习之HTTP表单验证