【Java】SSM入门开发流程总结

1.1 SSM整合流程
  1. 创建工程
  2. SSM整合
    • Spring
      • SpringConfig
    • MyBatis
      • MybatisConfig
      • JdbcConfig
      • jdbc.properties
    • SpringMVC
      • ServletConfig
      • SpringMvcConfig
  3. 功能模块
    • 表与实体类
    • dao(接口+自动代理)
    • service(接口+实现类)
      • 业务层接口测试(整合JUnit)
    • controller
      • 表现层接口测试(PostMan)
SpringConfig

对于Spring需要配置SpringConfig,需要配置的内容如下:

  • 设置为配置类:@Configuration
  • 扫描Bean的路径:@ComponentScan
  • 是否导入其他类,并加载其Bean:@Import
  • 导入其他类的配置项:@PropertySource(“classpath:XXXXXX”)
MybatisConfig

对于Mybatis需要配置MybatisConfig、JdbConfig以及引入Jdbc.properties数据库配置文件。

1.JdbcConfig:

  • 用@Value加载数据库连接信息,比如driver、username、password、url
  • 设置DataSource类,把信息载入jdbc
public DataSource dataSouce(){
	DruidDataSource dataSource = new DruidDataSource();
	dataSource.setDriverClassName(driver);
	dataSource.setUrl(url);
	dataSource.setUsername(username);
	dataSource.setPassword(password);
	return dataSource;
}
  • 判断是否要添加事务管理器
public  PlateformTransactionManager plateformtransactionManager(DataSource dataSource){
	DataSourceTransactionManager ds=new DataSourceTransactionManager();
	ds.setDataSource(datasource);
	return ds;
}

2.MybatisConfig

  • 设置工厂Bean用于创建数据库会话:SqlSessionFactoryBean
@Bean
public SqlSessionFactoryBean sqlsessionFactoryBean(DataSource dataSource){
	SqlsessionFactoryBean factory = new SqlsessionFactoryBean();
	factory.setDataSource(datasource);
	return factory;
}
  • 配置映射器:MapperScannerConfigurer
public MapperScannerConfigurer mapperScannerConfigurer(){
	MapperScannerConfigurer msc = new MapperScannerConfigurer();
	msc.setBasePackage("Hayaizo.dao");
	return msc;
}
SpringMVCConfig

SpringMVC需要配置SpringMVCConfig、ServletConfig

1.SpringMVCConfig

  • 设置为配置类:@Configuration
  • 设置Bean的扫描路径:@ComponentScan
  • 启动Spring MVC框架:@EnableWebMvc
  • 开启事务管理:@EnableTransationManagement

2.ServletConfig

  • 设置为配置类:@Configuration
  • 继承AbstractAnnotationConfigDispatcherServletInitilizer并实现方法
package Hayaizo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;

@Configuration
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

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

    //配置过滤器,处理中文乱码问题
    protected Filter[] getServletFilters(){
        CharacterEncodingFilter filter=new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}
Controller层
  • Restful控制器:@RestController
  • 浏览器中访问资源路径:@RequestMapping(“/books”)
  • 自动装配:@Autowired
  • @PostMapping:处理HTTP POST请求的路径映射
    • @RequestParam:获取请求参数的值,不一定要填写参数
    • @PathVariable:获取URL路径中的变量值,一定要写参数
    • @RequestBody:用于接收Post请求体中的数据,可以把前端的json数据转换为对象
    • @RequestParam:用于接收Get请求URL上的参数
@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {
        boolean flag=bookService.save(book);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean flag=bookService.update(book);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag=bookService.delete(id);
        return new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book=bookService.selectById(id);
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null? "":"数据查询失败";
        return new Result(code,book,msg);
    }
    @GetMapping
    public Result selectAll() {
        List<Book> book=bookService.selectAll();
        Integer code=book!=null?Code.GET_OK:Code.GET_ERR;
        String msg=book!=null? "":"数据查询失败";
        return new Result(code,book,msg);
    }
}
SpringMvc中的异常处理

常用的注解:@RestControllerAdvice、@ExceptionHandler

@RestControllerAdvice:用于标识当前类为REST风格对应的异常处理器

@ExceptionHandler:标识用于处理哪种异常

@RestControllerAdvice
public class ProjectExceptionAdvice {
    //@ExceptionHandler用于设置当前处理器类对应的异常类型
    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public Result doBusinessException(BusinessException ex){
        return new Result(ex.getCode(),null,ex.getMessage());
    }

    //除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
    @ExceptionHandler(Exception.class)
    public Result doOtherException(Exception ex){
        //记录日志
        //发送消息给运维
        //发送邮件给开发人员,ex对象发送给开发人员
        return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
    }
}
给静态资源放行
  • 在SpringMvcSupport类中,此类继承于WebMvcConfigurationSupport
  • 实现方法addResourceHandlers
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport{
    private ProjectInterceptor interceptor;
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).addPathPatterns("/books","/books/*");
    }
}
interceptor拦截器
  • 在controller接口层添加一个interceptor的包
  • 创建一个拦截器的类ProjectorInterceptor
  • ProjectorInterceptor实现HandlerInterceptor接口的方法
@Component
public class ProjectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
  • 在SpringMvcSupport中添加上拦截器
  • addInterceptor,通过registry来注册拦截器
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport{
    private ProjectInterceptor interceptor;
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(interceptor).addPathPatterns("/books","/books/*");
    }
}

你可能感兴趣的:(Java,java,开发语言)