官方说明文档

https://docs.spring.io/spring-security/site/docs/4.2.4.RELEASE/reference/htmlsingle/#ns-config

添加pom

<dependencies><!--...otherdependencyelements...--><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId><version>5.0.3.RELEASE</version></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId><version>5.0.3.RELEASE</version></dependency></dependencies>


2.添加Spring Security配置

<b:beansxmlns="http://www.springframework.org/schema/security"xmlns:b="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security.xsd"><http/><user-service><username="user"password="password"authorities="ROLE_USER"/></user-service></b:beans>


3.启用Spring Security:

<?xmlversion="1.0"encoding="UTF-8"?><web-appversion="3.0"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"><!---LocationoftheXMLfilethatdefinestherootapplicationcontext-AppliedbyContextLoaderListener.--><context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring/*.xml</param-value></context-param><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><!---Loadstherootapplicationcontextofthiswebappatstartup.-Theapplicationcontextisthenavailablevia-WebApplicationContextUtils.getWebApplicationContext(servletContext).--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>

4.新建文件:src/main/webapp/index.jsp

<body><divclass="container"><h2>Thisissecured!</h2><p>Hello<b><c:outvalue="${pageContext.request.remoteUser}"/></b></p><c:urlvar="logoutUrl"value="/logout"/><formclass="form-inline"action="${logoutUrl}"method="post"><inputtype="submit"value="Logout"/><inputtype="hidden"name="${_csrf.parameterName}"value="${_csrf.token}"/></form></div></body>