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 のインストールからデータ作成まで
↑ 一覧