上一篇https://blog.csdn.net/stark_jc/article/details/79778962采用了Spring+Struts2+Hibernate的方式实现了登录,且上次采用的是XML配置(包括实体类与数据表之间的配置、以及Struts2的action映射关系的配置),本文以SpringMVC取代Struts2,在路径和处理器以及实体类属性和数据表字段的映射关系上使用注解.
UserInfo,采用注解的方式
package com.digital.entity;
import javax.persistence.*;
@Entity
@Table(name = "user_info", catalog = "digital")
public class UserInfo {
private int id;
private String userName;
private String password;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "userName", length = 16)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "password", length = 16)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// 无参构造
public UserInfo() {
}
// 有参构造
public UserInfo(String userName, String password) {
this.userName = userName;
this.password = password;
}
}
applicationContext
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql:///digital" />
<property name="user" value="root" />
<property name="password" value="admin" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="10" />
bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
prop>
props>
property>
<property name="annotatedClasses">
<list>
<value>com.digital.entity.UserInfovalue>
list>
property>
bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
bean>
<context:annotation-config />
<context:component-scan base-package="com.digital">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
context:component-scan>
<tx:annotation-driven transaction-manager="transactionManager" />
beans>
package com.digital.dao;
import java.util.List;
import com.digital.entity.UserInfo;
public interface UserInfoDAO {
public List search(UserInfo cond);
}
package com.digital.dao.impl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.digital.dao.UserInfoDAO;
import com.digital.entity.UserInfo;
//使用@Repository注解在Spring容器中注册实例名为userInfoDAO的UserInfoDAOImpl实例
@Repository("userInfoDAO")
public class UserInfoDAOImpl implements UserInfoDAO {
// 通过@Autowired注解注入Spring容器中的SessionFactory实例
@Autowired
SessionFactory sessionFactory;
@Override
public List search(UserInfo cond) {
/*
* 使用HQL查询,优点:
* 1. 直接针对实体类和属性进行查询,不用写繁琐的SQL语句
* 2. 查询结果直接保存在List对象中,不用再次封装
* 3. 可以通过配置dialect属性,对不同数据库自动生成不同的用于执行的SQL语句。
*
*/
// 获得session
/*Session session = sessionFactory.getCurrentSession();
String hql = "from UserInfo as ui where ui.userName=:userName and ui.password=:password";
Query query = session.createQuery(hql);
query.setString("userName", cond.getUserName());
query.setString("password", cond.getPassword());
List uiList = query.list();
return uiList;*/
/*
* 使用QBC查询
*
*/
List uiList = null;
// 获得session
Session session = sessionFactory.getCurrentSession();
// 创建Criteria对象
Criteria c = session.createCriteria(UserInfo.class);
// 使用Example工具类创建示例对象
Example example = Example.create(cond);
// 为Criteria对象指定示例对象example作为查询条件(所有非空属性都将作为查询条件,如果全为空,则全匹配)
c.add(example);
// 执行查询
uiList = c.list();
// 返回结果
return uiList;
}
}
由于添加了注解,SpringIoC会自动扫描装配bean,也就不用在applicationContext里面注册了。
package com.digital.service;
import java.util.List;
import com.digital.entity.UserInfo;
public interface UserInfoService {
public List login(UserInfo cond);
}
package com.digital.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.digital.dao.UserInfoDAO;
import com.digital.entity.UserInfo;
import com.digital.service.UserInfoService;
//使用@Service注解在Spring容器中注册名为userInfoService的UserInfoServiceImpl实例
@Service("userInfoService")
//使用@Transactional注解实现事务管理
@Transactional
public class UserInfoServiceImpl implements UserInfoService {
//使用@Autowired注解注入UserInfoDAOImpl实例
@Autowired
UserInfoDAO userInfoDAO;
@Override
public List login(UserInfo cond) {
return userInfoDAO.search(cond);
}
}
UserInfoHandler
package com.digital.controller;
import java.util.List;
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 com.digital.entity.UserInfo;
import com.digital.service.UserInfoService;
@RequestMapping("/userinfo")
@Controller
public class UserInfoHandler {
// 使用@Autowired注解注入UserInfoServiceImpl实例
@Autowired
UserInfoService userInfoService;
@RequestMapping("/login")
public String login(UserInfo ui) {
List uiList=userInfoService.login(ui);
if (uiList.size() > 0) {
// 登录成功,转发到到index.jsp
return "index";
} else {
// 登录失败,重定向到login.jsp
return "redirect:/login.jsp";
}
}
}
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
listener-class>
listener>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter
filter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener
listener-class>
listener>
<filter>
<filter-name>HiddenHttpMethodFilterfilter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter
filter-class>
filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
servlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.digital" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
context:component-scan>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>mvc:annotation-driven>
<mvc:default-servlet-handler />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576" />
<property name="defaultEncoding" value="UTF-8" />
bean>
beans>
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>登录页title>
head>
<body>
<form action="userinfo/login" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="userName" />td>
tr>
<tr>
<td>密 码:td>
<td><input type="text" name="password" />td>
tr>
<tr>
<td><input type="submit" value="登录" />td>
<td>td>
tr>
table>
form>
body>
html>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>系统首页面title>
head>
<body>
欢迎您,登录成功!
body>
html>