当前位置: 首页 > news >正文

SpringBooot

目录

一、简介

1、使用原因

2、JavaConfig

(1)Configuration注解

(2)Bean注解

(3)ImportResource注解

(4)PropertyResource注解

(5)案例

3、简介

4、特征

 5、SpringBoot案例

 6、SpringBoot配置文件

二、多环境配置

三、@Value 注解@ConfigurationProperties注解

四、SpringBoot使用jsp

五、SpringBoot使用容器

六、CommandLineRunner接口, ApplicationRunner接口

 七、拦截器

八、servlet

九、过滤器

十、SpringBoot字符集过滤器

1、spingmvc自带的

2、根据属性文件

十一、SpringBoot整合Mybatis

1、 @mapper

2、 @MapperScan

十二、SpringBoot事务

1、Spring框架中的事务

2、Springboot中使用事务,

十三、RESTFUL 架构风格


一、简介

1、使用原因

(1、)因为spring,springmvc需要使用的大量的配置文件(xml)

             还需要配置各种对象,把使用的对象放入到spring容器中才能使用对象

             需要了解其它框架配置规则

(2、)springboot,就相当于不需要配置文件 spring+springmvc.常用的框架和第三方都已经配置好了.直接拿来使用就可以

(3、)Springboot开发效率高,使用方便

2、JavaConfig

JavaConfig: 使用java类作为XML配置文件的替代。

                    是配置spring容器的纯JAVA的方式

                   在这个java类这可以创建java对象,把对象放入spring容器中(注入到容器)

(1)Configuration注解

放在一个类的上面,表示这个类是作为配置文件使用的.

(2)Bean注解

声明对象,把对象注入到容器中

(3)ImportResource注解

作用导入其它的xml配置文件

相当于<import resource="文件.xml"/>

(4)PropertyResource注解

作用:读取properties属性配置文件,使用配置文件可以实现外部化配置

在程序代码之外提供数据.

步骤:

<1>resources目录下,创建properties 文件,使用 key =value的格式提供数据

<2>PropertyResource指定 properties文件的位置

<3>使用@Value(value="${key")

(5)案例

package com.iotek.vo;/*** @Author:* @CreateTime: 2023-04-03  16:52*/
public class Car {private String name;private String color;private String brand;public Car() {super();}public Car(String name, String color, String brand) {this.name = name;this.color = color;this.brand = brand;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}@Overridepublic String toString() {return "Car{" +"name='" + name + '\'' +", color='" + color + '\'' +", brand='" + brand + '\'' +'}';}
}
package com.iotek.vo;import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;/*** @Author:* @CreateTime: 2023-04-03  17:24*/
@Component("employee")
public class Employee {@Value("${employee.name}")private String name;@Value("${employee.age}")private Integer age;@Overridepublic String toString() {return "Employee{" +"name='" + name + '\'' +", age=" + age +'}';}
}
package com.iotek.vo;/*** @Author:* @CreateTime: 2023-04-03  16:25*/
public class Student {private String name;private Integer age;private String address;public Student() {super();}public Student(String name, Integer age, String address) {this.name = name;this.age = age;this.address = address;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}
}
package com.iotek.config;import com.iotek.vo.Student;
import org.springframework.context.annotation.*;/*** @Author:* @CreateTime: 2023-04-03  16:24*/
//Configuration 表示当前类是作为配置文件使用的,用来配置容器,位置在类上
//PropertySource  加载配置文件
//@ComponentScan  扫描
@Configuration
@ImportResource(value = "classpath:applicationContext.xml")
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages="com.iotek.vo")
public class SpringConfig {/*** 创建方法:方法的返回值是对象,在方法的上面加入@Bean* 方法的返回值对象就注入到容器中** @Bean 把对象注入到Spring容器中  相当于<bean></bean>* @Bean 不指定对象的名称,默认是方法名是ID**/@Beanpublic Student createStudent(){Student student = new Student();student.setName("蓉儿");student.setAge(23);student.setAddress("台湾");return  student;}/*** 指定对象在容器中的名称<bean>的ID属性**/@Bean(name = "s2")public Student createStudent2(){Student student = new Student();student.setName("祖儿");student.setAge(26);student.setAddress("杭州");return  student;}
}

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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="car" class="com.iotek.vo.Car"><property name="name" value="奥迪"/><property name="color" value="黑"/><property name="brand" value="大众"/></bean>
</beans>

beans.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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><bean id="s1" class="com.iotek.vo.Student"><property name="name" value="小青"/><property name="age" value="22"/><property name="address" value="上海"/></bean>
</beans>

config.properties

employee.name=小花
employee.age=33
package com.iotek;import com.iotek.config.SpringConfig;
import com.iotek.vo.Car;
import com.iotek.vo.Employee;
import com.iotek.vo.Student;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/*** @Author:* @CreateTime: 2023-04-03  16:30*/
public class SpringTest {@Testpublic void test1(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");Student student = (Student) applicationContext.getBean("s1");System.out.println("student容器对象----"+student);//student容器对象----Student{name='小青', age=22, address='上海'}}@Testpublic void test2(){ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);Student student = (Student) applicationContext.getBean("createStudent");System.out.println("JavaConfig容器对象----"+student);//JavaConfig容器对象----Student{name='蓉儿', age=23, address='台湾'}}@Testpublic void test3(){ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);Student student = (Student) applicationContext.getBean("s2");System.out.println("JavaConfig容器对象----"+student);//JavaConfig容器对象----Student{name='祖儿', age=26, address='杭州'}}@Testpublic void test4(){ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);Car car = (Car) applicationContext.getBean("car");System.out.println("JavaConfig容器ImportResource注解对象----"+car);//JavaConfig容器ImportResource注解对象----Car{name='奥迪', color='黑', brand='大众'}}@Testpublic void test5(){ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);Employee employee = (Employee) applicationContext.getBean("employee");System.out.println("JavaConfig容器PropertySource注解对象----"+employee);//JavaConfig容器PropertySource注解对象----Employee{name='小花', age=33}}
}

3、简介

springboot是spring中的一个成员.可简化 spring,springmvc的使用。它的核心还是lOC容器.

4、特征

  • 创建独立的 Spring 应用程序

  • 直接嵌入Tomcat,Jetty或Undertow(无需部署WAR文件)

  • 提供“starter”依赖项以简化构建配置

       比如使用mybatis框架,需要在spring项目中,配置 mybatis的对象sqlsessionFactory, Dao的代理对象,在springboot项目中,在POM.xml里面加入了一个 mybatis spring.boot starter依赖。

  • 尽可能自动配置 Spring 和第三方库

  • 提供了健康检查,统计,外部化配置.

  • 无需生成代码,也无需 XML 配置 

 5、SpringBoot案例

@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,可以使用bean声明对象,并注入容器配置文件
@EnableAutoConfiguration启用自动配置,把Java对象配置好,注入到spring容器中
@ComponentScan扫描器,找到注解,根据注解的功能创建好,给属性赋值等等.默认扫描包:@ComponentScan所在的类所在的包和子包.
package com.iotek.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author:* @CreateTime: 2023-04-03  18:17*/
@Controller
public class HelloSpringboot {@RequestMapping(value = "/hello")@ResponseBody//响应public String helloSpringBoot(){return "欢迎使用SpringBoot框架";}
}

 6、SpringBoot配置文件

配置文件application

扩展名:properties(k=v)  yml

使用application.properties       application.yml

application.properties

#设置端口号
#server.port=8022
#设置访问应用上下文路径 contextpath
#server.servlet.context-path=/myboot

application.yml

server:port: 8044servlet:context-path: /myboot2

二、多环境配置

有开发环境、测试环境,上线环境

每个环境有不同的配置信息,比如:端口,上下文件,数据库 URL,用户名,密码等等

使用多环境配置文件,可以方便的切换不同的配置

使用方式:创建多个配置文件,名称规则application-环境名称.properties(yml)

创建开发环境的配置文件:applicatio-dev.properties(application-dev.yml)

创建测试环境的配置文件:application-test.properties

application.properties

#激活使用哪个配置文件
spring.profiles.active=test

三、@Value 注解@ConfigurationProperties注解

@ConfigurationProperties把配置文件的数据映射为java对象。

属性: prefix配置文件中的某些key的开头的内容.

package com.iotek.vo;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;/*** @Author:* @CreateTime: 2023-04-03  21:27*/
@Component
@ConfigurationProperties(prefix = "employee")
public class EmployeeInfo {private String name;private Integer age;private String address;public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "EmployeeInfo{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';}
}
package com.iotek.controller;import com.iotek.vo.EmployeeInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;/*** @Author:* @CreateTime: 2023-04-03  21:11*/
@Controller
public class EmployeeController {@Value("${server.port}")private Integer port;@Value("${server.servlet.context-path}")private String contextPath;@Value("${employee.name}")private String name;@Value("${employee.age}")private Integer age;@Value("${employee.address}")private String address;@Resourceprivate EmployeeInfo info;@RequestMapping(value = "/data")@ResponseBodypublic String queryData(){return "name="+name+" age=" + age +" address=" + address+";访问路径=" + contextPath+" 端口号="+port;}@RequestMapping(value = "/info")@ResponseBodypublic String queryEmployeeInfo(){return info.toString();}
}

application.properties

server.port=8083
server.servlet.context-path=/mydataemployee.name=蓉儿
employee.age=24
employee.address=台湾

四、SpringBoot使用jsp

Springboot不推荐使用jsp,而是使用模板技术代替 jsp

<!-- 编译jsp --><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.2.1</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><!-- 指定jsp编译后存放的路径 --><resources><resource><!-- jsp原来的路径 --><directory>src/main/webapp</directory><!-- 指定编译后的存放路径 --><targetPath>META-INF/resources</targetPath><!-- 指定处理的目录文件 --><includes><include>**/*.*</include></includes></resource></resources>
server.port=8088
server.servlet.context-path=/myboot#视图解析器
#前缀  后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
<%--Created by IntelliJ IDEA.User: 杪&秋Date: 2023/4/4Time: 10:39To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><h1>使用JSP,显示控制器的数据${data}</h1>
</body>
</html>
package com.iotek.controller;import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;import javax.servlet.http.HttpServletRequest;/*** @Author:* @CreateTime: 2023-04-04  10:41*/
@Controller
public class ShowDataController {@RequestMapping(value ="showdata")public String showData(Model model){model.addAttribute("data","小青");return "index";//逻辑视图名}
}

五、SpringBoot使用容器

想在通过代码,从容器获取对象

SpringApplication.run(Application.class args);返回值获取容器.

public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
package com.iotek.service;/*** @Author:* @CreateTime: 2023-04-04  11:48*/
public interface UserService {void sayHello(String name);
}
package com.iotek.service.impl;import com.iotek.service.UserService;
import org.springframework.stereotype.Service;/*** @Author:* @CreateTime: 2023-04-04  11:49*/
@Service(value = "userService")
public class UserServiceImpl implements UserService {@Overridepublic void sayHello(String name) {System.out.println("say hello" + name);//say hello小花}
}
package com.iotek;import com.iotek.service.UserService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;@SpringBootApplication
public class Application {public static void main(String[] args) {//手动获取容器对象ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);UserService userService = (UserService)context.getBean("userService");userService.sayHello("小花");}}

六、CommandLineRunner接口, ApplicationRunner接口

这两个接口都有一个run方法,执行时间在容器对象创建好后,自动执行run()方法

可以完成自定义的在容器对象创建好的一些操作

public interface CommandLineRunner {void run(String... args) throws Exception;
}
public interface ApplicationRunner {void run(ApplicationArguments args) throws Exception;
}

 案例:

package com.iotek.service;public interface UserService {String sayHello(String name);
}
package com.iotek.service.impl;import com.iotek.service.UserService;
import org.springframework.stereotype.Service;/*** @Author:* @CreateTime: 2023-04-04  12:18*/
@Service(value = "userService")
public class UserServiceImpl implements UserService {@Overridepublic String sayHello(String name) {return "say hello---"+name;}
}
package com.iotek;import com.iotek.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;import javax.annotation.Resource;@SpringBootApplication
public class Application implements CommandLineRunner {@Autowiredprivate UserService userService;public static void main(String[] args) {System.out.println("创建容器对象之前准备工作...........");SpringApplication.run(Application.class, args);System.out.println("创建容器对象之后...........");}@Overridepublic void run(String... args) throws Exception {//自定义的操作,读取文件、数据库等等。。。。。。。。。。String message = userService.sayHello("祖儿");System.out.println(message);System.out.println("容器对象创建好,执行的方法............");}
}

 七、拦截器

拦截器是spirngmvc中一种对象,能拦截对controller的请求.

自定义拦截器:

1、创建springmvc框架的handlerlnterceptor接口

//请求方法处理前执行@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true;}//请求方法处理后执行@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}//处理后执行@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {HandlerInterceptor.super.afterCompletion(request, response, handler, ex);}
package com.iotek.web;import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @Author:* @CreateTime: 2023-04-04  14:48*/
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("执行拦截器..........preHandle");return true;}
}
package com.iotek.config;import com.iotek.web.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @Author:* @CreateTime: 2023-04-04  15:01*/
@Configuration
public class WebMcvConfig implements WebMvcConfigurer {//添加拦截器对象,注入到容器中@Overridepublic void addInterceptors(InterceptorRegistry registry) {//创建拦截器对象HandlerInterceptor interceptor = new LoginInterceptor();//指定拦截的请求URL地址String path[]={"/user/**"};//指定不拦截的地址String excludePath[] = {"/user/login"};registry.addInterceptor(interceptor).addPathPatterns(path).excludePathPatterns(excludePath);}
}
package com.iotek.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author:* @CreateTime: 2023-04-04  15:06*/
@Controller
public class BootController {@RequestMapping(value = "/user/account")@ResponseBodypublic String userAccount(){return "访问user/account地址";}@RequestMapping(value = "/user/login")@ResponseBodypublic String userLogin(){return "访问user/login地址";}
}

八、servlet

package com.iotek.web;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @Author:* @CreateTime: 2023-04-04  16:06*/
public class MyServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html;charset=utf-8");PrintWriter out = resp.getWriter();out.println("执行servlet。。。。。。。。。。。。。");out.flush();out.close();}
}
package com.iotek.config;import com.iotek.web.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @Author:* @CreateTime: 2023-04-04  16:10*/
@Configuration
public class WebApplicationConfig {@Beanpublic ServletRegistrationBean servletRegistrationBean(){/*ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(),"/myServlet");*/ServletRegistrationBean bean = new ServletRegistrationBean();bean.setServlet(new MyServlet());bean.addUrlMappings("/login","/test");return bean;}
}

九、过滤器

package com.iotek.web;import javax.servlet.*;
import java.io.IOException;/*** @Author:* @CreateTime: 2023-04-04  16:27*/
public class MyFilter implements Filter {@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("执行了过滤器");filterChain.doFilter(servletRequest,servletResponse);}
}
package com.iotek.config;import com.iotek.web.MyFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** @Author:* @CreateTime: 2023-04-04  16:28*/
@Configuration
public class WebAppConfig{@Beanpublic FilterRegistrationBean filterRegistrationBean(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new MyFilter());bean.addUrlPatterns("/user/*");return bean;}
}
package com.iotek.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author:* @CreateTime: 2023-04-04  16:31*/
@Controller
public class FilterController {@RequestMapping(value = "/user/account")@ResponseBodypublic String userAccount(){return "user/account";}@RequestMapping(value = "/query")@ResponseBodypublic String queryAccount(){return "/query";}
}

十、SpringBoot字符集过滤器

1、spingmvc自带的

CharacterEncodingFilter:解决post 请求中文乱码的问题

package com.iotek.web;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @Author:* @CreateTime: 2023-04-07  11:45*/
public class MyServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");PrintWriter pw = resp.getWriter();pw.println("人生如梦");pw.flush();pw.close();}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}
}
package com.iotek.config;import com.iotek.web.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;import java.nio.charset.CharacterCodingException;/*** @Author:* @CreateTime: 2023-04-11  19:30*/
@Configuration
public class WebConfig {@Beanpublic ServletRegistrationBean servletRegistrationBean(){MyServlet myServlet = new MyServlet();ServletRegistrationBean bean = new ServletRegistrationBean(myServlet,"/myServlet");return bean;}//注册过滤器@Beanpublic FilterRegistrationBean filterRegistrationBean(){FilterRegistrationBean bean = new FilterRegistrationBean();//使用springMVC框架的自带的过滤器CharacterEncodingFilter filter = new CharacterEncodingFilter();filter.setEncoding("utf-8");//指定编码filter.setForceEncoding(true);//指定request,response请求都使用Encoding的值bean.setFilter(filter);bean.addUrlPatterns("/*");return bean;}
}
server.servlet.encoding.enabled=false

2、根据属性文件

package com.iotek.web;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;/*** @Author:* @CreateTime: 2023-04-11  20:25*/
public class MyServlet extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");PrintWriter pw = resp.getWriter();pw.println("人生如梦");pw.flush();pw.close();}@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}
}
package com.iotek.config;import com.iotek.web.MyServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @Author:* @CreateTime: 2023-04-11  20:26*/
@Configuration
public class WebConfig {@Beanpublic ServletRegistrationBean servletRegistrationBean(){MyServlet myServlet = new MyServlet();ServletRegistrationBean bean = new ServletRegistrationBean(myServlet,"/myServlet");return bean;}
}
server.port=8082
server.servlet.context-path=/myboot#开启默认的过滤器
server.servlet.encoding.enabled=true
server.servlet.encoding.charset=utf-8#强制request、response使用charset
server.servlet.encoding.force=true

十一、SpringBoot整合Mybatis

1、 @mapper

mapper:放在dao,接口上面,每个接口都需要使用这个注解。

package com.iotek.pojo;/*** @Author:* @CreateTime: 2023-04-11  20:51*/
public class User {private Integer id;private String name;private Integer age;private String email;public User() {super();}public User(Integer id, String name, Integer age, String email) {this.id = id;this.name = name;this.age = age;this.email = email;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", age=" + age +", email='" + email + '\'' +'}';}
}
package com.iotek.dao;import com.iotek.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;@Mapper//mybatis是dao接口,创建此接口前代理对象
@Repository
public interface UserDao {User selectUserById(@Param("userId") Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.iotek.dao.UserDao"><select id="selectUserById" resultType="com.iotek.pojo.User">select * from user where id=#{userId}</select>
</mapper>
package com.iotek.server;import com.iotek.pojo.User;/*** @Author:* @CreateTime: 2023-04-11  21:00*/
public interface UserServer {User queryUser(Integer id);
}
package com.iotek.server.impl;import com.iotek.dao.UserDao;
import com.iotek.pojo.User;
import com.iotek.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @Author:* @CreateTime: 2023-04-11  21:01*/
@Service(value = "userServer")
public class UserServerImpl implements UserServer {@Autowiredprivate UserDao userDao;@Overridepublic User queryUser(Integer id) {return userDao.selectUserById(id);}
}
package com.iotek.controller;import com.iotek.pojo.User;
import com.iotek.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author:* @CreateTime: 2023-04-11  21:03*/
@Controller
public class UserController {@Autowiredprivate UserServer userServer;@RequestMapping(value = "/user/query")@ResponseBodypublic String queryUser(Integer id){User user = userServer.queryUser(id);return user.toString();}
}
server.port=8088
server.servlet.context-path=/myboot#连接数据库相关信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
<!-- resources插件 --><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources>

2、 @MapperScan

找到dao接口和 mapper文件
basePackages: dao接口所在的包名.

十二、SpringBoot事务

1、Spring框架中的事务

1)管理事务的对象,事务管理器(接口,接口有很多的实现类)

JDBC和 mybatis,访问数据库,使用事务管理器DataSourceTranscationManager

2)声明式事务:在 xml配置文件或者使用注解说明事务控制的内容.

控制事务,隔离级别,传播行为,超时时间

3)事务处理方式

<1>Spring框架中的@Transactional

<2>Aspectl框架可以在XML 配置文件中,声明事务控制的内容

2、Springboot中使用事务,

(1、)在业务方法的上面加@Transactional ,加入注解后,方法有事务功能了

(2、)明确在主启动类上面加入@EnableTransationManager

<resources><resource><directory>src/main/resources</directory><includes><include>**/*.*</include></includes></resource></resources>
server.port=8088
server.servlet.context-path=/mybootspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
spring.datasource.username=root
spring.datasource.password=123456mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
package com.iotek.service.impl;import com.iotek.dao.UserDao;
import com.iotek.pojo.User;
import com.iotek.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;/*** @Author:* @CreateTime: 2023-04-12  10:52*/
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserDao userDao;@Transactional//事务表示方法有事务支持,默认使用库的隔离级别REQUIREO 传播行为超时时间 -1  抛出运行时异常,事务回退@Overridepublic int insertUser(User user) {System.out.println("添加用户");int row = userDao.insertUser(user);System.out.println("影响了"+row);int rs = 100 / 0;return row;}
}
package com.iotek.controller;import com.iotek.pojo.User;
import com.iotek.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Author:* @CreateTime: 2023-04-12  10:56*/
@Controller
public class UserController {@Autowiredprivate UserService userService;@RequestMapping("addUser")@ResponseBodypublic String UserService(String name,Integer age,String email){User user = new User();user.setName(name);user.setAge(age);user.setEmail(email);int row = userService.insertUser(user);return "添加用户"+row;}
}
package com.iotek;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;@SpringBootApplication
@EnableTransactionManagement
@MapperScan(basePackages = {"com.iotek.dao"})
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}

十三、RESTFUL 架构风格

Rest(Representational state transfer)表现层状态转移Rest是一种接口的架构风格和设计理念,不

是标准.优点:更简洁,更有层次

表现层就是视图层,显示资源的,通过视图页面,jsp等等为示操作资源的结果.状态:资源变化.

转移:资源可以变化的,资源能创建,查询资源,修改资源,删除资源

在url中,使用名词表示资源,以及访问资源的信息,在URL中,使用/分隔对资源的信息

比如:http://localhost:8088/myboot/user/1001

在使用http中的动作请求方式;表示对资源的操作 CRUD

GET查询资源  /post创建资源   /put更新资源  /DELETE删除资源

Rest :使用URL表示资源,使用HITP动作操作资源

注解:
@PathVariable从URL中获取资源

@GetMapping:支持get 请求-->@RequestMapping(method=RequestMethod.Get)

@PostMapping:支持post请求-->@RequestMapping(method=RequestMethod.Post)

@PutMapping:支持put请求-->@RequestMapping(method=RequestMethod.PUT)

@DeleteMapping:支持delete请求--> @RequestMapping(method=RequestMethod.Delete)

@RestController复合注解(@controller 和@ResponseBody)

在 springmvc中有一个过滤器 HiddenHttpMethodFilter

作用把请求post请求转换成put,delete

Springboot application.properties开启使用HiddenHttpMethodFilter过滤器

package com.iotek.controller;import org.springframework.web.bind.annotation.*;/*** @Author:* @CreateTime: 2023-04-12  20:59*/
@RestController
public class MyRestController {/*** @description: @PathVariablec从URL中获取资源* value路径变量名* userId   定义路径变量名* http://localhost:8080/user/1001**/@GetMapping("/user/{userId}")public String queryUser(@PathVariable(value = "userId") Integer uid){return "查询用户"+uid;//查询用户1001}@PostMapping("/user/{name}/{age}")public String insertUser(@PathVariable(value = "name") String uname,@PathVariable(value = "age") Integer uage){return "创建资源---"+"uname=="+uname+"uage=="+uage;}@PutMapping("/put/{id}/{name}")public String modifyUser(@PathVariable(value = "id") String uid,@PathVariable(value = "name") String uname){return "更新资源---"+"uid=="+uid+"uname=="+uname;}@DeleteMapping("/delete/{id}")public String deleteUser(@PathVariable(value = "id") Integer uid){return "删除资源---"+"uid=="+uid;}
}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<form action="user/aaaa/12345" method="post"><input type="submit" value="添加用户">
</form>
<form action="put/999/aaa" method="post"><input type="hidden" name="_method" value="put"><input type="submit" value="修改用户">
</form>
<form action="delete/999" method="post"><input type="hidden" name="_method" value="delete"><input type="submit" value="删除用户">
</form>
</body>
</html>
#启用支持put、delete
spring.mvc.hiddenmethod.filter.enabled=true

相关文章:

SpringBooot

目录 一、简介 1、使用原因 2、JavaConfig &#xff08;1&#xff09;Configuration注解 &#xff08;2&#xff09;Bean注解 &#xff08;3&#xff09;ImportResource注解 &#xff08;4&#xff09;PropertyResource注解 &#xff08;5&#xff09;案例 3、简介 4…...

测牛学堂:2023软件测试linux和shell脚本入门系列(shell的运算符)

shell中的注释 以# 开头的就是shell中的注释&#xff0c;不会被执行&#xff0c;是给编程的人看的。 shell中的运算符 shell中有很多运算符。 按照分类&#xff0c;可以分为算术运算符&#xff0c;关系运算符&#xff0c;布尔运算符&#xff0c;字符串运算符&#xff0c;文件…...

TensorFlow 2.0 快速入门指南:第三部分

原文&#xff1a;TensorFlow 2.0 Quick Start Guide 协议&#xff1a;CC BY-NC-SA 4.0 译者&#xff1a;飞龙 本文来自【ApacheCN 深度学习 译文集】&#xff0c;采用译后编辑&#xff08;MTPE&#xff09;流程来尽可能提升效率。 不要担心自己的形象&#xff0c;只关心如何实现…...

webpack介绍

webpack是一个静态资源打包工具 开发时&#xff0c;我们会使用框架&#xff08;Vue&#xff0c;React&#xff09;&#xff0c;ES6模块化语法&#xff0c;Less/Sass等css预处理器等语法进行开发。 这样的代码想要在浏览器运行必须经过编译成浏览器能识别的JS、CSS等语法&#x…...

SpringBoot 面试题汇总

1、spring-boot-starter-parent 有什么用 ? 我们都知道&#xff0c;新创建一个 SpringBoot 项目&#xff0c;默认都是有 parent 的&#xff0c;这个 parent 就是 spring-boot-starter-parent &#xff0c;spring-boot-starter-parent 主要有如下作用&#xff1a; 1、 定义了 J…...

已知原根多项式和寄存器初始值时求LFSR的简单例子

线性反馈移位寄存器&#xff08;LFSR&#xff09;是一种用于生成伪随机数序列的简单结构。在这里&#xff0c;我们有一个四项原根多项式 p ( x ) 1 x 0 x 2 11 0 2 p(x) 1 x 0x^2 110_2 p(x)1x0x21102​ 和初始值 S 0 100 S_0 100 S0​100。我们将使用 LFSR 动作过…...

【场景生成与削减】基于蒙特卡洛法场景生成及启发式同步回带削减风电、光伏、负荷研究(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…...

探索C/C++ main函数:成为编程高手的关键步骤

探索C/C main函数&#xff1a;成为编程高手的关键步骤&#xff08;Exploring the C/C Main Function: A Key Step to Becoming a Programming Master&#xff09; 引言&#xff08;Introduction&#xff09;main函数的基本概念&#xff08;Basic Concepts of the main function…...

【Linux】应用层协议—http

&#x1f387;Linux&#xff1a; 博客主页&#xff1a;一起去看日落吗分享博主的在Linux中学习到的知识和遇到的问题博主的能力有限&#xff0c;出现错误希望大家不吝赐教分享给大家一句我很喜欢的话&#xff1a; 看似不起波澜的日复一日&#xff0c;一定会在某一天让你看见坚持…...

七、Django进阶:第三方库Django-extensions的开发使用技巧详解(附源码)

Django-extensions是 Django 的扩展应用&#xff0c;给django开发者提供了许多便捷的扩展工具(extensions)&#xff0c;它提供了许多有用的工具和命令行工具&#xff0c;帮助 Django 开发者更高效地进行开发和调试。它的作用包括&#xff1a; - 提供了更多的Django命令&#x…...

浏览器特色状态

强缓存&#xff1a;不会向服务器发送请求&#xff0c;直接从缓存中读取资源&#xff0c;在chrome控制台的Network选项中可以看到该请求返回200的状态码&#xff0c;并且Size显示from disk cache或from memory cache。 强缓存可以通过设置两种HTTP Header实现&#xff1a;Expir…...

context 浅析

在缺少直接调用关系的两个函数之间传递数据&#xff0c;一般都会考虑使用 context&#xff0c;而 context 也被用来存储整个请求链路的公参信息&#xff0c;用户 uid、链路 traceID、特定的业务参数等。函数第一个参数类型设置为 context.Context 也是 Go 的默认写法&#xff0…...

Bandizip已管理员身份运行

系列文章目录 文章目录 系列文章目录前言一、Bandzib是什么&#xff1f;二、使用步骤1.引入库 前言 在解压krita源码包时Bandizip报错 一、Bandzib是什么&#xff1f; bandzip官网 Bandizip 是一款压缩软件&#xff0c;它支持Zip、7-Zip 和 RAR 以及其它压缩格式。它拥有非…...

LiveCharts2 初步认识

文章目录 1 LiveCharts2 是什么&#xff1f;2 LiveCharts2 可以做什么&#xff1f;3 简单使用LiveCharts2 &#xff0c;实现动态曲线图 1 LiveCharts2 是什么&#xff1f; GitHub&#xff1a;https://github.com/beto-rodriguez/LiveCharts2 官网&#xff1a; https://lvchar…...

Java设计模式 11-代理模式

代理模式 一、 代理模式(Proxy) 1、代理模式的基本介绍 代理模式&#xff1a;为一个对象提供一个替身&#xff0c;以控制对这个对象的访问。即通过代理对象访问目标对象.这样做的好处是: 可以在目标对象实现的基础上,增强额外的功能操作,即扩展目标对象的功能。被代理的对象…...

Python综合案例-小费数据集的数据分析(详细思路+源码解析)

目录 1. 请导入相应模块并获取数据。导入待处理数据tips.xls&#xff0c;并显示前5行。 2、分析数据 3.增加一列“人均消费” 4查询抽烟男性中人均消费大于5的数据 5.分析小费金额和消费总额的关系&#xff0c;小费金额与消费总额是否存在正相关关系。画图观察。 6分析男女顾…...

软件安全测试

软件安全性测试包括程序、网络、数据库安全性测试。根据系统安全指标不同测试策略也不同。 1.用户程序安全的测试要考虑问题包括&#xff1a; ① 明确区分系统中不同用户权限; ② 系统中会不会出现用户冲突; ③ 系统会不会因用户的权限的改变造成混乱; ④ 用户登陆密码是否…...

Scala模式匹配

Scala中有一个非常强大的模式匹配机制&#xff0c;应用也非常广泛, 例如: 判断固定值 类型查询 快速获取数据 简单模式匹配 一个模式匹配包含了一系列备选项&#xff0c;每个备选项都开始于关键字 case。且每个备选项都包含了一个模式及一到多个表达式。箭头符号 > 隔开…...

银行数仓分层架构

一、为什么要对数仓分层 实现好分层架构&#xff0c;有以下好处&#xff1a; 1清晰数据结构&#xff1a; 每一个数据分层都有对应的作用域&#xff0c;在使用数据的时候能更方便的定位和理解。 2数据血缘追踪&#xff1a; 提供给业务人员或下游系统的数据服务时都是目标数据&…...

Go并发编程的学习代码示例:生产者消费者模型

文章目录 前言代码仓库核心概念main.go&#xff08;有详细注释&#xff09;结果总结参考资料作者的话 前言 Go并发编程学习的简单代码示例&#xff1a;生产者消费者模型。 代码仓库 yezhening/Programming-examples: 编程实例 (github.com)Programming-examples: 编程实例 (g…...

Python爬虫实战:研究MechanicalSoup库相关技术

一、MechanicalSoup 库概述 1.1 库简介 MechanicalSoup 是一个 Python 库,专为自动化交互网站而设计。它结合了 requests 的 HTTP 请求能力和 BeautifulSoup 的 HTML 解析能力,提供了直观的 API,让我们可以像人类用户一样浏览网页、填写表单和提交请求。 1.2 主要功能特点…...

(二)TensorRT-LLM | 模型导出(v0.20.0rc3)

0. 概述 上一节 对安装和使用有个基本介绍。根据这个 issue 的描述&#xff0c;后续 TensorRT-LLM 团队可能更专注于更新和维护 pytorch backend。但 tensorrt backend 作为先前一直开发的工作&#xff0c;其中包含了大量可以学习的地方。本文主要看看它导出模型的部分&#x…...

linux 下常用变更-8

1、删除普通用户 查询用户初始UID和GIDls -l /home/ ###家目录中查看UID cat /etc/group ###此文件查看GID删除用户1.编辑文件 /etc/passwd 找到对应的行&#xff0c;YW343:x:0:0::/home/YW343:/bin/bash 2.将标红的位置修改为用户对应初始UID和GID&#xff1a; YW3…...

k8s业务程序联调工具-KtConnect

概述 原理 工具作用是建立了一个从本地到集群的单向VPN&#xff0c;根据VPN原理&#xff0c;打通两个内网必然需要借助一个公共中继节点&#xff0c;ktconnect工具巧妙的利用k8s原生的portforward能力&#xff0c;简化了建立连接的过程&#xff0c;apiserver间接起到了中继节…...

Maven 概述、安装、配置、仓库、私服详解

目录 1、Maven 概述 1.1 Maven 的定义 1.2 Maven 解决的问题 1.3 Maven 的核心特性与优势 2、Maven 安装 2.1 下载 Maven 2.2 安装配置 Maven 2.3 测试安装 2.4 修改 Maven 本地仓库的默认路径 3、Maven 配置 3.1 配置本地仓库 3.2 配置 JDK 3.3 IDEA 配置本地 Ma…...

Redis的发布订阅模式与专业的 MQ(如 Kafka, RabbitMQ)相比,优缺点是什么?适用于哪些场景?

Redis 的发布订阅&#xff08;Pub/Sub&#xff09;模式与专业的 MQ&#xff08;Message Queue&#xff09;如 Kafka、RabbitMQ 进行比较&#xff0c;核心的权衡点在于&#xff1a;简单与速度 vs. 可靠与功能。 下面我们详细展开对比。 Redis Pub/Sub 的核心特点 它是一个发后…...

Spring是如何解决Bean的循环依赖:三级缓存机制

1、什么是 Bean 的循环依赖 在 Spring框架中,Bean 的循环依赖是指多个 Bean 之间‌互相持有对方引用‌,形成闭环依赖关系的现象。 多个 Bean 的依赖关系构成环形链路,例如: 双向依赖:Bean A 依赖 Bean B,同时 Bean B 也依赖 Bean A(A↔B)。链条循环: Bean A → Bean…...

RabbitMQ入门4.1.0版本(基于java、SpringBoot操作)

RabbitMQ 一、RabbitMQ概述 RabbitMQ RabbitMQ最初由LShift和CohesiveFT于2007年开发&#xff0c;后来由Pivotal Software Inc.&#xff08;现为VMware子公司&#xff09;接管。RabbitMQ 是一个开源的消息代理和队列服务器&#xff0c;用 Erlang 语言编写。广泛应用于各种分布…...

嵌入式常见 CPU 架构

架构类型架构厂商芯片厂商典型芯片特点与应用场景PICRISC (8/16 位)MicrochipMicrochipPIC16F877A、PIC18F4550简化指令集&#xff0c;单周期执行&#xff1b;低功耗、CIP 独立外设&#xff1b;用于家电、小电机控制、安防面板等嵌入式场景8051CISC (8 位)Intel&#xff08;原始…...

协议转换利器,profinet转ethercat网关的两大派系,各有千秋

随着工业以太网的发展&#xff0c;其高效、便捷、协议开放、易于冗余等诸多优点&#xff0c;被越来越多的工业现场所采用。西门子SIMATIC S7-1200/1500系列PLC集成有Profinet接口&#xff0c;具有实时性、开放性&#xff0c;使用TCP/IP和IT标准&#xff0c;符合基于工业以太网的…...