上一篇https://blog.csdn.net/stark_jc/article/details/79778962采用了Spring+Struts2+Hibernate的方式实现了登录,且上次采用的是XML配置(包括实体类与数据表之间的配置、以及Struts2的action映射关系的配置),本文以SpringMVC取代Struts2,在路径和处理器以及实体类属性和数据表字段的映射关系上使用注解.
这是此次所需的文件
Model层开发
创建实体类
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;
}
}
Spring与Hibernate的整合
applicationContext
<?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: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>
<!-- 配置Hibernate的sessionFactory实例 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 配置数据源属性 -->
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- 配置 Hibernate的基本属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<!-- 配置 Hibernate基于注解的实体类的位置及名称 -->
<property name="annotatedClasses">
<list>
<value>com.digital.entity.UserInfo</value>
</list>
</property>
</bean>
<!-- 声明Hibernate事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 开启注解处理器 -->
<context:annotation-config />
<!-- 开启Spring的Bean自动扫描机制来检查与管理Bean实例 -->
<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>
<!-- 基于@Transactional注解方式的事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
DAO层开发
UserInfoDAO接口
package com.digital.dao;
import java.util.List;
import com.digital.entity.UserInfo;
public interface UserInfoDAO {
public List<UserInfo> search(UserInfo cond);
}
UserInfoDAOImpl
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<UserInfo> 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<UserInfo> uiList = query.list();
return uiList;*/
/*
* 使用QBC查询
*
*/
List<UserInfo> 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里面注册了。
Service层开发
UserInfoService接口
package com.digital.service;
import java.util.List;
import com.digital.entity.UserInfo;
public interface UserInfoService {
public List<UserInfo> login(UserInfo cond);
}
UserInfoServiceImpl
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<UserInfo> login(UserInfo cond) {
return userInfoDAO.search(cond);
}
}
Controller层开发
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<UserInfo> uiList=userInfoService.login(ui);
if (uiList.size() > 0) {
// 登录成功,转发到到index.jsp
return "index";
} else {
// 登录失败,重定向到login.jsp
return "redirect:/login.jsp";
}
}
}
Spring整合SpringMVC
web.xml配置
<!-- 配置ContextLoaderListener,加载Spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>
<!-- 配置org.springframework.web.filter.HiddenHttpMethodFilter, 可将POST请求转为DELETE或PUT请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置 Spring MVC 的 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 配置Spring MVC配置文件的位置及名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
springmvc.xml配置
<?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: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">
<!-- 配置自动扫描的包,SpringMVC 的 IOC 容器中的 bean 可以来引用 Spring IOC 容器中的 bean.
但 Spring IOC 容器中的 bean 却不能来引用 SpringMVC IOC 容器中的 bean! -->
<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>
<!-- 配置视图解析器 ,将handler方法返回的逻辑视图解析为物理视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 启用MVC注解驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- default-servlet-handler 将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,
它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet
处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理 一般 WEB 应用服务器默认的 Servlet 的名称都是 default.
若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定 -->
<mvc:default-servlet-handler />
<!-- 配置CommonsMultipartResolver,实现文件上传 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为1MB -->
<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>