第七次课:ssh的集成(SpringMV+Spring+Hibernate)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第七次课:ssh的集成(SpringMV+Spring+Hibernate)相关的知识,希望对你有一定的参考价值。

第一部分:程序结构

技术分享

第二部分:配置

1、配置web.xml文件,启动spring和springMVC:

1)配置启动spring:

  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:config/spring-core.xml</param-value>
  </context-param>
  
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

2)配置springMVC的servlet:

  <servlet>
      <servlet-name>spring-mvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath*:config/spring-mvc.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>spring-mvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>

2、配置spring-mvc.xml,用于配置springMVC:

    <!-- 配置扫描包 -->
    <context:component-scan base-package="cn.shxy.web.controller" />
    
    <!-- 启用注解 -->
    <mvc:annotation-driven />        
    
    <!-- 视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

3、配置spring-hibernate.xml,用于配置hibernate:

<!-- 配置数据源 -->
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url"
            value="jdbc:mysql://localhost:3306/db_test?useUnicode=true&amp;characterEncoding=UTF-8" />
        <property name="username" value="root" />
        <property name="password" value="th362cn" />
    </bean>

    <!-- 配置sessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL57InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- 配置实体类映射路径 -->
        <property name="configLocations">
            <list>
                <value>classpath*:cn/shxy/web/entity/hibernate.cfg.xml
                </value>
            </list>
        </property>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <!-- 配置事务处理基类 -->
    <bean id="transactionBase"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
        lazy-init="true" abstract="true">
        <property name="transactionManager" ref="transactionManager" />
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="del*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
                <prop key="get*">PROPAGATION_NEVER</prop>
            </props>
        </property>
    </bean>

4、配置spring-core.xml,用于配置spring管理的bean:

    <import resource="classpath*:config/spring-hibernate.xml"/>
    <import resource="classpath*:cn/shxy/web/service/user.xml"/>
    <import resource="classpath*:cn/shxy/web/service/util.xml"/>

第三部分:代码编写

1、编写实体类User:

技术分享
package cn.shxy.web.entity;

import java.util.Date;

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

import org.hibernate.annotations.GenericGenerator;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name = "T_User")
public class User {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    private String id;

    @Column(length = 32, unique = true)
    private String userName;

    @Column(length = 32)
    private String password;
    
    @Column(length = 18)
    private String real_name;

    @Column(length = 18, unique = true)
    private String id_card_number;

    @Column(length = 32, unique = true)
    private String code;

    @Column
    @DateTimeFormat(pattern = "yyyy-MM-dd")  
    private Date birthday;

    @Column(length = 50)
    private String graduate_school;

    @Column(length = 32)
    private String education;

    @Column(length = 32)
    private String degree;

    @Column(length = 50)
    private String major;

    @Column
    @DateTimeFormat(pattern = "yyyy-MM-dd")  
    private Date work_time;

    @Column(length = 32)
    private String nation;

    @Column(length = 100)
    private String native_place;

    @Column(length = 4)
    private String sex;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getReal_name() {
        return real_name;
    }

    public void setReal_name(String real_name) {
        this.real_name = real_name;
    }

    public String getId_card_number() {
        return id_card_number;
    }

    public void setId_card_number(String id_card_number) {
        this.id_card_number = id_card_number;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getGraduate_school() {
        return graduate_school;
    }

    public void setGraduate_school(String graduate_school) {
        this.graduate_school = graduate_school;
    }

    public String getEducation() {
        return education;
    }

    public void setEducation(String education) {
        this.education = education;
    }

    public String getDegree() {
        return degree;
    }

    public void setDegree(String degree) {
        this.degree = degree;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public Date getWork_time() {
        return work_time;
    }

    public void setWork_time(Date work_time) {
        this.work_time = work_time;
    }

    public String getNation() {
        return nation;
    }

    public void setNation(String nation) {
        this.nation = nation;
    }

    public String getNative_place() {
        return native_place;
    }

    public void setNative_place(String native_place) {
        this.native_place = native_place;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
View Code

2、编写User类的数据库操作接口IUserDAO和操作类UserDAO:

1)IUserDAO:

技术分享
package cn.shxy.web.dao;


import java.util.List;

import cn.shxy.web.entity.User;

/**
 * 用户管理接口
 * 
 * @author Jhon
 *
 */
public interface IUserDAO {
    /**
     * 添加用户信息进入数据库
     * 
     * @param user
     * @return
     */
    public String add_user(User user);

    /**
     * 根据账号密码获取用户的信息
     * 
     * @param userName
     * @param password
     * @return
     */
    public User get_user(String userName, String password);
    
    /**
     * 获取所有用户信息
     * @return
     */
    public List<User> get_users();
}
View Code

2)UserDAO:

技术分享
package cn.shxy.web.dao;


import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import cn.shxy.web.entity.User;

public class UserDAO implements IUserDAO {
    private SessionFactory sessionFactory;

    @Override
    public String add_user(User user) {
        return (String) sessionFactory.getCurrentSession().save(user);
    }

    @Override
    public User get_user(String userName, String password) {
        Query query = sessionFactory.getCurrentSession().createQuery("From User Where userName=? And password=?");
        query.setString(0, userName);
        query.setString(1, password);
        return (User) query.uniqueResult();
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<User> get_users() {
        Query query = sessionFactory.getCurrentSession().createQuery("From User");
        return query.list();
    }

}
View Code

3、编写Use操作逻辑接口IUserService和操作逻辑类UserService:

1)IUserService:

技术分享
package cn.shxy.web.service;

import java.util.List;

import cn.shxy.web.entity.User;

/**
 * 用户操作接口
 * 
 * @author Jhon
 *
 */
public interface IUserSerivce {

    /**
     * 添加用户信息进入数据库
     * 
     * @param user
     * @return
     */
    public String add_user(User user);

    /**
     * 根据账号密码获取用户的信息
     * 
     * @param userName
     * @param password
     * @return
     */
    public User get_user(String userName, String password);
    
    /**
     * 获取所有用户
     * @return
     */
    public List<User> get_users();
}
View Code

2)UserService:

技术分享
package cn.shxy.web.service;

import java.util.List;

import cn.shxy.web.entity.Degree;
import cn.shxy.web.entity.Education;
import cn.shxy.web.entity.Nation;

public interface IUtilService {
    /**
     * 获取所有学历信息
     * 
     * @return
     */
    public List<Education> get_educations();

    /**
     * 获取所有学位信息
     * 
     * @return
     */
    public List<Degree> get_degrees();

    /**
     * 获取所有民族信息
     * 
     * @return
     */
    public List<Nation> get_nations();

}
View Code

4、配置hibernate.cfg.xml文件,用于指定数据库和类的映射:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
    <session-factory>
        <mapping class="cn.shxy.web.entity.User"/>
    </session-factory>
</hibernate-configuration>

5、配置user.xml,用于管理用户操作类的bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    <!-- 实例化用户管理类 -->
    <bean id="userDAO" class="cn.shxy.web.dao.UserDAO">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <!-- 实例化用户服务类 -->
    <bean id="userServiceBase" class="cn.shxy.web.service.UserService">
        <property name="userDAO" ref="userDAO" />
    </bean>
    <!-- 为用户服务类加上拦截器,进行事务管理 -->
    <bean id="userService" parent="transactionBase">
        <property name="target" ref="userServiceBase" />
    </bean>
</beans>

6、编写UserController类:

技术分享
package cn.shxy.web.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.shxy.web.entity.Degree;
import cn.shxy.web.entity.Education;
import cn.shxy.web.entity.Nation;
import cn.shxy.web.entity.User;
import cn.shxy.web.service.IUserSerivce;
import cn.shxy.web.service.IUtilService;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource(name = "userService")
    IUserSerivce userService;
    @Resource(name = "utilService")
    IUtilService utilService;

    @RequestMapping("/login")
    public String login() {
        return "/login";
    }

    @RequestMapping("/check_login")
    public String check_login(User user, RedirectAttributes attr) {
        User user2 = userService.get_user(user.getUserName(), user.getPassword());
        if (user2 == null) {
            attr.addFlashAttribute("error", "用户名或密码有误!");
            return "redirect:/user/login";
        }
        return "redirect:/sys/index";
    }

    @RequestMapping("/reg")
    public String reg(HttpServletRequest request) {
        List<Education> educations = utilService.get_educations();
        List<Degree> degrees = utilService.get_degrees();
        List<Nation> nations = utilService.get_nations();

        request.setAttribute("educations", educations);
        request.setAttribute("degrees", degrees);
        request.setAttribute("nations", nations);

        return "/reg";
    }

    @RequestMapping("/reg_save")
    public String reg_save(User user, String repassword, RedirectAttributes attr) {
        
        return "redirect:/user/login";
    }
}
View Code

7、编写网页文件:login.jsp和index.jsp:

1)login.jsp:

<%@ 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>用户登录</title>
</head>
<body>
    <form action="/mvc3/user/check_login" method="post">
        <table>
            <tr>
                <td>账号:</td>
                <td><input type="text" name="userName" /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="登录" />&nbsp;<a href="/mvc3/user/reg">注册</a></td>
            </tr>
        </table>
    </form>
    ${error }
</body>
</html>

2)index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>主页</title>
</head>
<body>
    欢迎登陆!
</body>
</html>

第四部分:测试

略。

注意:springMVC使用POST方法可能造成中文乱码,解决方法是使用SpringMVC提供的编码过滤器:

 

<filter>  
    <filter-name>CharacterEncodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
        <param-name>encoding</param-name>  
        <param-value>utf-8</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>CharacterEncodingFilter</filter-name>  
    <url-pattern>/*</url-pattern>  
</filter-mapping>

 

以上是关于第七次课:ssh的集成(SpringMV+Spring+Hibernate)的主要内容,如果未能解决你的问题,请参考以下文章

第七次课大纲

第七次课作业(项目沟通管理合同管理)

第七次课:Python帮助和数据类型转换

第七次团队作业:汇总博客

第七次团队作业:汇总博客

第七次作业