第一部分:程序结构

第二部分:配置

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. vim(5)vim下wimrc的配置,解决中文乱码问题

    解决linux下vim乱码的情况:(修改vimrc的内容) 全局的情况下:即所有用户都能用这个配置 文件地址:/etc/vimrc 在文件中添加: ,ucs-bom,gb18030,gbk,gb231 ...

  2. javascript的事件

    前戏 今天在博客中看到了javascript的事件机制,就自己试试写一个简单的冒泡捕获测试,但是测试结果出乎了我的意料,主要是自己原来对事件了解不是很清楚,现在写篇博客记录下. 基础 先来看一下我在A ...

  3. log4j配置不同的类多个日志文件

    <Configuration status="INFO"> <Appenders> <Console name="STDOUT" ...

  4. perl脚本基础总结

    1.  单引号字符串中的\n不会被当做换行符处理. 如:'\'\\'  -->  '\  . 2.  双引号 字符串联    "Hello"."World" ...

  5. Python isdigit()方法

    描述 Python isdigit() 方法检测字符串是否只由数字组成. 语法 isdigit()方法语法: str.isdigit() 参数 无. 返回值 如果字符串只包含数字则返回 True 否则 ...

  6. WPF的图片操作效果(一):RenderTransform

    一.RenderTransform类的成员: 1.TranslateTransform 平移效果 2.RotateTransform 旋转效果 3.ScaleTransform       缩放效果 ...

  7. 第19章 queue队列容器

    /* 第19章 queue队列容器 19.1 queue技术原理 19.2 queue应用基础 19.3 本章小结 */ // 第19章 queue队列容器 // 19.1 queue技术原理 // ...

  8. 根据Excel线程句柄得到ID并且关闭进程

    [System.Runtime.InteropServices.DllImport("User32.dll", CharSet = System.Runtime.InteropSe ...

  9. js的打印分页

    调用 浏览器 自带的 打印功能 时,在需要分页的地方插入如下HTML,便可实现打印分页: <div  style="page-break-before:always;"> ...

  10. POJ 2502 - Subway Dijkstra堆优化试水

    做这道题的动机就是想练习一下堆的应用,顺便补一下好久没看的图论算法. Dijkstra算法概述 //从0出发的单源最短路 dis[][] = {INF} ReadMap(dis); for i = 0 ...