学习日志day51(2021-09-17)(1、Spring事务 2、SpringMVC)

学习内容:学习Spring框架(Day51)

1、Spring事务
2、SpringMVC


1、Spring事务

(1)Spring事务隔离级别
• DEFAULT 使用数据库默认隔离级别
• READ_UNCOMMITTED 允许读取尚未提交的数据。可能导致脏读、幻读或不可重复读。
• READ_COMMITTED 允许从已经提交的并发事务读取。可以防止脏读,但依然会出现幻读和不可重复读。
• REPEATABLE_READ 对相同字段的多次读取结果是相同的,除非数据被当前事务改变。可以防止脏读和不可重 复读,但幻读依然出现。
• SERIALIZABLE 完全符合ACID的隔离级别,确保不会发生脏读,幻读和不可重复读。

(2)• 脏读:一个事务读取到另一个事务没有提交到的数据。
• 不可重复读:在同一事务中,多次读取同一数据返回的结果不同。
• 幻读:一个事务读取到另一个事务已经提交的事务。

(3)Spring事务传播属性
• REQUIRED 业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到这个事务中, 否则自己创建一个事务。(大部分情况下使用)
• NOT-SUPPORTED 声明方法需要事务。如果方法没有关联到一个事务,容器会为它开启一个事务,如果方法在 一个事务中被调用,该事务将会被挂起,在方法调用结束后 ,原先的事务会恢复执行。
• REQUIREDNEW 业务方法必须在自己的事务中运行。一个新的事务将被启动,而且如果有一个事务正在运行, 则将这个事务挂起,方法运行结束后,新事务执行结束,原来的事务恢复运行。
• MANDATORY 该方法必须运行在一个现有的事务中,自身不能创建事务,如果方法在没有事务的环境下被调用, 则会抛出异常。
• SUPPORTS 如果该方法在一个事务环境中运行,那么就在这个事务中运行,如果在事务范围外调用,那么就在 一个没有事务的环境下运行。
• NEVER 表示该方法不能在有事务的环境下运行,如果在有事务运行的环境下调用,则会抛出异常
• NESTED 如果一个活动的事务存在,则运行在一个嵌套的事务中,如果没有活动事务,则按照REQUIRED事 务方式执行。该事务可以独立的进行提交或回滚,如果回滚不会对外围事务造成影响

(4)1.编程式事务
使用Spring事务需要的jar包
spring-tx.jar

配置applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--开启基于注解的bean管理 依赖注入-->
    <context:component-scan base-package="com.hisoft"/>
  
    <!--获取配置文件-->
    <context:property-placeholder location="db.properties"/>
    <!--配置数据源-->
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        <property name="username" value="${db.userName}"/>
        <property name="password" value="${db.password}"/>
        <property name="jdbcUrl" value="${db.url}"/>
<!--    <property name="driverClassName" value="${db.driver}"/>-->
    </bean>

    <!-- 构建事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

(5)基于XML配置的事务,主要依赖于AOP切面加入事务管理,当出现异常时进行回滚

<!-- 基于XML配置的事务 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- name表示事务管理器在指定的包中哪些方法上生效,以什么开头,propagation表示传播属性 -->
        <tx:method name="save*" propagation="REQUIRED"/>
        <tx:method name="del*"/> 
        <tx:method name="edit*"/>
        <!-- read-only="true"只读事务 -->
        <tx:method name="find*" read-only="true"/>
        <!-- name="*"表示在包中所有方法上生效,rollback-for表示触发回滚的异常范围 -->
        <tx:method name="*" rollback-for="Exception"/>
    </tx:attributes>
</tx:advice>
<aop:config>
    <!--配置切入点,指定生效的包-->
    <aop:pointcut expression="execution(* com.hisoft.service..*.*(..))" id="myPointcut"/>
    <!--事务的切入点-->
    <aop:advisor advice-ref="txAdvice" pointcut-ref = "myPointcut" />
</aop:config>

(6)2.声明式事务
基于Annotation的事务

<!--开启基于注解的事务管理-->
<tx:annotation-driven transaction-manager="transactionManager"/>

构建一个异常

public class MyException extends RuntimeException{
    public MyException(){
        super();
    }
    public MyException(String msg){
        super(msg);
    }
    public MyException(Throwable th,String msg){
        super(msg,th);
    }
}

Spring事务出现在Service层,在service层加上@Transactional注解,加入事务管理

@Transactional
@Service("bookService")
public class BookServiceImpl {

    @Autowired
    private BookDao bookDao;
    public void save(Book book){
        bookDao.save(book);
    }
    //可以在方法上再次加上@Transactional注解,使事务只读,会覆盖类上的事务
    @Transactional(readOnly = true)
    public Book findById(int id){
        return bookDao.findById(id);
    }
}

当在Dao层或者service层出现运行时异常时,数据不会保存,进行回滚。但是在外部,如controller层出现异常时,不会回滚。事务只能处理运行时异常,其它异常被try catch后事务无法处理。

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(Book book) {
        String sql = "insert into book(bookname,author,publisher) values(?,?,?)";
        jdbcTemplate.update(sql, book.getBookName(), book.getAuthor(), book.getPublisher());
	//抛出异常,存入失败
        if(true){
            throw new MyException();
        }
    }
}

@Transactional(rollbackFor=Exception.class) 如果目标方法出现该异常,事务回滚
MyException不是运行时异常

public class MyException extends Exception{
    public MyException(){
        super();
    }
}

指定异常,出现该异常时事务回滚

@Transactional(rollbackFor = Exception.class)
@Service("bookService")
public class BookServiceImpl {

    @Autowired
    private BookDao bookDao;
    public void save(Book book) throws MyException {
        bookDao.save(book);
    }
}

配置隔离级别和传播属性
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED)

(7)编程式事务和声明式事务
编程式事务是通过编程开启的事务,比较繁琐

@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private HikariDataSource hikariDataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void save(Book book) throws MyException, SQLException {
        String sql = "insert into book(bookname,author,publisher) values(?,?,?)";
        jdbcTemplate.update(sql, book.getBookName(), book.getAuthor(), book.getPublisher());
        Connection conn = hikariDataSource.getConnection();
        PreparedStatement statement = conn.prepareStatement(sql);
        conn.rollback();
        conn.commit();//提交事务
}

声明式事务就是通过注解开启的事务。

2、SpringMVC

(1)需要的jar包有
spring-web.jar
spring-webmvc.jar
jstl.jar
javax.servlet-api.jar

(2)Spring的web框架围绕DispatcherServlet设计。 这是一个前端控制器,所有请求都要先通过前端控制器,DispatcherServlet的作用是将请求分发到不同的处理器,创建在WEB-INF目录下。

在这里插入图片描述

在web.xml文件中配置中央(前端)控制器和Spring ioc容器

<!--配置springMVC前置控制器-->
<servlet>
  <!--名字对应前端控制器文件mvc-servlet.xml文件名的前半-->
  <servlet-name>mvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--服务器在启动的时候,就加载springmvc的配置文件,如果不配置就默认去WEB-INF文件夹下找
    如果不配置初始化参数就要把springmvc的配置文件放到WEB-INF文件夹下-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:mvc-servlet.xml</param-value>
  </init-param>
  <!--tomcat启动时就需要启动,所有的请求都要经过前端控制器-->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>mvc</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 配置spring ioc容器 -->
<context-param>
  <param-name>contextConfigLocation </param-name>
  <param-value>classpath:applicationContext.xml </param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener </listener-class>
</listener>

创建mvc-servlet.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
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--开启基于注解的bean管理 依赖注入-->
    <!--自动扫描com.hisoft.controller包,数据和请求通过前端控制器到controller层再发送给服务层-->
    <!--服务层返回的数据通过controller层返回到前端控制器,前端控制器将数据解析后返回给客户端-->
    <context:component-scan base-package="com.hisoft.controller"/>

    <!--获取配置文件-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--开启使用注解传递参数,在springMVC中只能通过注解来传递参数,不能配置文件来传递参数-->
    <mvc:annotation-driven/>

    <!--配置视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <!--注入jstl类型的视图-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!--视图前缀-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--视图后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--访问静态资源,不设置的话请求这个目录下文件时会认为是controller请求-->
    <mvc:resources mapping="/static/**" location="/static/"/>
    
    <!--其它映射,不经过controller层直接跳转到页面,path是url路径,view-name是跳转的文件名-->
    <mvc:view-controller path="/" view-name="upload"/>
</beans>

controller层

@Controller
//@RequestMapping("/books")  如果在类上设置了请求url,方法上的请求url就默认跟在/books后面
public class BookController {
    //@requestMapping("/book/save") 设置请求url
    //设置get请求,也可以这样写@RequestMapping(value =”/book/save”,method=RequestMethod.GET)
    @GetMapping("/book/save") 
    //@RequestParam设置请求参数,required = false表示输入url时不强制必须添加参数,
    //defaultValue表示参数的默认值,value = "uid"表示参数的键为uid时,值赋给id
    //参数需要使用包装类型
    public String save(@RequestParam(required = false, defaultValue = "13", value = "uid") Integer id, Integer p) {
        System.out.println("save....." + id);
        //跳转到book.jsp页面
        return "book";
    }
}

(3)接收表单提交值
创建jsp页面

<form action="book/save" method="post">
    书籍名称:<input type="text" name="bookName" />
    作者名称:<input type="text" name="author"/>
    ISBN:<input type="text" name="ISBN"/>
    <input type="submit" value="提交">
</form>

controller层

//设置post请求
@PostMapping("/book/save")
public String save(String bookName,String author) {
    System.out.println("save....." + bookName + "\t" + author);
    return "book";
}

在web.xml文件中配置字符集过滤器解决提交数据乱码

<!--spring 字符集过滤器-->
<filter>
  <filter-name>encoding</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>encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

如果有一个Book实体类,属性名与提交的表单参数相同,controller层也可以这样接收表单数据

@PostMapping("/book/save")
//传入的参数是一个Book对象,这是根据Book类中的set方法名来匹配的,
//实体类中没有这样的属性名时再设置其它参数
public String save(Book book, String ISBN) {
    System.out.println("save....." + book.getBookName() + "\t" + book.getAuthor());
    return "book";
}

(4)输入url时参数的格式

//此时输入url时写的是/book/update/2/3  ,参数p的值用正则表达式限制为整数
@GetMapping("/book/update/{id}/{p:\\d+}")
//设置参数时使用@PathVariable才能写为这种格式
public String update(@PathVariable(value = "id") Integer uid, @PathVariable Integer p) {
    System.out.println("uid: " + uid + " p: " + p);
    return "book";
}

(5)使用重定向进行跳转,使用request和session获取参数

@GetMapping(value = "/book/del/{id}")
public String delete(@PathVariable Integer id) {
    System.out.println(id);
    //使用redirect重定向进行跳转
    return "redirect:/book/list";
}

@GetMapping("/book/list")
  //传入request和session对象来获取参数,/book/list?age=12
  public String findAll(HttpServletRequest request, HttpSession session){
      System.out.println(request.getParameter("age"));
      List<String> bookList = new ArrayList<>();
      bookList.add("Rose");
      bookList.add("Jack");
      bookList.add("Jerry");
      return "list";
  }

(6)使用Model、ModelMap和ModelAndView带参跳转到jsp页面
Model和ModelMap

@GetMapping("/book/list")
  //可以使用public String findAll(ModelMap modelMap){
  public String findAll(Model model){
      List<String> bookList = new ArrayList<>();
      bookList.add("Rose");
      bookList.add("Jack");
      bookList.add("Jerry");
      //跳转到list.jsp页面后,可以使用jstl语句获取bookList值
      model.addAttribute("bookList",bookList);
      //modelMap.addAttribute("bookList",bookList);
      return "list";
  }

ModelAndView

@GetMapping("/book/list")
public ModelAndView findAll() {
    ModelAndView modelAndView = new ModelAndView("list");
    List<String> bookList = new ArrayList<>();
    bookList.add("Rose");
    bookList.add("Jack");
    bookList.add("Jerry");
    modelAndView.addObject("bookList",bookList);
    return modelAndView;
}

list.jsp页面

<h3>books</h3>
<c:forEach items="${bookList}" var="book">
    ${book}
</c:forEach>

(7)传入RedirectAttributes参数,跳转后进行提示

@GetMapping(value = "/book/del/{id}")
public String delete(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
    System.out.println(id);
    //在跳转前设置提示
    redirectAttributes.addFlashAttribute("msg","删除成功!");
    return "redirect:/book/list";
}

list.jsp页面,刷新页面提示信息就会消失

<div>
    ${msg}
</div>

(8)使用@ResponseBody返回字符串

@GetMapping("/txt")
//@ResponseBody  也可以写在方法上方
 public @ResponseBody String respText(){
     //此时是返回字符串"Hello",而不是跳转页面
     return "Hello";
 }

使用@ResponseBody返回json数据

//设置produces属性
@GetMapping(value = "/json",produces = "application/json;charset=utf-8")
 public @ResponseBody String respJson(){
     //此时返回的是json数据
     return "{\"name\":\"jerry\"}";
 }

也可以使用下面的方法返回json数据,但是可能会因为导入的jackson-databind.jar包版本问题而报错,但是不影响使用。网上有解决报错的方法。

@GetMapping(value = "/list",produces = "application/json;charset=utf-8")
public @ResponseBody List<Book> findAllJson(){
    Book book = new Book();
    book.setBookName("Spring 实战");
    book.setAuthor("边佳");
    List<Book> bookList = new ArrayList<>();
    bookList.add(book);
    return bookList;
}

(9)使用@RequestBody注解,用来接收前端传递给后端的json字符串中的数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值