spring security起步二:自定义登录页

来源:互联网 发布:阿里云的公共dns 编辑:程序博客网 时间:2024/04/30 20:59

在上一篇文章 spring security 起步:框架搭建 最后,我们可以看到spring security自动为我们生成了一个默认的登录页。首先呢 那个登录页太丑,其次呢登录时我们也想实现一些其他的功能:比如找回密码,Remember me等。那么 我们如何实现自定义登录页功能呢?

添加登录页 login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><style>.error {padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;color: #a94442;background-color: #f2dede;border-color: #ebccd1;}.msg {padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;color: #31708f;background-color: #d9edf7;border-color: #bce8f1;}#login-box {width: 300px;padding: 20px;margin: 100px auto;background: #fff;-webkit-border-radius: 2px;-moz-border-radius: 2px;border: 1px solid #000;}</style></head><body onload='document.loginForm.username.focus();'><div id="login-box"><h2>请输入您的用户名与密码</h2><form name='loginForm' action="" method='POST'><table><tr><td>用户:</td><td><input type='text' name='username' value=''></td></tr><tr><td>密码:</td><td><input type='password' name='password' /></td></tr><tr><td colspan='2'><input name="submit" type="submit" value="登录" /></td></tr></table></form></div></body></html>


实现登录的Controller

@Controllerpublic class LoginController {@RequestMapping(value = "/login", method = RequestMethod.GET)public String loginPage() {return "login";}}

配置spring security

在上面的配置中,通过指定url /login 跳转到login.jsp页面。那么接下来就是告诉spring security 我想使用自己定义的登录页,而且还要告诉spring security不能拦截我的登录页面。具体配置如下:

<?xml version="1.0" encoding="UTF-8"?><bean:beans xmlns="http://www.springframework.org/schema/security"xmlns:bean="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.xsdhttp://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"><http pattern="/login" security="none"></http><http auto-config="true" use-expressions="true"><intercept-url pattern="/*" access="hasRole('ROLE_USER')" /><form-login login-page="/login" /></http><authentication-manager alias="authenticationManager"><authentication-provider><user-service><user authorities="ROLE_USER" name="guest" password="guest" /></user-service></authentication-provider></authentication-manager></bean:beans>

启动项目 可以看到我们自定义的登录页面

源码下载

https://github.com/SmallBadFish/spring_security_demo/archive/0.1.0-customlogin.zip

1 0
原创粉丝点击