• springMVC,spring和Hibernate整合(重要)


    springMVC,spring和Hibernate整合 

    https://my.oschina.net/hugohxb/blog/184715

    第一步:搭建一个springmvc工程,需要的jar有:

     

     在此输入图片描述 

    在此输入图片描述

    第二步:配置工程的web.xml文件.

    <!-- lang: xml -->
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc</display-name>
    <welcome-file-list>
    	<welcome-file>Login.jsp</welcome-file>
    	<welcome-file>index.html</welcome-file>
    	<welcome-file>index.htm</welcome-file>
    	<welcome-file>index.jsp</welcome-file>
    	<welcome-file>default.html</welcome-file>
    	<welcome-file>default.htm</welcome-file>
    	<welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    
    <!-- 加载所有的配置文件 -->
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath*:config/spring-*.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>
    	<init-param>
    		<param-name>encoding</param-name>
    		<param-value>UTF-8</param-value>
    	</init-param>
    	<init-param>
    		<param-name>forceEncoding</param-name>
    		<param-value>true</param-value>
    	</init-param>
    </filter>
    <filter-mapping>
    	<filter-name>encodingFilter</filter-name>
    	<url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置Session -->
    <filter>
    	<filter-name>openSession</filter-name>
    	<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    	<!-- 请注意,此处必须定义,否则后面会报错,具体是什么,笔者没截图,记不太清楚了 -->
    	<init-param>
    		<param-name>sessionFactoryBeanName</param-name>
    		<param-value>sessionFactory</param-value>
    	</init-param>
    </filter>
    <filter-mapping>
    	<filter-name>openSession</filter-name>
    	<url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置SpringMVC -->
    <servlet>
    	<servlet-name>springMVC</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>springMVC</servlet-name>
    	<url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 引用js,如果无此配置,则无法对js进行加载 -->
    <servlet-mapping>
    	<servlet-name>default</servlet-name>
    	<url-pattern>*.js</url-pattern>
    </servlet-mapping>
    

    </web-app> tomcat对里面的加载顺序:Context-Param---->Listener---->filter---->servlet

    第三步:配置hibernate,spring,springmvc等文件,将这些文件全部放到src/config目录下。 Hibernate的配置文件,spring-common.xml如下:

    <!-- lang: 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: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.xsd">
    
    <!-- 配置数据源 -->
    <bean id="dataSource"
    	class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    	<property name="url" value="jdbc:mysql://localhost/springmvc"></property>
    	<property name="username" value="root"></property>
    	<property name="password" value="root"></property>
    </bean>
    
    <!-- 配置SessionFactory -->
    <bean id="sessionFactory"
    	class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    	<property name="dataSource" ref="dataSource" />
    	<property name="hibernateProperties">
    		<props>
    			<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    			<prop key="hibernate.hbm2ddl.auto">update</prop>
    			<prop key="hibernate.show_sql">true</prop>
    			<prop key="hibernate.format_sql">true</prop>
    		</props>
    	</property>
    	<!-- 注解扫描的包 -->
    	<property name="annotatedClasses">
    		<list>
    			<value>ne.springmvc.entity.User</value>
    		</list>
    	</property>
    </bean>
    
    <!-- 配置一个事务管理器 -->
    <bean id="transactionManager"
    	class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    	<property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
    <!-- 配置事务,使用代理的方式 -->
    <bean id="transactionProxy"
    	class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
    	abstract="true">
    	<property name="transactionManager" ref="transactionManager"></property>
    	<property name="transactionAttributes">
    		<props>
    			<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
    			<prop key="modify*">PROPAGATION_REQUIRED,-myException</prop>
    			<prop key="del*">PROPAGATION_REQUIRED</prop>
    			<prop key="*">PROPAGATION_REQUIRED</prop>
    		</props>
    	</property>
    </bean>
    

    </beans>

    springmvc的配置文件spring-mvc.xml如下

    <!-- lang: 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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         				http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
            			http://www.springframework.org/schema/context
        				http://www.springframework.org/schema/context/spring-context-3.0.xsd 
            			http://www.springframework.org/schema/mvc
            			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    
    <!-- 注解扫描包 -->
    <context:component-scan base-package="ne.springmvc.*" />
    
    <!-- 开启注解 -->
    <mvc:annotation-driven />
    
    <!-- 静态资源(js/image)的访问 -->
    <!-- <mvc:resources location="/js/" mapping="/js/**"/> -->
    
    <!-- 定义视图解析器 -->
    <bean id="viewResolver"
    	class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="prefix" value="/WEB-INF/jsp"></property>
    	<property name="suffix" value=".jsp"></property>
    </bean>
    

    </beans>

    spring的配置文件spring-beans.xml如下:

    <!-- lang: 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: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.xsd">  
     
    <bean id="userDao" class="ne.springmvc.dao.UserDaoImpl">  
        <property name="sessionFactory" ref="sessionFactory"></property>  
    </bean>  
    
    <bean id="userManagerBase" class="ne.springmvc.service.UserManagerImpl">  
        <property name="userDao" ref="userDao"></property>  
    </bean>  
      
    <!-- 此处为代理 -->  
    <bean name="userManager" parent="transactionProxy">  
        <property name="target" ref="userManagerBase"></property>  
    </bean>     
    

    </beans>

    工程的四个配置文件全部完成,接下来按照mvc的设计模式,从dao层代码开始,先编写实体entity。注:在此之前,需要在mysql数据库中新建好数据库和表。实体User.java如下:

    <!-- lang: java -->
    package ne.springmvc.entity;
    
    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;
    
    /**
     * 此实体的定义应用了springmvc的注解,省去了传统的Hibernate跟数据库之间的映射配置文件
     * @author will
     *
     */
    @Entity  
    @Table(name="T_USER")  
    public class User {  
    
    @Id  
    @GeneratedValue(generator="system-uuid")  
    @GenericGenerator(name = "system-uuid",strategy="uuid")  
    @Column(length=32)  
    private String id;  
      
    @Column(length=32)  
    private String userName;  
      
    @Column(length=32)  
    private String age;  
    
    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 getAge() {  
        return age;  
    }  
    
    public void setAge(String age) {  
        this.age = age;  
    }  
    

    }

    dao层:接口userDao.java如下:

    <!-- lang: java -->
    package ne.springmvc.dao;
    
    import java.util.List;
    
    import ne.springmvc.entity.User;
    
    public interface UserDao {
    
    public User getUser(String id);  
    
    public List<User> getAllUser();  
      
    public void addUser(User user);  
      
    public boolean delUser(String id);  
      
    public boolean updateUser(User user);  
    

    }

    接口userDao.java的实现类UserDaoImpl.java如下:

    <!-- lang: java -->
    package ne.springmvc.dao;
    
    import java.util.List;
    
    import org.hibernate.Query;
    import org.hibernate.SessionFactory;
    
    import ne.springmvc.entity.User;
    
    public class UserDaoImpl implements UserDao {
    
    private SessionFactory sessionFactory;  
      
    public void setSessionFactory(SessionFactory sessionFactory) {  
        this.sessionFactory = sessionFactory;  
    }  
    
    /**
     * 根据用户id查询用户
     */
    public User getUser(String id) {  
          
        String hql = "from User u where u.id=?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        query.setString(0, id);  
          
        return (User)query.uniqueResult();  
    }  
    
    /**
     * 查询所有用户
     */
    public List<User> getAllUser() {  
          
        String hql = "from User";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
          
        return query.list();  
    }  
    
    /**
     * 添加用户
     */
    public void addUser(User user) {  
        sessionFactory.getCurrentSession().save(user);  
    }  
    
    /**
     * 根据用户id删除用户
     */
    public boolean delUser(String id) {  
          
        String hql = "delete User u where u.id = ?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        query.setString(0, id);  
          
        return (query.executeUpdate() > 0);  
    }  
    
    /**
     * 编辑用户
     */
    public boolean updateUser(User user) {  
          
        String hql = "update User u set u.userName = ?,u.age=? where u.id = ?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        query.setString(0, user.getUserName());  
        query.setString(1, user.getAge());  
        query.setString(2, user.getId());  
          
        return (query.executeUpdate() > 0);  
    }  
    
    }
    

    service层的接口UserManager.java如下:

    <!-- lang: java -->
    package ne.springmvc.service;
    
    import java.util.List;
    import ne.springmvc.entity.User;
    
    public interface UserManager {  
      
    public User getUser(String id);  
      
    public List<User> getAllUser();  
      
    public void addUser(User user);  
      
    public boolean delUser(String id);  
      
    public boolean updateUser(User user);  
    }  
    

    接口userManager的实现类UserManagerImpl.java如下:

    <!-- lang: java -->
    package ne.springmvc.service;
    
    import java.util.List;
    import ne.springmvc.dao.UserDao;
    import ne.springmvc.entity.User;
    
    public class UserManagerImpl implements UserManager {
    
    private UserDao userDao;  
    
    public void setUserDao(UserDao userDao) {  
        this.userDao = userDao;  
    }  
    
    public User getUser(String id) {  
        return userDao.getUser(id);  
    }  
    
    public List<User> getAllUser() {  
        return userDao.getAllUser();  
    }  
    
    public void addUser(User user) {  
        userDao.addUser(user);  
    }  
    
    public boolean delUser(String id) {  
          
        return userDao.delUser(id);  
    }  
    
    public boolean updateUser(User user) {  
        return userDao.updateUser(user);  
    }  
    
    }
    

    控制层UserController.java如下:

    <!-- lang: java -->
    package ne.springmvc.controller;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import ne.springmvc.entity.User;
    import ne.springmvc.service.UserManager;
    import javax.annotation.Resource;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    
    @Controller  
    @RequestMapping("/user")  
    public class UserController {  
    
    @Resource(name="userManager")  
    private UserManager userManager;  
    
    @RequestMapping("/getAllUser")  
    public String getAllUser(HttpServletRequest request){  
        request.setAttribute("userList", userManager.getAllUser());  
        return "/Index";  
    }  
      
    @RequestMapping("/getUser")  
    public String getUser(String id,HttpServletRequest request){  
        request.setAttribute("user", userManager.getUser(id));  
        return "/editUser";  
    }  
      
    @RequestMapping("/toAddUser")  
    public String toAddUser(){  
        return "/addUser";  
    }  
      
    @RequestMapping("/addUser")  
    public String addUser(User user,HttpServletRequest request){  
        System.out.println("用户名:======"+user.getUserName());  
        userManager.addUser(user);  
        return "redirect:/user/getAllUser";  
    }  
      
    @RequestMapping("/delUser")  
    public void delUser(String id,HttpServletResponse response){  
        String result = "{"result":"error"}";  
        if(userManager.delUser(id)){  
            result = "{"result":"success"}";  
        }  
        response.setContentType("application/json");  
        try {  
            PrintWriter out = response.getWriter();  
            out.write(result);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
      
    @RequestMapping("/updateUser")  
    public String updateUser(User user,HttpServletRequest request){  
        if(userManager.updateUser(user)){  
            user = userManager.getUser(user.getId());  
            request.setAttribute("user", user);  
            return "redirect:/user/getAllUser";  
        }else{  
            return "/error";  
        }  
    }  
    }  
    

    jsp页面:Login.jsp,Index.jsp,addUser.jsp,editUser.jsp总共四个页面,成功和错误页面就没写了。 Login.jsp页面如下:

    <!-- lang: html -->
    <%@ 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>  
    <h5><a href="/springmvc-hibernate-test/user/getAllUser">进入用户管理页</a></h5>
    </body>  
    </html> 
    

    Index.jsp页面如下:

    <!-- lang: html -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>
    <%
    	String path = request.getContextPath();
    %>
    <script type="text/javascript" src="<%=path%>/js/jquery-1.9.1.min.js"></script>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Insert title here</title>  
    <script type="text/javascript">  
        function del(id){  
        $.get("/springmvc-hibernate-test/user/delUser?id=" + id,function(data){  
            if("success" == data.result){  
                alert("删除成功");  
                window.location.reload();  
            }else{  
                alert("删除失败");  
            }  
        });  
    }  
    </script>  
    </head>  
    <body>  
        <h6><a href="/springmvc-hibernate-test/user/toAddUser">添加用户</a></h6>  
        <table border="1">  
            <tbody>  
            <tr>  
                <th>姓名</th>  
                <th>年龄</th>  
                <th>操作</th>  
            </tr>  
            <c:if test="${!empty userList }">  
                <c:forEach items="${userList }" var="user">  
                    <tr>  
                        <td>${user.userName }</td>  
                        <td>${user.age }</td>  
                        <td>  
                            <a href="/springmvc-hibernate-test/user/getUser?id=${user.id }">编辑</a>  
                            <a href="javascript:del('${user.id }')">删除</a>  
                        </td>  
                    </tr>               
                </c:forEach>  
            </c:if>  
        </tbody>  
    </table>  
    </body>  
    </html>  
    

    addUser.jsp页面如下:

    <!-- lang: html -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
    <!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>Insert title here</title>  
    <script type="text/javascript">  
    function addUser(){  
        var form = document.forms[0];  
        form.action = "/springmvc-hibernate-test/user/addUser";  
        form.method="post";  
        form.submit();  
    }  
    </script>  
    </head>  
    <body>  
    <h1>添加用户</h1>  
    <form action="" name="userForm">  
        姓名:<input type="text" name="userName">  
        年龄:<input type="text" name="age">  
        <input type="button" value="添加" onclick="addUser()">  
    </form>  
    </body>  
    </html>  
    

    editUser.jsp页面如下:

    <!-- lang: html -->
    <%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
    <html>  
    <head>
    <%
    String path = request.getContextPath();
    %>  
    <script type="text/javascript" src="<%=path %>/js/jquery-1.9.1.min.js"></script>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
    <title>Insert title here</title>  
    </head>  
    <body>  
    <h1>编辑用户</h1>  
    <form action="/springmvc-hibernate-test/user/updateUser" name="userForm" method="post">  
        <input type="hidden" name="id" value="${user.id }">  
        姓名:<input type="text" name="userName" value="${user.userName }">  
        年龄:<input type="text" name="age" value="${user.age }">  
        <input type="submit" value="编辑" >  
    </form>  
    </body>  
    </html> 
    

    以上便是所有的代码,下面是页面效果。 首页: 在此输入图片描述

    管理页面:

    在此输入图片描述

    添加页面:

    在此输入图片描述

    编辑页面:

    在此输入图片描述

    遇到的问题:

    1、jquery.1.9.1.min.js加载不进来,原因是springmvc将js统一认定为静态资源,所以需要额外配置去引用js,我是在web.xml里面配置的,配置如下:

    <!-- lang: xml -->
    <servlet-mapping>
    	<servlet-name>default</servlet-name>
    	<url-pattern>*.js</url-pattern>
    </servlet-mapping>
    

    2、添加用户时,mysql数据库出现中文乱码问题,在eclipse,tomcat,数据库和表都设置为utf-8之后,还需要将mysql安装目录下的my.ini文件中,将default-character-set=utf8和character-set-server=utf8,如下图: 在此输入图片描述

     
  • 相关阅读:
    Idea14 生成webservices
    第10组 Beta冲刺(4/4)
    2019 SDN上机第7次作业
    第10组 Beta冲刺(3/4)
    第10组 Beta冲刺(2/4)
    第10组 Beta冲刺(1/4)
    2019 SDN上机第6次作业
    SDN课程阅读作业(2)
    2019 SDN上机第5次作业
    第10组 Alpha冲刺(4/4)
  • 原文地址:https://www.cnblogs.com/bwdblogs/p/11001621.html
Copyright © 2020-2023  润新知