第一部分:程序结构

第二部分:配置

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. Android中如何监听GPS开启和关闭

    转自 chenming 原文 Android中如何监听GPS开启和关闭   摘要: 本文简单总结了如何监听GPS开关的小技巧 有时需要监听GPS的开关(这种需求并不多见).实现的思路是监听代表 GPS ...

  2. iOS官方Sample大全

    转载自:http://blog.csdn.net/yangtb2010/article/details/7005471 http://developer.apple.com/library/ios/s ...

  3. HTC ONE里面一个非常奇怪的问题。。。调用kSOAP出错

    也是在某统计网站上看到了我们的APP爆出了这么一个bug: java.lang.NoSuchFieldError: No instance field headerOut of type [Lorg/ ...

  4. memcache c++使用

    memcache作为一个内存数据库,快速查询的功能. 在c++下面使用memcache需要一个memcache client.c++版本的是libmemcached http://libmemcach ...

  5. The Magic only works with total devotion of one's heart

    The Magic only works with total devotion of one's heart All tools and equipments are useless without ...

  6. js 淡入淡出的图片

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  7. maven 打包 spring 项目

    在程序中使用到了springframework控件(主要是为了使用Mybatis-spring操作数据库,省事). 使用maven管理项目的构建,现在需要生成一个jar包,包含所有依赖的jar包,并可 ...

  8. Centos下MySQL使用总结

    转载于CentOS中文站:http://www.centoscn.com/CentOS/Intermediate/2013/0817/1334.html 一.MySQL安装 Centos下安装mysq ...

  9. LVS三种工作方式八种算法

    一.集群简介 什么是集群 计算机集群简称集群是一种计算机系统,它通过一组松散集成的计算机软件和/或硬件连接起来高度紧密地协作完成计算工作.在某种意义上,他们可以被看作是一台计算机.集群系统中的单个计算 ...

  10. RGBA 与opacity

    RGBA是一种表示颜色的方式,初次看到觉得很奇怪,与RGB的区别是什么?后面查了下,才发现RGBA的好处. RGBA各个字母的含义为: R:红色值,正整数 | 百分数: G:绿色值,正整数 | 百分数 ...