Spring
1、初识spring
2、IOC控制反转
1、概述
2、IOC入门案例
3、DI入门案例
4、Bean的基础配置
3、Bean的实例化
1、bean实例化的四种方式
最推荐
2、Bean的生命周期
3、依赖注入
1、setter注入
2、构造器注入(不推荐)
3、自动装配
4、集合注入
4、案例:数据源对象管理
5、加载properties文件
加载多个properties文件
4、容器
5、注解开发bean
1、定义bean
2、定义spring核心配置文件
3、依赖注入(只能自动装配)
注:此处名称是bean的名称
在核心配置类中增加如下注解@PropertySource,可以读取对应配置文件的内容
例如:
通过${ key }可以读取配置文件对应key的值,从而实现动态修改值。例如:
4、第三方bean管理
通过@Bean注解实现,有两种写法
1·、直接写在核心配置类中(不推荐)
2、自定义类通过方法实现
3、把自定义第三方bean导入项目(两种方法)
5、第三方bean依赖注入
1、简单数据类型
例如:
2、引用数据类型
例如:
6、总结
6、整合mybatis和junit
//TODO待补充
7、AOP
1、概述
2、入门案例
3、AOP切入点表达式
4、AOP通知类型
8、事务
注:事务管理器常写在jdbcConfig中,写在别的地方也行,有Bean注解。
例如:
例如:
SpringMVC
1、简介和入门案例
1、简介
2、入门案例
代码实现:(四步走)
1、导入依赖
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
2、创建controller类
package com.itheima.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(){
System.out.println("save ... ");
return "{'info':'springMVC save'}";
}
@RequestMapping("/delete")
@ResponseBody
public String delete(){
System.out.println("delete ... ");
return "{'info':'delete'}";
}
}
3、创建SpringMvcConfig类
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.itheima.controller")
public class SpringMvcConfig {
}
4、创建Container容器类
package com.itheima.config;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;
public class ServletContianerConfig extends AbstractDispatcherServletInitializer {
//加载springMVC容器(为了启动tomcat的时候扫描SpringMvcConfig类)
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext ctx =new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
//设置哪些请求归属springMVC处理("/"为所有)
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载spring容器(暂时不设置)
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
5、浏览器显示
3、部分注解详解
4、一加N(配置不用记)
5、配置详解
1、AnnotationConfigWebApplicationContext类及三个需要继承的方法
6、入门案例工作流程
7、bean扫描范围管理
2、get和post请求
1、get/post 请求 通过 url 向后端传参
直接在方法中定义参数即可接收(默认参数名要和传入的参数名一样)
2、解决post中文乱码
在Container容器类中,重写 getServletFilters 方法(固定写法)
3、五种参数接收方式
4、json格式参数接收(四步)
@EnableWebMvc注解
5、时间日期类型参数(可能需要@EnableWebMvc注解)
@DateTimeFormat注解
3、REST
简化:
4、解决无法访问静态资源的问题
1、自定义一个类继承WebMvcConfigurationSupport类并重写addResourceHandlers方法
2、在ComponentScan注解中添加自定义类的包,让服务器启动后扫描到自定义类
3、浏览器就可以访问静态资源了
SSM整合
1、整和步骤
1、创建webapp项目
2、导入依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
3、创建项目目录结构
4、完善项目类
1、SpringConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration //声明为配置类
@ComponentScan({"com.itheima.service"}) //扫描管理的bean
@PropertySource("classpath:jdbc.properties") //加载配置文件
@Import({JdbcConfig.class, MyBatisConfig.class}) //导入类到spring容器
@EnableTransactionManagement //开启事务
public class SpringConfig {
}
2、SpringMvcConfig
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration //声明为配置类
@ComponentScan("com.itheima.controller") //扫描管理得方法
@EnableWebMvc //开启json自动转为实体类等
public class SpringMvcConfig {
}
3、SpringMvcSupport类
package com.itheima.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) {
registry.addResourceHandler("/page/*").addResourceLocations("/page/");
}
}
4、servlet容器
package com.itheima.config;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class ServletContainerconfig extends AbstractAnnotationConfigDispatcherServletInitializer {
//指定SpringConfig类
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//指定SpringMvcConfig类
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//指定spring管理拦截路径(一般为所有路径)
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
5、jdbc配置文件(jdbc.properties)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_test
jdbc.username=root
jdbc.password=134679
6、JdbcConfig类
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class JdbcConfig {
//通过注解获取配置文件中的值
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//DataSource得Bean,用来指定数据库信息
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
//事务管理的Bean
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}
7、MyBatisConfig
package com.itheima.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class MyBatisConfig {
//同SqlSessionFactory,指定实体类路径,即对应数据库字段类型得类
@Bean
public SqlSessionFactoryBean sessionFactoryBean(DataSource dataSource) {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setTypeAliasesPackage("com.itheima.domain");
return sqlSessionFactoryBean;
}
//映射Bean,同mapper。指定映射接口路径,即mybatis操作数据库得接口
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.itheima.dao");
return scannerConfigurer;
}
}
8、创建实体类(domain包下)
package com.itheima.domain;
public class Book {
private Integer id;
private String type;
private String name;
private String description;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", type='" + type + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
9、创建mybatis查询结构(dao包下)
package com.itheima.dao;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface BookDao {
@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
public void save(Book book);
@Delete("delete from tbl_book where id = #{id}")
public void delete(Integer id);
@Update("update tbl_book set type = #{type},name=#{name},description=#{description} where id = #{id}")
public void update(Book book);
@Select("select * from tbl_book where id = #{id}")
public Book selectById(Integer id);
@Select("select * from tbl_book")
public List<Book> selectAll();
}
10、service类
接口
package com.itheima.service;
import com.itheima.domain.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional //开启事务
public interface BookService {
public boolean save(Book book);
public boolean delete(Integer id);
public boolean update(Book book);
public Book selectById(Integer id);
public List<Book> selectAll();
}
实现类
package com.itheima.service.Impl;
import com.itheima.dao.BookDao;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
bookDao.save(book);
return true;
}
public boolean delete(Integer id) {
bookDao.delete(id);
return true;
}
public boolean update(Book book) {
bookDao.update(book);
return true;
}
public Book selectById(Integer id) {
Book book = bookDao.selectById(id);
return book;
}
public List<Book> selectAll() {
List<Book> books = bookDao.selectAll();
return books;
}
}
11、controller层
package com.itheima.controller;
import com.itheima.domain.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books") //RESTFUL风格
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}
@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@GetMapping("/{id}")
public Book selectById(@PathVariable Integer id) {
Book book = bookService.selectById(id);
return book;
}
@GetMapping
public List<Book> selectAll() {
List<Book> books = bookService.selectAll();
return books;
}
}
12、引入tomcat,即可启动服务,整合完毕!!!
社区版需要下载tomcat插件
2、拦截器
代码实现
方法一:(推荐)
1、编写一个类实现 HandlerInterceptor 接口并重写所有方法(别忘了加注解)
package com.itheima.controller.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ProjectInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true; //此处返回ture即放行,返回false拦截。可自定义规则。
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
2、在SpringMvcSupport 中添加重写 addInterceptors 方法
package com.itheima.config;
import com.itheima.controller.interceptor.ProjectInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.xml.ws.Action;
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
//新增,自动注入自定义得interceptor对象
@Autowired
private ProjectInterceptor interceptor;
//以前放行静态资源的代码
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/page/*").addResourceLocations("/page/");
}
//新增,指定拦截的路径
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(interceptor).addPathPatterns("/books","/books/*");
}
}
3、在 SpringMvcConfig 配置类中添加扫描到以上两个类
添加注解即可
@ComponentScan({"com.itheima.controller","com.itheima.config"})