您现在的位置是:首页 >技术杂谈 >ssh整合:spring+springmvc+hibernate网站首页技术杂谈

ssh整合:spring+springmvc+hibernate

跟着宝哥学java 2023-06-09 16:00:03
简介ssh整合:spring+springmvc+hibernate

1 创建maven的web项目

2 补全项目结构

image-20211208112217457

3 补全web.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"
         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>java37_05_ssh01</display-name>
  <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

4 在pom.xml中引入所有的依赖

<properties>
    <!--声明所有的jar的版本信息-->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <springVersion>4.3.1.RELEASE</springVersion>
    <hibernateVersion>4.3.5.Final</hibernateVersion>
    <jstlVersion>1.2</jstlVersion>
    <taglibVersion>1.1.2</taglibVersion>
    <servletVersion>3.0-alpha-1</servletVersion>
    <jsonVersion>1.9.13</jsonVersion>
    <jacksonVersion>2.5.0</jacksonVersion>
    <mysqlVersion>5.1.38</mysqlVersion>
    <c3p0Version>0.9.1.2</c3p0Version>
    <log4jVersion>1.2.17</log4jVersion>
    <fileuploadVersion>1.3.1</fileuploadVersion>
    <lombokVersion>1.16.10</lombokVersion>
</properties>

<dependencies>
    <!-- 单元测试 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>

    <!-- spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${springVersion}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springVersion}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springVersion}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springVersion}</version>
    </dependency>

    <!-- spring web + spring MVC-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springVersion}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springVersion}</version>
    </dependency>

    <!-- hibernate配置-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernateVersion}</version>
    </dependency>

    <!-- hibernate 缓存, 视情况添加-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>${hibernateVersion}</version>
    </dependency>

    <!-- jsp页面使用的jstl支持-->
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>${jstlVersion}</version>
    </dependency>
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>${taglibVersion}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>${servletVersion}</version>
        <scope>provided</scope>
    </dependency>

    <!-- DataBase数据库连接 mysql包-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysqlVersion}</version>
    </dependency>

    <!-- 数据库连接池-->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>${c3p0Version}</version>
    </dependency>

    <!-- json数据 使springMVC可以返回json值 ,视情况添加-->
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jsonVersion}</version>
    </dependency>

    <!-- Jackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象-->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jacksonVersion}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>${jacksonVersion}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jacksonVersion}</version>
    </dependency>

    <!-- log4j配置, 视情况添加-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4jVersion}</version>
    </dependency>

    <!--文件 上传-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>${fileuploadVersion}</version>
    </dependency>

    <!-- lombok插件导包-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombokVersion}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

5 创建一个属性集文件:

  • 位置:main/resources 名字:ssh.properties
#jdbc paramters
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/db_37?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = root

#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = update

6 创建springmvc的核心配置文件

  • 位置:main/resources 名字:springmvc_conf.xml
1 扫描action包
2 mvc标签注册处理器映射器和处理器适配器
3 配置视图解析器
4 配置拦截器
5 配置多部件表单解析器
<?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-4.1.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.1.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射-->
    <mvc:annotation-driven />

    <context:component-scan base-package="com.zhiyou100.action" />

    <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
    <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>

    <!--这里是对静态资源的映射-->
    <mvc:resources mapping="/js/**" location="/resources/js/" />
    <mvc:resources mapping="/css/**" location="/resources/css/" />
    <mvc:resources mapping="/img/**" location="/resources/imgs/" />


    <!--配置多部件表单解析器-->
    <!-- 5 配置多部件解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize"  value="999999999"/>
    </bean>
</beans>

7 创建spring的核心配置文件

  • 位置:main/resources 名字:spring_conf.xml
1 扫描service和repersity包 创建bean
2 创建datasource的bean
3 创建sessionfactory的bean
4 创建事务管理bean
//5 mybatis中需要为ampper接口创建实现类对象
<?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-4.1.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.1.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <!--1 扫描除了action包以外的所有包 为添加注解的类创建bean-->
    <context:component-scan base-package="com.zhiyou100">
        <!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--加载属性集文件-->
    <context:property-placeholder location="classpath:ssh.properties" />

    <!--2 创建数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driver}" />  <!--数据库连接驱动-->
        <property name="jdbcUrl" value="${jdbc.url}" />     <!--数据库地址-->
        <property name="user" value="${jdbc.username}" />   <!--用户名-->
        <property name="password" value="${jdbc.password}" />   <!--密码-->
        <property name="maxPoolSize" value="40" />      <!--最大连接数-->
        <property name="minPoolSize" value="1" />       <!--最小连接数-->
        <property name="initialPoolSize" value="10" />      <!--初始化连接池内的数据库连接-->
        <property name="maxIdleTime" value="20" />  <!--最大空闲时间-->
    </bean>

    <!--3 创建sessionfactory-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--指定实体类:注解形式-->
        <property name="packagesToScan" value="com.zhiyou100.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <!--hibernate根据实体自动生成数据库表-->
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>   <!--指定数据库方言-->
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>     <!--在控制台显示执行的数据库操作语句-->
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>     <!--在控制台显示执行的数据哭操作语句(格式)-->
            </props>
        </property>
    </bean>

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

8 配置项目的核心配置文件:web.xml

1 配置欢迎页
2 配置项目的初始化参数指定spring的核心配置文件
3 配置paringmvc的中央控制器
4 配置spring的上下文监听器
5 配置全站编码过滤器
<?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"
         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>java37_05_ssh01</display-name>
    <!-- 地址为http://localhost:8080/  显示的默认网页-->
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
    <!--加载Spring的配置文件到上下文中去-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring_config.xml</param-value>
    </context-param>
    <!-- spring MVC config start-->
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <!-- 此处指向的的是SpringMVC的配置文件 -->
            <param-value>classpath:springmvc_conf.xml</param-value>
        </init-param>
        <!--配置容器在启动的时候就加载这个servlet并实例化-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>


    <!-- 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>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>ERROR</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
</web-app>

9 启动测试

image-20211208121933952

10 创建实体类

@Entity
@Table(name="student")
public class Student   implements Serializable {
    @Id
    @GenericGenerator(name="sg",strategy = "identity")
    @GeneratedValue(generator = "sg")
    @Column(name = "sid")
    private  Integer sid;
    @Column(name = "sname")
    private String sname;
    @Column(name = "sex")
    private String sex;
    @Column(name = "score")
    private Float score;
    @Column(name = "sdy")
    private Boolean sdy;
    @Column(name = "sbirthday")
    private Date sbirthday;
    ...
}

11 创建通用的dao接口

package com.zhiyou100.dao;

import org.hibernate.Session;

import java.util.List;

public interface GenericDao<E,K> {
    Session  getSession();
    void closeSession();
    E getOneByKey(K k);
    List<E>  getAll();
    int addOne(E e);
    int deleteOne(K k);
    int updateOne(E e);

}

12 创建studentdao

public interface StudentDao   extends  GenericDao<Student,Integer>{
}

13 创建dao实现类

package com.zhiyou100.dao;

import com.zhiyou100.entity.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
@Transactional
public class StudentDaoImp   implements  StudentDao{
    @Autowired
    private SessionFactory factory;
    @Override
    public Session getSession() {
        return factory.getCurrentSession();
    }

    @Override
    public void closeSession() {
        factory.getCurrentSession().close();
    }

    @Override
    public Student getOneByName(String sname) {
        List<Student> list=getSession().createQuery("from com.zhiyou100.entity.Student where sname='"+sname+"'").list();
        return (list==null||list.size()==0)?null:list.get(0);
    }



    @Override
    public Student getOneByKey(Integer id) {
        return (Student) getSession().get(Student.class,id);
    }

    @Override
    public List<Student> getAll() {
        return getSession().createQuery("from com.zhiyou100.entity.Student").list();
    }

    @Override
    public int addOne(Student student) {
        return (Integer) getSession().save(student);
    }

    @Override
    public int deleteOne(Integer id) {
        Student student=getOneByKey(id);
        if(student!=null){
            getSession().delete(student);
            return 1;
        }
        return 0;
    }

    @Override
    public int updateOne(Student student) {
        getSession().update(student);
        return 1;
    }
}

14 创建service接口和实现类

15 创建action

@Controller
@RequestMapping("/student")
public class StudentAction {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAll.action")
    @ResponseBody
    public List<Student> getAllMethod(){
        List<Student> list=studentService.getAll();
        System.out.println(list);
        return list;
    }
}

16 创建页面:index.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">
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <a   href="/student/getAll.action">请求getAll</a>
</body>
</html>

17 测试

18 改进:使用jstl

引入jsp和jstl的依赖

<!-- JSP 页面使用的依赖-->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>


<!--一下依赖 已经存在-->
<!-- jsp页面使用的jstl支持-->
<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>${jstlVersion}</version>
</dependency>
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>${taglibVersion}</version>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>${servletVersion}</version>
    <scope>provided</scope>
</dependency>

在web-inf下引入需要的tld文件

修改页面: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" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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">
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
    <%----%>
    <c:if test="${empty requestScope.list}">
        <jsp:forward page="/student/getAllForJsp.action"/>
    </c:if>

    <a   href="/student/getAllForJsp.action">请求getAll获取jsp</a><br/>
    <table>
        <tr>
            <th>学号</th><th>名字</th><th>性别</th><th>分数</th><th>党员</th>
        </tr>
        <c:forEach items="${requestScope.list}" var="s">
            <tr>
                <td>${s.id}</td>
                <td>${s.name}</td>
                <td>${s.sex}</td>
                <td>${s.score}</td>
                <td>${s.dy}</td>
            </tr>
        </c:forEach>

    </table>

    <a   href="/student/getAllForJson.action">请求getAlljson</a><br/>

</body>
</html>

修改action

@Controller
@RequestMapping("/student")
public class StudentAction {
    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAllForJson.action")
    @ResponseBody
    public List<Student> getAllForJsonMethod(){
        List<Student> list=studentService.getAll();
        System.out.println(list);
        return list;
    }

    @RequestMapping("/getAllForJsp.action")
    public String getAllForJspMethod(Model model){
        List<Student> list=studentService.getAll();
        System.out.println(list);
        model.addAttribute("list",list);
        return "index";
    }
}

19 添加crud功能

添加action

package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import com.zhiyou100.exception.StudentCrudExceprion;
import com.zhiyou100.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@RequestMapping("/student")
@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAll.action")
    public String getAllMethod(Model model){
         model.addAttribute("list",studentService.getAll());
         return  "index";
    }

    @RequestMapping("/getAllJson.action")
    @ResponseBody
    public List<Student> getAllJsonMethod(){
        return  studentService.getAll();
    }

    @RequestMapping("/getOne/{sid}.action")
    public String getOneMethod(@PathVariable("sid") int sid, Model model){
        model.addAttribute("stu",studentService.getOneById(sid));
        return  "index";
    }
    @RequestMapping("/deleteOne/{sid}.action")
    public String deleteOneMethod(@PathVariable("sid") int sid, Model model){
        studentService.deleteOne(sid);
        model.addAttribute("message","删除成功!");
        return  "index";
    }

    @RequestMapping("/addOne.action")
    public String addOneMethod(Student student,Model model){
        studentService.addOne(student);
        model.addAttribute("message","添加成功!");
        return  "index";
    }
    @RequestMapping("/updateOne.action")
    public String updateOneMethod(Student student,Model model){
        studentService.udpateOne(student);
        model.addAttribute("message","修改成功!");
        return  "index";
    }
}

页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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">
    <script type="text/javascript" src="<c:url value='/js/jquery-1.8.0.min.js'/>"></script>
    <link type="text/css" rel="stylesheet" href="<c:url value='/css/main.css'/>"/>
</head>
<body>
<h1>学生信息管理页面</h1>
<c:if test="${empty requestScope.list}">
    <jsp:forward page="/student/getAll.action"/>
</c:if>
<table  id="tab_list">
    <c:if test="${not empty requestScope.message}">
        <tr>
             <th colspan="7" style="color: red;">${requestScope.message}</th>
        </tr>
    </c:if>

     <tr>
         <th>学号</th><th>名字</th><th>性别</th><th>分数</th><th>党员</th><th>操作</th>
     </tr>
    <c:forEach items="${requestScope.list}" var="s">

        <tr>
            <td>${s.sid}</td>
            <td>${s.sname}</td>
            <td>${s.sex}</td>
            <td>${s.score}</td>
            <td>${s.sdy}</td>
            <td>
                <a  href="<c:url value='/student/deleteOne/${s.sid}.action'/>">删除</a> |
                <a  href="<c:url value='/student/getOne/${s.sid}.action'/>">修改</a>
            </td>
        </tr>
    </c:forEach>
</table>
<c:choose>
    <c:when test="${empty requestScope.student}">
        <c:url var="url" value="/student/addOne.action"/>
        <c:set value="添加" var="butValue"/>
    </c:when>
    <c:otherwise>
        <c:url var="url" value="/student/updateOne.action"/>
        <c:set value="修改" var="butValue"/>
    </c:otherwise>
</c:choose>
<form action="${url}" method="post" >
    <input type="hidden" name="sid" value="${requestScope.student.sid}"/>
    <table id="tab_add_update">
          <tr>
              <th>学生名字:</th>
              <td><input  name="sname" value="${requestScope.student.sname}" type="text"/></td>
          </tr>
        <tr>
            <th>学生性别:</th>
            <td>男<input  name="sex" value="男" type="radio"/> |
            女<input  name="sex" value="女" type="radio"/>  </td>
        </tr>
        <tr>
            <th>学生分数:</th>
            <td><input  name="score" value="${requestScope.student.score}" type="text"/></td>
        </tr>
        <tr>
            <th>是否党员:</th>
            <td>是<input  name="sdy" value="true" type="radio"/> |
                否<input  name="sdy" value="false" type="radio"/>  </td>
        </tr>
        <tr>
            <th colspan="2">
                <input type="submit" value="${butValue}"  id="but_submit"/>
            </th>
        </tr>

    </table>
</form>

</body>
</html>

测试

在这里插入图片描述

改进:

党员和性别默认选中
<script type="text/javascript">
      $(function () {
              var sex="${requestScope.student.sex}";
              if(sex){
                  $.each($("#tab_add_update input[name='sex']"),function(i,n){
                      if($(n).val()==sex){
                          $(n).attr("checked","checked");
                      }
                  });
              }
              var sdy="${requestScope.student.sdy}";
              if(sdy){
                  $.each($("#tab_add_update input[name='sdy']"),function(i,n){
                      if($(n).val()==sdy){
                          $(n).attr("checked","checked");
                      }
                  });
              }
      });
</script>

20 解决问题

20.1 js文件加载失败:404

在这里插入图片描述

  • 注意1:
script标签不能内部闭合
  • 注意2
配置中央控制器时:url 必须是*.action 不能是/*

20.2 事务 增删改没有提交事务

  • 1pom.xml中引入spring-tx的jar
<!--事务管理-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>4.3.1.RELEASE</version>
</dependency>
  • 2 在spring的核心配置文件中 引入tx的ns
<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:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-4.1.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
  • 3 在spring的核心配置文件中 通过tx标签启动事务
<!--启动事务-->
<tx:annotation-driven/>
  • 4 改service添加事务
package com.zhiyou100.service;

import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class StudentServiceImp   implements  StudentService{
    @Autowired
    private StudentDao studentDao;

    @Override
    public Student getOneById(int id) {
        return studentDao.getOneByKey(id);
    }

    @Override
    public Student getOneByName(String name) {
        return studentDao.getOneByName(name);
    }

    @Override
    public List<Student> getAll() {
        return studentDao.getAll();
    }

    @Override
    @Transactional//可以加在方法上 也可以加在类上
    public int addOne(Student s) {
        return studentDao.addOne(s);
    }

    @Override
    @Transactional//可以加在方法上 也可以加在类上
    public int deleteOne(int id) {
        return studentDao.deleteOne(id);
    }

    @Override
    @Transactional//可以加在方法上 也可以加在类上
    public int udpateOne(Student s) {
        return studentDao.updateOne(s);
    }
}

  • 5 修改dao的getSeesion的方法
@Repository
public class StudentDaoImp   implements  StudentDao{
    @Autowired
    private SessionFactory factory;
    @Override
    public Session getSession() {
        //return factory.openSession();
        return factory.getCurrentSession();
    }
    ...
}
  • 6 改dao实现类添加注解
否则报错:HibernateException: Could not obtain transaction-synchronized Session for current thread
@Repository
@Transactional
public class StudentDaoImp   implements  StudentDao{
    ...
}
  • 测试成功

在这里插入图片描述

20.3 单元测试

  • 1 引入spring-test的jar
<!--单元测试-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.1.RELEASE</version>
</dependency>
  • 2 更改junit的版本
<!-- 单元测试
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    -->
<!-- junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
  • 3 测试类
package com.zhiyou100.test;

import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entity.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring_config.xml","classpath:springmvc_config.xml"})
public class Test01 {

    @Autowired
    private StudentDao studentDao;

    @Test
    public void test01(){
        System.out.println(studentDao.getAll());
        System.out.println(studentDao.getOneByName("444"));
        System.out.println(studentDao.getOneByKey(1));
        System.out.println("添加:"+studentDao.addOne(new Student(null,"呵呵","男",33f,true)));
        System.out.println("删除:"+studentDao.deleteOne(2));
        System.out.println("修改:"+studentDao.updateOne(new Student(3,"哈哈","男",44f,true)));
    }
}
  • 结果

在这里插入图片描述

20.4 显示日志信息

  • 引入log4j依赖的jar
<!--日志系统-->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
</dependency>
<!-- log4j配置, 视情况添加-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4jVersion}</version>
</dependency>
  • 在resources下创建log4j的属性集文件
log4j.rootLogger=DEBUG,console,file

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%M-%t-%r-%d{HH:mm:ss}-%m%n

log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=d:\log4j\log4j.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

log4j.logger.java.sql=DEBUG
log4j.logger.com.zhiyou100=DEBUG
log4j.logger.org.springframework=ERROR
log4j.logger.com.alibaba=DEBUG
log4j.logger.com.mchange.v2.resourcepool.BasicResourcePool=ERROR
log4j.logger.com.mchange.v2=ERROR
  • 创建文件夹:d:log4j
  • 测试

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4dz5rCCB-1682126190381)(imgs/image-20230220150637345.png)]

20.5 异常处理

  • 定义异常类
package com.zhiyou100.exception;

public class StudentCrudExceprion   extends RuntimeException{
    public StudentCrudExceprion(String ms){
        super(ms);
    }
}
  • 处理异常的advice
package com.zhiyou100.action;
...
@RestControllerAdvice
public class MyExceptionAdvice{

    @ExceptionHandler(StudentCrudExceprion.class)
    public ModelAndView exceptionHandler(StudentCrudExceprion e){
        ModelAndView mav=new ModelAndView();
        mav.addObject("message",e.getMessage());
        mav.setViewName("index");
        return mav;
    }
}
  • action出现异常
    @RequestMapping("/deleteOne/{sid}.action")
    public String deleteOneMethod(@PathVariable("sid") int sid, Model model){
        Student student=studentService.getOneById(sid);
        if(student==null){
            throw new StudentCrudExceprion("删除失败!sid不存在!");
        }
        studentService.deleteOne(sid);
        model.addAttribute("message","删除成功!");
        return  "index";
    }
  • service出现异常
@Override
@Transactional
public int addOne(Student s) {
    Student student=studentDao.getOneByName(s.getSname());
    if(student!=null){
        throw new StudentCrudExceprion("添加失败!名字不能重复!");
    }
    return studentDao.addOne(s);
}
  • 测试

在这里插入图片描述

  • 注意
1: 处理异常的handler方法不能返回string作为逻辑路径  必须是返回modelanview
@ExceptionHandler(StudentCrudExceprion.class)
public ModelAndView exceptionHandler(StudentCrudExceprion e){
    ModelAndView mav=new ModelAndView();
    mav.addObject("message",e.getMessage());
    mav.setViewName("index");
    return mav;
}
2:注意数据回显:判断添加还是修改 域属性名不能为student
3: hql中写法和sql完全相同 除了类名+属性名::::
    字符串写在单引号中
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。