栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Day03笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring Day03笔记

Spring事务:

        1.在业务层接口上使用@Transactional注解

        2.Spring配置类中,启用事务@EnableTransactionManagement

        3.在Jdbc配置类中,定义事务管理类

@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
    DataSourceTransactionManager tm = new DataSourceTransactionManager();
    tm.setDataSource(dataSource);
    return tm;
}

Spring事务角色:

        事务管理员:发起事务者,开启事务的方法。下图中事务T。

        事务协调员:参与事务者,数据层或业务层方法。下图事务T1和T2

Spring的事务默认只回滚err和运行时异常,对于IO异常这类直接继承于Exception的编译时异常是不回滚的,但可以通过rollbackfor属性属性设置回滚类型 

@Transactional(rollbackFor = IOException.class)

事务传播行为:业务要求转账操作执行失败后,日志不回滚,但现在的情况是三个事务都加入了同一个事物。要回滚一起回滚,如下图。可在日志接口使用propagation属性,设置属性传播行为

@Transactional(propagation = Propagation.REQUIRES_NEW)

 SpringMVC:

1.导入相关jar包


    javax.servlet
    servlet-api
    2.5
    provided



    org.springframework
    spring-webmvc
    5.2.10.RELEASE

注意,servlet一定要加provided作用范围,否则报错A child container failed during start 


    org.apache.tomcat.maven
    tomcat7-maven-plugin
    2.1
    
        90
        /
    

2.创建控制器类

package com.supersql.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    //设置访问路径
    @RequestMapping("/save")
    //设置当前操作的返回值类型
    @ResponseBody
    public String save(){
        return "{name:'张三'}";
    }
}

3.初始化SpringMvc配置类

package com.supersql.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.supersql.controller")
public class SpringMvcConfig {
}

4.初始化servlet容器,加载MVC环境

package com.supersql.config;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;

public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
    //加载SpringMvc容器的配置
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(SpringMvcConfig.class);
        return ctx;
    }
    //设置哪些请求归属Mvc
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //加载Spring容器配置
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        return null;
    }
}

简化方案:

package com.supersql.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{
                SpringConfig.class
        };
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{
                SpringMcvConfig.class
        };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{
                "/"
        };
    }

}

工作流程:

加载Spring控制的bean时,排除SpringMvc控制的bean

按注解过滤:

@ComponentScan(value = "com.supersql",excludeFilters = @ComponentScan.Filter(
        type = FilterType.ANNOTATION,
        classes = Controller.class
))
public class SpringConfig {
}

设置请求映射路径:

        @RequestMapping,可用于类注解,方法注解

Post请求处理中文乱码:

//Servlet容器中
@Override
protected Filter[] getServletFilters() {
    CharacterEncodingFilter cf = new CharacterEncodingFilter();
    cf.setEncoding("UTF-8");
    return new Filter[]{cf};
}

五种类型的参数传递:@RequestParams适用于url、表单传参,@RequestBody适用于json传参

        普通参数:默认按参数名接参数,参数名不同的可用@RequestParam绑定请求参数

        POJO类型:如果请求参数和实体类中的参数名一样,就自动装配

        嵌套POJO型:User类型中嵌套Address类型,参数传递时应为address.city,参数名.属性

        数组类型:传递多个同名参数,用同名数组接收

        集合类型: 不加@RequestParams注解,会将集合类型当成POJO类型,尝试构造对象。

JSON数据类型传递:

        1.导入jackson坐标

        2.SpringMvc配置类中开启@EnableWebMvc

日期类型参数传递:

        对于yyyy/MM/dd格式的日期,可直接用Date类型接受,其他格式需要用@DataTimeFormat进行格式化

@RequestMapping("/time")
@ResponseBody
public String time(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date){
    System.out.println(date);
    return "test";
}

响应:

        响应页面:不加@ResponseBody,返回值是String,就是响应页面。

        响应文本:加@ResponseBody,返回值是String。

        响应json:加@ResponseBody,返回pojo,pojo转json是由(HttpMessageConverter)jackson完成的

Rest风格:从路径取参数@PathVariable,如果全类都是响应数据的,可以把@ResponseBody放到类上面,从而简化书写。

        @Controller + @ResponseBody = @RestController

        @RequestMapping(method = RequestMethod.POST) = @PostMapping

@RequestMapping(value = "/save/{username}",method = RequestMethod.POST)
//@PostMapping("/save/{username}") ,简化开发
@ResponseBody
    public String save(@PathVariable String username){
    System.out.println(username);
    return username;
}

放行静态资源:

        此时如果想访问:/pages/test.jsp,会报错因为servlet容器配置类中已经把所有请求都给SpringMvc处理了,实际上上述页面应该给tomcat处理的。

定义配置类,SpringMvcConfig里扫描带他上,即可

package com.supersql.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当访问pages/下的资源,不要走mvc
        registry.addResourceHandler("/pages/**","/css/**").addResourceLocations("/pages/",""/css/);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036138.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号