第一部分:程序结构

第二部分:配置

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;
    }
}

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();
}

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();
    }

}

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();
}

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();

}

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";
    }
}

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)的更多相关文章

  1. SSH项目(struts+spring+hibernate)搭建_代码简化

    在上篇讲到SSH框架的搭建后,为了有利于随时能熟练的把一个SSH的项目快速的搭建起来,我又进一步对其了解学习,对代码进行了简化,大家相互讨论学习. 为什么要简化:  如果要做一个大项目,假设项目的ac ...

  2. 吴裕雄--天生自然JAVA SPRING框架开发学习笔记:SSH框架(Struts2+Spring+Hibernate)搭建整合详细步骤

    在实际项目的开发中,为了充分利用各个框架的优点,通常都会把 Spring 与其他框架整合在一起使用. 整合就是将不同的框架放在一个项目中,共同使用它们的技术,发挥它们的优点,并形成互补.一般而言,在进 ...

  3. S2SH的集成(Struts2,Spring,Hibernate)----青软S2SH(笔记)

  4. 9、ssh的集成方式1

    集成方式1:核心 我们没有创建applicationContext-action.xml配置文件,在该配置文件里面让Spring去管理我们的AddUserAction,但是AddUserAction的 ...

  5. struts2+spring+hibernate(SSH)框架的搭建和总结

    SSH框架:struts2+spring+hibernate,是目前较流行的一种Web应用程序开源集成框架,用于构建灵活.易于扩展的多层Web应用程序. struts2+spring+hibernat ...

  6. 【SSH进阶之路】Hibernate系列——总结篇(九)

    这篇博文是Hibernate系列的最后一篇,既然是最后一篇,我们就应该进行一下从头到尾,整体上的总结,将这个系列的内容融会贯通. 概念 Hibernate是一个对象关系映射框架,当然从分层的角度看,我 ...

  7. 集成Struts2+Spring+Hibernate_两种方案

    集成Struts2+Spring+Hibernate 第一种方案:让Spring创建Struts2的Action,不让Spring完全管理Struts2的Action      Struts2 Act ...

  8. centos Linux下磁盘管理 parted,df ,du,fdisk,partprobe,mkfs.ext4,mount,/etc/fstab,fsck,e2fsck,mk2efs,tmpfs ,nr_inodes, LVM,传统方式扩容文件系统 第七节课

    centos Linux下磁盘管理   parted,df ,du,fdisk,partprobe,mkfs.ext4,mount,/etc/fstab,fsck,e2fsck,mk2efs,tmpf ...

  9. 【SSH进阶之路】Hibernate映射——一对多关联映射(七)

    上上篇博文[SSH进阶之路]Hibernate映射——一对一单向关联映射(五),我们介绍了一对一的单向关联映射,单向是指只能从人(Person)这端加载身份证端(IdCard),但是反过来,不能从身份 ...

随机推荐

  1. ConfigParser.MissingSectionHeaderError: File contains no section headers.

    今天使用ConfigParser解析一个ini文件,报出如下错误: config.read(logFile) File "C:\Python26\lib\ConfigParser.py&qu ...

  2. git 新建项目

    备份. 1.cd dirctory 2.git init 3.git.oschina.net 上新建项目. 4.git remote add origin XXX.git 5.git push ...

  3. 使用asmcmdcp命令把datafile从文件系统移动(move)到asm磁盘组中 针对11gR2

    使用asmcmd cp命令 把datafile从文件系统移动(move)到asm磁盘组中--针对11gR2 参考原文:How to Move a Datafile from Filesystem to ...

  4. 创建sa账号

    ①以windows身份验证的方式默认登陆 ②选择安全性下的登录名中的sa账号,右键选择属性,进行相关项的设置 ③将sa账号的状态中对应的登录项由之前的禁用,改为已启用 ④将sa对应的密码进行修改为自己 ...

  5. python中的装饰器

    一.什么是装饰器 装饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能 ...

  6. 2016-08-15:从YUV420P中提取指定大小区域

    typedef struct { int width; int height; }SizeInfo; typedef struct { int x; int y; int width; int hei ...

  7. Qlikview 处理增量数据的脚本

    一般设计Qlikview报表的时候需要些2个脚本文件,一个针对Qlikview的Server job 导出数据到qvd数据文具. 另一个用户访问的Qlikview的脚本是直接展示qvd文件的数据. 事 ...

  8. ASP.NET MVC 5 一 入门

    本系类教程将要构建ASP.NET MVC 5 Web 应用程序,使用的工具是VS2013 .现在有预览版可以下载了, 点击下载VS2013 FOR WEB ISO文件 .VS2012 还没用几天呢,2 ...

  9. zedboard如何从PL端控制DDR读写(七)

    前面已经详细介绍了从PL端如何用AXI总线去控制DDR的读写,并且从AXI_BRESP的返回值来看,我们也是成功写入了的.但是没有通过别的方式来验证写入的数据的话,总是感觉差了点什么. 今天试了一把从 ...

  10. threadlocal类

    1.threadlocal对象为线程提供变量的副本,该副本为线程私有的,其它线程访问不到: 2.变量的副本存储在ThreadLocalMap对象中: 3.使用threadlocal时候,最好先使用in ...