Spring Securityでのログイン画面のカスタマイズ
Spring Security では、デフォルトでは Spring Security 標準のログイン画面が表示される。

これを、独自のログイン画面にカスタマイズする。
まず、独自のログイン画面を用意する。
src/main/webapp の直下に login.jsp を作成する。
formタグのactionは、Spring Security で標準のログイン処理に使われるURLを指定し、ユーザー名とパスワードも標準のログインで使用されるパラメータ名 j_username と j_password を使用する。
login.jsp
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<title>ログイン</title>
</head>
<body>
<h3>ユーザー名とパスワードを入力してください</h3>
<form name='f' action='/<%=request.getContextPath() %>/j_spring_security_check' method='POST'>
<table>
<tr><td>ユーザー名:</td><td><input type='text' name='j_username' value=''></td></tr>
<tr><td>パスワード:</td><td><input type='password' name='j_password'/></td></tr>
<tr><td colspan='2'><input name="submit" type="submit" value="Login"/></td></tr>
</table>
</form>
</body>
</html>
spring-security.xml に24行目の設定を追加して、権限なしでこのファイルにアクセスできるようにする。
spring-security.xml
<sec:http pattern="/" security="none"/>
<sec:http pattern="/index.jsp" security="none"/>
<sec:http pattern="/login.jsp" security="none"/>
<sec:http pattern="/css/**" security="none"/>
ここで、login.jsp にアクセスできることを確認する。

次に、権限が必要なページにアクセスしたときは、ログイン画面に遷移するように spring-security.xml に設定を追加する。
追加したのは、28行目の1行のみ。
spring-security.xml
<sec:http pattern="/" security="none"/>
<sec:http pattern="/index.jsp" security="none"/>
<sec:http pattern="/login.jsp" security="none"/>
<sec:http pattern="/css/**" security="none"/>
<sec:http auto-config="true">
<intercept-url pattern="/**" access="ROLE_USER" />
<sec:form-login login-page="/login.jsp" />
<sec:logout
logout-url="/logout"
logout-success-url="/"
invalidate-session="true"
delete-cookies="JSESSIONID" />
</sec:http>
これで、権限が必要なURLにアクセスしたとき、独自のログイン画面 login.jsp が表示されるようになる。
認証をパスできるユーザー名とパスワードを入力すれば、目的のページに遷移する。
ログインしたユーザー情報の取得
ログインしたユーザーを取得するには、コントローラの引数に Principal を追加する。
ここでは、追加した Princical から getName()メソッドでユーザー名を取得し、addAttribute() で name に値を設定している。
HomeController.java
@RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model, Principal p) {
model.addAttribute("name", p.getName());
model.addAttribute("title", "成績の検索");
return "home";
}
home.jsp では、EL式で名前を表示する。
home.jsp
<h1>${title}</h1>
<p>ようこそ ${name} さん。</p>
<p>受験番号を入力してください</p>
より詳細のユーザー情報が必要な場合は、DAO を使用して名前で検索してオブジェクトを取得する。
pom.xmlの追加(書き忘れ)
Spring Security を利用するために、pom.xml の最後に以下の設定を追加する。
<!-- Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>