2013年10月28日月曜日

1-6-1. 認証機能のカスタマイズ

前回作成した認証機能を、前々回までに作成した DB とログイン画面を使って認証するように修正します。

DB に直接接続して認証

applicationContext-security.xml を編集
 http にログインページの URL を指定し、さらにどのユーザからもこのページアクセスできるように設定します。
 authentication-manager で DB 接続設定として applicationContext.xml で登録した dataSource を指定し、ユーザー情報を取得する SQL 文を記述します。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns="http://www.springframework.org/schema/security"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <!-- アクセス設定。 -->
  <http auto-config="true">
    <form-login login-page="/login" /> <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/**" access="ROLE_USER" /> </http>
  <!-- アカウント情報。 --> <!-- <authentication-manager> <authentication-provider> <user-service> <user name="admin" password="admin" authorities="ROLE_SUPERVISOR, ROLE_USER" /> <user name="user" password="user" authorities="ROLE_USER" /> </user-service> </authentication-provider> </authentication-manager> -->
<!-- SQL で DB からユーザー情報を取得。 --> <authentication-manager> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="select loginid as username, password, true as enabled from user_mst where loginid = ?" authorities-by-username-query="select loginid as username, 'ROLE_USER' as authority from user_mst where loginid = ?" /> </authentication-provider> </authentication-manager>
</beans:beans>
login.jsp の修正
 サーバーに送信するアドレスやパラメータ名を、前回表示されたログイン画面に合わせます。
エラーメッセージはセッションから取得できます。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 
/**
 * ログインページ。
 * 
 * @author 2013/10/20 matsushima
 */
 -->
<!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>index</title>
</head>
<body>
	<form action="<%=request.getContextPath() %>/j_spring_security_check" method="post">
		<label for="loginid">ログインID</label>
		<input type="text" id="loginid" name="j_username" value="${user.loginid}" />
		<br />
		<label for="password">パスワード</label>
		<input type="password" id="password" name="j_password" value="${user.password}" />
		<br />
		<div style="color: red;">${message}${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}</div>
		<input type="submit" name="login" value="ログイン" />
	</form>
</body>
</html>
index.jsp
 username は SecurityContextHolder から取得できます。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>index</title>
</head>
<body>
index page<br />
<%--<% if (null != request.getAttribute("user")) { %> ${user.name} さんこんにちは。 <% } %>--%>
<%@ page import="org.springframework.security.core.context.SecurityContextHolder" %> <%@ page import="org.springframework.security.core.userdetails.UserDetails" %> <% if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserDetails) { %> <%=((UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername() %> さんこんにちは。 <% } %>
</body> </html>
サーバを起動し、ブラウザから http://localhost:8080/spring-test/index にアクセスします。
DB に登録したログインID、パスワードを入力してログインボタンをクリックし、
xxx さんこんにちは。と表示されれば OK です。


ユーザー情報取得コードを実装して認証

applicationContext-security.xml 編集
 authentication-provider に org.springframework.security.authentication.dao.DaoAuthenticationProvider を 指定します。
userDetailsService には UserDetailsService インターフェースを実装したクラスを指定します。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns="http://www.springframework.org/schema/security"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <!-- アクセス設定。 -->
  <http auto-config="true">
    <form-login login-page="/login" />
    <intercept-url pattern="/login" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/**" access="ROLE_USER" />
  </http>

  <!-- アカウント情報を指定して認証。 -->
  <!-- <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="admin" password="admin" authorities="ROLE_SUPERVISOR, ROLE_USER" />
        <user name="user" password="user" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager> -->
  <!-- SQL で DB からユーザー情報を取得して認証。 -->
  <!-- <authentication-manager>
    <authentication-provider>
      <jdbc-user-service data-source-ref="dataSource"
        users-by-username-query="select loginid as username, password, true as enabled from user_mst where loginid = ?"
        authorities-by-username-query="select loginid as username, 'ROLE_USER' as authority from user_mst where loginid = ?"
      />
    </authentication-provider>
  </authentication-manager> -->
  <!-- UserDetailsService クラスを実装して認証。 --> <authentication-manager> <authentication-provider ref="authenticationProvider" /> </authentication-manager> <beans:bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <beans:property name="userDetailsService" ref="userDetailsService" /> </beans:bean> <beans:bean id="userDetailsService" class="jp.matsushima.spring_test.service.UserDetailsServiceImpl" />
</beans:beans>
Service, DAO の実装
 UserDetailsService インターフェースを実装したクラスを実装します。
loadUserByUsername メソッドのパラメータに username が渡ってくるので、そこからユーザー情報を取得し、UserDetails bean で返します。
package jp.matsushima.spring_test.service;

import java.util.ArrayList;
import java.util.Collection;

import jp.matsushima.spring_test.dao.UserDao;
import jp.matsushima.spring_test.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * ユーザー情報サービス。
 * 
 * @author 2013/10/25 matsushima
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserDao userDao;

	class MyUserDetails implements UserDetails {

		private static final long serialVersionUID = 1L;

		/** ユーザーマスタ。 */
		private User user;

		public MyUserDetails(User user) {
			super();
			this.user = user;
		}

		/**
		 * ユーザーマスタ。を取得します。
		 * @return ユーザーマスタ。
		 */
		public User getUser() {
		    return user;
		}

		/**
		 * ユーザーマスタ。を設定します。
		 * @param user ユーザーマスタ。
		 */
		public void setUser(User user) {
		    this.user = user;
		}

		@Override
		public Collection<? extends GrantedAuthority> getAuthorities() {
			System.out.println("getAuthorities");
			ArrayList<GrantedAuthority> result = new ArrayList<>();
			result.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			result.add(new SimpleGrantedAuthority("ROLE_USER"));
			return result;
		}

		@Override
		public String getPassword() {
			System.out.println("getPassword");
			return user.getPassword();
		}

		@Override
		public String getUsername() {
			System.out.println("getUsername");
			return user.getLoginid();
		}

		@Override
		public boolean isAccountNonLocked() {
			System.out.println("isAccountNonLocked");
			return true;
		}

		@Override
		public boolean isEnabled() {
			System.out.println("isEnabled");
			return true;
		}

		@Override
		public boolean isAccountNonExpired() {
			System.out.println("isAccountNonExpired");
			return true;
		}

		@Override
		public boolean isCredentialsNonExpired() {
			System.out.println("isCredentialsNonExpired");
			return true;
		}
	}

	/**
	 * ユーザー名からユーザー情報を取得。
	 * 
	 * @param username
	 * @return
	 */
	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = userDao.selectByLoginid(username);
		return (null == user ? null : new MyUserDetails(user));
	}
}
package jp.matsushima.spring_test.dao;

import jp.matsushima.spring_test.model.User;

/**
 * ユーザーマスタ。
 * 
 * @author 2013/10/15 matsushima
 *
 */
public interface UserDao {

	/**
	 * ログイン ID、パスワードからユーザーを取得。
	 * 
	 * @param param
	 * @return
	 */
	public User selectForAuth(User param);

/** * ログイン ID からユーザーを取得。 * * @param loginid * @return */ public User selectByLoginid(String loginid);
}
package jp.matsushima.spring_test.dao;

import jp.matsushima.spring_test.model.User;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * ユーザーマスタ。
 * 
 * @author 2013/10/15 matsushima
 */
@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	/**
	 * ログイン ID、パスワードからユーザーを取得。
	 * 
	 * @param param
	 * @return
	 */
	@Override
	public User selectForAuth(User param) {
		return (User)sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("loginid", param.getLoginid()))
				.add(Restrictions.eq("password", param.getPassword()))
				.uniqueResult();
	}

/** * ログイン ID からユーザーを取得。 * * @param loginid * @return */ @Override public User selectByLoginid(String loginid) { return (User)sessionFactory.getCurrentSession().createCriteria(User.class) .add(Restrictions.eq("loginid", loginid)) .uniqueResult(); }
}
サーバを起動し、ブラウザから http://localhost:8080/spring-test/index にアクセスします。
DB に登録したログインID、パスワードを入力してログインボタンをクリックし、
xxx さんこんにちは。と表示されれば OK です。

プロジェクトの最新版はこちらで公開しています。
https://github.com/matsushima-terunao/blog_java/

← 1-6. 認証機能追加
↑ 一覧

2013年10月25日金曜日

1-6. 認証機能追加

pom.xml にライブラリを追加
 spring-security を使用します。ただし spring-asm は 3.2 で spring-core に統合されたため、依存関係から外します。
  pom.xml -> Dependency Hierachy -> Filter: spring-asm
  spring-asm : 3.0.7.RELEASE [compile] -> Exclude Maven Artifact... -> OK
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>jp.matsushima</groupId>
  <artifactId>spring-test</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-test Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <build>
    <finalName>spring-test</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <encoding>UTF-8</encoding>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>3.2.4.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>3.2.4.RELEASE</version>
    </dependency>
    <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>3.1.4.RELEASE</version> <exclusions> <exclusion> <artifactId>spring-asm</artifactId> <groupId>org.springframework</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>3.1.4.RELEASE</version> </dependency>
    <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.6.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
web.xml の編集
 filter にユーザー認証を行う org.springframework.web.filter.DelegatingFilterProxy を追加します。
 設定を別ファイルにするため、listener に org.springframework.web.context.ContextLoaderListener を指定し、context-param の contextConfigLocation に設定ファイルのパスを指定します。
ここでは同時に既存の /WEB-INF/dispatcher-servlet.xml を /main/src/resources/applicationContext.xml に変更し、spring-security の設定ファイルに /main/src/resources/applicationContext-security.xml を指定しています。
 filter-mapping に filter が呼び出される url を指定します。
ここではすべてのリクエストで Filter を通るように指定しています。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">

  <display-name>spring-test Web Application</display-name>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <!-- HTTP リクエストを Controller にディスパッチするサーブレット。 -->
    <!-- contextConfigLocation を指定しない場合、/WEB-INF/{servlet-name}-servlet.xml がロードされる。 -->
    <!-- classpath: プレフィックスで /src/main/resources 配下のパスを指定できる。 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param>
    <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
  <!-- WebApplicationContext を生成する Listener。 --> <!-- listener を登録しない場合、servlet で指定したファイルがロードされる --> <!-- (servlet の contextConfigLocation の指定値または /WEB-INF/{servlet-name}-servlet.xml)。 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- applicationContext.xml のパスを変更する場合に指定。 --> <!-- contextConfigLocation を指定しない場合、/WEB-INF/applicationContext.xml がロードされる。 --> <!-- classpath: プレフィックスで /src/main/resources 配下のパスを指定できる。 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml,classpath:applicationContext-security.xml</param-value> </context-param> <!-- ユーザー認証を行う Filter。 --> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <!-- Filter を行う URL。 --> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
</web-app>
applicationContext-security.xml の編集
 http にアクセス設定を指定します。
<intercept-url pattern="/**" access="ROLE_USER" /> ですべての URL で ROLE_USER のみアクセス可能にさせます。
ほかの設定は auto-config="true" の指定によって既定値に設定されます。
 authentication-manager にアカウント情報を指定します。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:beans="http://www.springframework.org/schema/beans"
  xmlns="http://www.springframework.org/schema/security"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">

  <!-- アクセス設定。 -->
  <http auto-config="true">
    <intercept-url pattern="/**" access="ROLE_USER" />
  </http>

  <!-- アカウント情報。 -->
  <authentication-manager>
    <authentication-provider>
      <user-service>
        <user name="admin" password="admin" authorities="ROLE_SUPERVISOR, ROLE_USER" />
        <user name="user" password="user" authorities="ROLE_USER" />
      </user-service>
    </authentication-provider>
  </authentication-manager>

</beans:beans>
サーバを起動し、ブラウザから http://localhost:8080/spring-test/index にアクセスします。
ログインページが表示され、ログイン後、インデックスページに移動すれば OK です。


プロジェクトの最新版はこちらで公開しています。
https://github.com/matsushima-terunao/blog_java/

→ 1-6-1. 認証機能のカスタマイズ
← 1-5-2. Spring MVC 3 + Hibernate 4 + HSQLDB
↑ 一覧

2013年10月21日月曜日

1-5. Spring MVC 3 + Hibernate 4 + MySQL

pom.xml にライブラリを追加
 今回使用するのは以下のライブラリです。
  spring-orm: O/R マッピングとトランザクション管理
  spring-tx: トランザクション管理
  commons-dbcp: DB のコネクションプールを管理
  hibernate-core: Hibernate のライブラリ
  mysql-connector-java: MySQL の JDBC ドライバ
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>jp.matsushima</groupId>
  <artifactId>spring-test</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-test Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <build>
    <finalName>spring-test</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <encoding>UTF-8</encoding>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>3.2.4.RELEASE</version>
    </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.6.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency>
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>   </dependencies> </project>
dispatcher-servlet.xml
 mvc:annotation-driven, context:component-scan の指定で、jp.matsushima.spring_test 配下のクラスのアノテーションを有効にします。
 dataSource Bean で DB の接続情報を指定します。
org.apache.commons.dbcp.BasicDataSource はコネクションプールをサポートする DataSource です。
 sessionFactory Bean で SessionFactory を指定します。
org.springframework.orm.hibernate4.LocalSessionFactoryBean は Spring で Hibernate をサポートするセッション管理クラスです。
 transactionManager Bean で TransactionManager を指定します。
org.springframework.orm.hibernate4.HibernateTransactionManager は Spring で Hibernate をサポートするトランザクション管理クラスです。
<?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:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

  <!-- @Controller の付いたクラスを Controller として登録。 -->
  <mvc:annotation-driven />

  <!-- @Controller, @Repository, @Service, @Component の付いたコンポーネントを検出するパッケージの指定。 -->
  <context:component-scan base-package="jp.matsushima.spring_test" />

  <!-- @Controller から view へのマッピング方法の指定。 -->
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp"/>
  </bean>

  <!-- DB 接続設定。 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- セッション管理。 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="packagesToScan" value="jp.matsushima.spring_test.model" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- トランザクション管理。 --> <!-- @Transactional によるトランザクション指定を有効。 --> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
</beans>
jp.matsushima.spring_test.model.User
 sessionFactory の packagesToScan に指定したパッケージ配下にテーブルに対応した Model クラスを作成します。
@Table にテーブル名、@Column にカラム名を指定します。
まず、private でフィールドを記述し、getter/setter は Source -> Generate Getters and Setters... または Limmy で生成します。
package jp.matsushima.spring_test.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * ユーザーマスタ。
 * 
 * @author 2013/10/15 matsushima
 */
@Entity
@Table(name = "user_mst")
public class User {

	/** ID: id, serial, , not null, IDX:, UQ:, PK:○, FK:,  */
	@Id
	@Column(name = "id")
	@GeneratedValue
	private int id;

	/** ログインID: loginid, varchar(100), , not null, IDX:, UQ:, PK:, FK:,  */
	@Column(name = "loginid")
	private String loginid;

	/** パスワード: password, text, , not null, IDX:, UQ:, PK:, FK:,  */
	@Column(name = "password")
	private String password;

	/** 名前: name, text, , not null, IDX:, UQ:, PK:, FK:,  */
	@Column(name = "name")
	private String name;

	/**
	 * ID: id, serial, , not null, IDX:, UQ:, PK:○, FK:,を取得します。
	 * @return ID: id, serial, , not null, IDX:, UQ:, PK:○, FK:,
	 */
	public int getId() {
	    return id;
	}

	/**
	 * ID: id, serial, , not null, IDX:, UQ:, PK:○, FK:,を設定します。
	 * @param id ID: id, serial, , not null, IDX:, UQ:, PK:○, FK:,
	 */
	public void setId(int id) {
	    this.id = id;
	}

	/**
	 * ログインID: loginid, varchar(100), , not null, IDX:, UQ:, PK:, FK:,を取得します。
	 * @return ログインID: loginid, varchar(100), , not null, IDX:, UQ:, PK:, FK:,
	 */
	public String getLoginid() {
	    return loginid;
	}

	/**
	 * ログインID: loginid, varchar(100), , not null, IDX:, UQ:, PK:, FK:,を設定します。
	 * @param loginid ログインID: loginid, varchar(100), , not null, IDX:, UQ:, PK:, FK:,
	 */
	public void setLoginid(String loginid) {
	    this.loginid = loginid;
	}

	/**
	 * パスワード: password, text, , not null, IDX:, UQ:, PK:, FK:,を取得します。
	 * @return パスワード: password, text, , not null, IDX:, UQ:, PK:, FK:,
	 */
	public String getPassword() {
	    return password;
	}

	/**
	 * パスワード: password, text, , not null, IDX:, UQ:, PK:, FK:,を設定します。
	 * @param password パスワード: password, text, , not null, IDX:, UQ:, PK:, FK:,
	 */
	public void setPassword(String password) {
	    this.password = password;
	}

	/**
	 * 名前: name, text, , not null, IDX:, UQ:, PK:, FK:,を取得します。
	 * @return 名前: name, text, , not null, IDX:, UQ:, PK:, FK:,
	 */
	public String getName() {
	    return name;
	}

	/**
	 * 名前: name, text, , not null, IDX:, UQ:, PK:, FK:,を設定します。
	 * @param name 名前: name, text, , not null, IDX:, UQ:, PK:, FK:,
	 */
	public void setName(String name) {
	    this.name = name;
	}
}
jp.matsushima.spring_test.dao.UserDao
jp.matsushima.spring_test.dao.UserDaoImpl
 クエリを定義、実装します。
sessionFactory は @Autowired によってインジェクションされます。
package jp.matsushima.spring_test.dao;

import jp.matsushima.spring_test.model.User;

/**
 * ユーザーマスタ。
 * 
 * @author 2013/10/15 matsushima
 *
 */
public interface UserDao {

	public User selectForAuth(User param);
}
package jp.matsushima.spring_test.dao;

import jp.matsushima.spring_test.model.User;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 * ユーザーマスタ。
 * 
 * @author 2013/10/15 matsushima
 */
@Repository
public class UserDaoImpl implements UserDao {

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public User selectForAuth(User param) {
		return (User)sessionFactory.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("loginid", param.getLoginid()))
				.add(Restrictions.eq("password", param.getPassword()))
				.uniqueResult();
	}
}
jp.matsushima.spring_test.service.UserService
jp.matsushima.spring_test.service.UserServiceImpl
 ビジネスロジックを定義、実装します。
userDao は @Autowired によってインジェクションされます。
package jp.matsushima.spring_test.service;

import jp.matsushima.spring_test.model.User;

/**
 * ユーザーサービス。
 * 
 * @author 2013/10/15 matsushima
 */
public interface UserService {

	/**
	 * 認証。
	 * 
	 * @param param
	 * @return
	 */
	public User auth(User param);
}
package jp.matsushima.spring_test.service;

import jp.matsushima.spring_test.dao.UserDao;
import jp.matsushima.spring_test.model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * ユーザーサービス。
 * 
 * @author 2013/10/15 matsushima
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao userDao;

	/**
	 * 認証。
	 * 
	 * @param param
	 * @return
	 */
	@Override
	@Transactional
	public User auth(User param) {
		if ((null == param.getLoginid()) || (param.getLoginid().isEmpty())
				|| (null == param.getPassword()) || (param.getPassword().isEmpty())) {
			return null;
		}
		return userDao.selectForAuth(param);
	}
}
jp.matsushima.spring_test.controller.LoginController
 リスエストを処理する Controller を実装します。
userService は @Autowired によってインジェクションされます。
 最初の login() は GET の /login リクエストで呼び出され、login.jsp を表示します。
 次の login() は POST の /login で login パラメータがある(後述の login.jsp でログインボタンを押したとき)リクエストで呼び出されます。
userService.auth(param) で送信された loginid, password で user_mst から検索します。
見つかった場合 index.jsp にフォワードします。そのとき user という名前で検索した User を登録します。
見つからなかった場合 login.jsp にフォワードします。そのとき message という名前でエラーメッセージを登録します。
package jp.matsushima.spring_test.controller;

import jp.matsushima.spring_test.model.User;
import jp.matsushima.spring_test.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.ModelAndView;

/**
 * ログインページ。
 * 
 * @author 2013/10/16 matsushima
 */
@Controller
@RequestMapping("/login")
public class LoginController {

	/** ユーザーサービス。 */
	@Autowired
	private UserService userService;

	/**
	 * ログインページ。
	 * 
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	/**
	 * ログイン。
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, params = {"login"})
	public ModelAndView login(User param) {
		// 認証。
		User result = userService.auth(param);
		if (null != result) {
			// ログイン -> 認証成功: インデックスページ
			return new ModelAndView("index", "user", result);
		} else {
			// ログイン -> 認証失敗: ログインページ
			return new ModelAndView("login", "message", "ログインIDまたはパスワードが違います。");
		}
	}
}
login.jsp
 ログインページを作成します。
${user.loginid}, ${user.password} で送信されたパラメータが再度表示されます。
${message} は失敗時に登録されたエラーメッセージです。
 ログインボタンを押したとき、POST で login パラメータが送信されます。
これによって、2つ目の login() の
@RequestMapping(method = RequestMethod.POST, params = {"login"})
に一致し、このメソッドが呼ばれます。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- 
/**
 * ログインページ。
 * 
 * @author 2013/10/20 matsushima
 */
 -->
<!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>index</title>
</head>
<body>
	<form action="<%=request.getContextPath() %>/login" method="post">
		<label for="loginid">ログインID</label>
		<input type="text" id="loginid" name="loginid" value="${user.loginid}" />
		<br />
		<label for="password">パスワード</label>
		<input type="password" id="password" name="password" value="${user.password}" />
		<br />
		<div style="color: red;">${message}</div>
		<input type="submit" name="login" value="ログイン" />
	</form>
</body>
</html>
index.jsp
 成功したときに登録された user を表示するように修正します。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>index</title>
</head>
<body>
index page<br />
<% if (null != request.getAttribute("user")) { %> ${user.name} さんこんにちは。 <% } %>
</body> </html>
サーバを起動し、ブラウザから http://localhost:8080/spring-test/login にアクセスします。
DB に登録したログインID、パスワードを入力してログインボタンをクリックし、
xxx さんこんにちは。と表示されれば OK です。

プロジェクトの最新版はこちらで公開しています。
https://github.com/matsushima-terunao/blog_java/

→ 1-5-2. Spring MVC 3 + Hibernate 4 + HSQLDB
← 1-4. MySQL のインストールからデータ作成まで
↑ 一覧

2013年10月19日土曜日

1-4. MySQL のインストールからデータ作成まで

MySQL のインストール
Windows
 MySQL のサイトから、
  http://www-jp.mysql.com/downloads/
 MySQL Community Server 5.6.14 をダウンロード、インストール
  http://dev.mysql.com/downloads/mysql/
Ubuntu
 tasksel で LAMP Server をインストールします。
 LAMP Server をインストールすると、Apache, MySQL, PHP がインストールされるので、個別にインストールする必要がありません。
  sudo apt-get install tasksel
  sudo tasksel
  [*] LAMP server -> <了解>
  あとは手順通り
 個別でインストールする場合
  sudo apt-get install mysql-server-5.5
 別途 MySQL Workbench のインストール
  sudo apt-get install mysql-workbench
データの作成
 MySQL Workbench を起動

 Database -> Connect to Database
 Stored Connection: Local instance MySQL56 -> OK
 スキーマを作成する場合
  右側の Navigator -> SCHEMAS からスキーマを右クリックし、Create Schema...
  Name: スキーマ名 -> Apply -> Apply -> Finish
 テーブル作成
  test -> Tables -> Create Table...
  下の画像を参考に、カラムを追加
  Apply -> Apply -> Finish

 レコード追加
  user_mst -> Select Rows - 1000 Limits
  下の画像を参考に、レコードを追加
  Apply -> Apply -> Finish

Eclipse からも DB に接続することができます。
 Data Source Explorer タブを選択
 (タブがないときは Window -> Show View -> Data Source Explorer)
 Database Connections -> New...
 MySQL -> Next
 インストール時、データ作成時に指定した情報を入力
  Database: test
  URL: jdbc:mysql://localhost:3306/test <- test はデータ作成時のスキーマ名
  User name: root <- インストール時に指定したアカウント
  Password: root <- インストール時に指定したアカウント
  Next


プロジェクトの最新版はこちらで公開しています。
https://github.com/matsushima-terunao/blog_java/

→ 1-5. Spring MVC 3 + Hibernate 4 + MySQL
← 1-3. Spring 開発用に設定、プログラム作成
↑ 一覧