ok了家人们,今天我们继续 studying springMvc,let‘me see see
四.SSM整合
SpringMVC | Spring | MyBatis |
WebConfig | SpringConfig | MybatisConfig |
SpringMvcSupport | jdbc.properties |
表现层 | 业务层 | 持久层 |
EmpController | EmpService | EmpMapper |
EmpServiceImp |
- 创建Maven工程,添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.cjx</groupId><artifactId>SpringMvc_04</artifactId><version>1.0-SNAPSHOT</version><!-- web项目打包方式是war--><packaging>war</packaging><dependencies><!--springMVC--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.2.10.RELEASE</version></dependency><!-- spring的事务管理 --><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><!-- mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version></dependency><!-- spring整合mybatis --><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>8.0.25</version></dependency><!-- <dependency>--><!-- <groupId>mysql</groupId>--><!-- <artifactId>mysql-connector-java</artifactId>--><!-- <version>5.1.47</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><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version><scope>provided</scope></dependency></dependencies><build><plugins><!--Tomcat插件 --><plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><version>2.2</version><configuration><port>8080</port><!--访问端口号 --><path>/</path><!--项目访问路径--><uriEncoding>UTF-8</uriEncoding></configuration></plugin></plugins></build></project>
- 创建数据库和表
CREATE TABLE t_emp(
emp_id INT primary key AUTO_INCREMENT,
emp_name CHAR(100),
emp_salary DOUBLE(10,5)
);
INSERT INTO t_emp(emp_name,emp_salary)
VALUES("张三",200.33);
INSERT INTO t_emp(emp_name,emp_salary)
VALUES("李四",200.44);
INSERT INTO t_emp(emp_name,emp_salary)
VALUES("王五",200.55);
- db.properties属性文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
- JdbcConfig配置类
package com.cjx.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 driverName;@Value("${jdbc.url}")private String url;@Value("${jdbc.username}")private String username;@Value("${jdbc.password}")private String password;// spring管理第三方的bean 使用方法的返回值交给spring管理@Beanpublic DataSource dataSource(){DruidDataSource dataSource=new DruidDataSource();//数据源需要数据库的连接信息dataSource.setDriverClassName(driverName);dataSource.setUrl(url);dataSource.setUsername(username);dataSource.setPassword(password);return dataSource;}//Spring事务管理需要的平台事务管理器对象@Beanpublic PlatformTransactionManager platformTransactionManager(DataSource dataSource){DataSourceTransactionManager ds=new DataSourceTransactionManager();ds.setDataSource(dataSource);return ds;}
}
- MybatisConfig配置类
package com.cjx.config;import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;import javax.sql.DataSource;public class MyBatisConfig {//把mybatis交给spring管理@Beanpublic SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();ssfb.setDataSource(dataSource);ssfb.setTypeAliasesPackage("com.cjx.pojo");return ssfb;}//扫描mapper文件 生成mapper代理对象@Beanpublic MapperScannerConfigurer mapperScannerConfigurer(){MapperScannerConfigurer msc=new MapperScannerConfigurer();msc.setBasePackage("com.cjx.mapper");return msc;}
}
- SpringConfig配置类
package com.cjx.config;import org.springframework.context.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.EnableTransactionManagement;@Configuration
@ComponentScan(value = "com.cjx",excludeFilters=@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = Controller.class) )
@PropertySource("classpath:db.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement //开启Spring事务管理
public class SpringConfig {
}
- SpringMvcConfig配置类
package com.cjx.config;import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration
@ComponentScan({"com.cjx.controller","com.cjx.config"})
@EnableWebMvc //开启springmvc注解支持
public class SpringMvcConfig {
}
- WebConfig配置类,加载SpringMvcConfig和SpringConfig配置类
package com.cjx.config;import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractDispatcherServletInitializer;import javax.servlet.Filter;public class WebConfig extends AbstractDispatcherServletInitializer {//加载springmvc的配置类@Overrideprotected WebApplicationContext createServletApplicationContext() {AnnotationConfigWebApplicationContext webApplicationContext= new AnnotationConfigWebApplicationContext();webApplicationContext.register(SpringMvcConfig.class);return webApplicationContext;}//拦截所有的请求@Overrideprotected String[] getServletMappings() {return new String[]{"/"};}//加载spring的配置类@Overrideprotected WebApplicationContext createRootApplicationContext() {AnnotationConfigWebApplicationContext rootApplicationContext=new AnnotationConfigWebApplicationContext();rootApplicationContext.register(SpringConfig.class);return rootApplicationContext;}//解决post中文乱码@Overrideprotected Filter[] getServletFilters() {CharacterEncodingFilter encodingFilter=new CharacterEncodingFilter();encodingFilter.setEncoding("utf-8");return new Filter[]{encodingFilter};}
}
- 静态资源放行
package com.cjx.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 {@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {//当访问/pages/xxxx时候,从/pages目录下查找内容//http://loclahost:8080/js/axios-0.18.0.jsregistry.addResourceHandler("/pages/**").addResourceLocations("/pages/");registry.addResourceHandler("/js/**").addResourceLocations("/js/");registry.addResourceHandler("/css/**").addResourceLocations("/css/");registry.addResourceHandler("/img/**").addResourceLocations("/img/");registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");}
}
- 创建实体类对象
package com.cjx.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {private Integer empId;private String empName;private Double empSalary;
}
package com.cjx.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;@Data
@NoArgsConstructor
@AllArgsConstructorpublic class Result {private int code;//响应状态码private String msg;//响应消息private Object data;//响应数据
}
- 持久层
package com.cjx.mapper;import com.cjx.pojo.Emp;
import org.apache.ibatis.annotations.*;import java.util.List;public interface EmpMapper {//根据id查找员工信息@Select("select emp_id empId,emp_name empName,emp_salary empSalary from t_emp where emp_id = #{empId}")public Emp findById(Integer empId);//查询所有员工信息@Select("select emp_id empId,emp_name empName,emp_salary empSalary from t_emp")public List<Emp> findAll();//根据id修改员工信息@Update("update t_emp set emp_name=#{empName},emp_salary=#{empSalary} where emp_id=#{empId}")public Integer updateById(@Param("empName") String empName,@Param("empSalary") Double empSalary,@Param("empId") Integer empId);//根据id删除员工信息@Delete("delete from t_emp where emp_id=#{empId}")public Integer deleteById(Integer empId);//添加一条数据@Insert("insert into t_emp values(null,#{empName},#{empSalary})")public Integer insertEmp(@Param("empName") String empName,@Param("empSalary") Double empSalary);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cjx.mapper.EmpMapper">
<!-- <select id="findById" resultType="Emp">-->
<!-- select emp_id empId,emp_name empName,emp_Salary empSalary from t_emp where emp_id=#{empId}-->
<!-- </select>-->
</mapper>
以上两种都可以,一个是注释,一个是xml文件
记得建包的时候(在resource文件中要用 com/cjx/mapper)
- 业务层
package com.cjx.service;import com.cjx.pojo.Emp;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;import java.util.List;public interface EmpService {Emp findEmpById(Integer empId);public List<Emp> findAllEmp();//根据id修改员工信息public Integer updateEmpById(String empName,Double empSalary,Integer empId);//根据id删除员工信息public Integer deleteEmpById(Integer empId);//添加一条数据public Integer insertEmp(String empName,Double empSalary);
}
package com.cjx.service.Impl;import com.cjx.mapper.EmpMapper;
import com.cjx.pojo.Emp;
import com.cjx.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Service
@Transactional
public class EmpServiceImpl implements EmpService {@Autowiredprivate EmpMapper empMapper;@Overridepublic Emp findEmpById(Integer empId) {return empMapper.findById(empId);}@Overridepublic List<Emp> findAllEmp() {return empMapper.findAll();}@Overridepublic Integer updateEmpById(String empName,Double empSalary,Integer empId) {return empMapper.updateById(empName, empSalary,empId);}@Overridepublic Integer deleteEmpById(Integer empId) {return empMapper.deleteById(empId);}@Overridepublic Integer insertEmp(String empName,Double empSalary) {return empMapper.insertEmp(empName,empSalary);}
}
- 表现层
package com.cjx.controller;import com.cjx.pojo.Emp;
import com.cjx.pojo.Result;
import com.cjx.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;@Controller
@RequestMapping("/emp")
public class EmpController {@Autowiredprivate EmpService empService;@RequestMapping("/findById")@ResponseBodypublic Result findById(Integer empId){Emp emp = empService.findEmpById(empId);System.out.println(emp);Result result = new Result(20000,"查询成功",emp);return result;}@RequestMapping("/findAll")@ResponseBodypublic Result findAll(){List<Emp> empList = empService.findAllEmp();Result result = new Result(20000,"查询成功",empList);return result;}@RequestMapping("/updateById")@ResponseBodypublic Result updateById(Integer empId,String empName,Double empSalary){Integer row = empService.updateEmpById(empName,empSalary,empId);Result result = new Result(20000,"查询成功",row);return result;}@RequestMapping("/deleteById")@ResponseBodypublic Result deleteById(Integer empId){Integer row = empService.deleteEmpById(empId);Result result = new Result(20000,"查询成功",row);return result;}@RequestMapping("/insertEmp")@ResponseBodypublic Result insertEmp(String EmpName,Double empSalary){Integer row = empService.insertEmp(EmpName, empSalary);Result result = new Result(20000,"查询成功",row);return result;}
}
- 页面
<%--Created by IntelliJ IDEA.User: AdministratorDate: 2024/11/1Time: 11:09To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title>
</head>
<body><input type="button" value="根据Id查询员工信息" onclick="fn01()"/><script src="/js/axios-0.18.0.js"></script><script>function fn01() {axios.get("http://localhost:8080/emp/findById?empId=1").then(function(response){console.log(response.data)});}</script><input type="button" value="查询所有员工信息" onclick="fn02()"/><script src="/js/axios-0.18.0.js"></script><script>function fn02() {axios.get("http://localhost:8080/emp/findAll").then(function(response){console.log(response.data)});}</script><input type="button" value="根据Id修改员工信息" onclick="fn03()"/><script src="/js/axios-0.18.0.js"></script><script>function fn03() {axios.get("http://localhost:8080/emp/updateById?empName=zxs&empSalary=88.88&empId=2 ").then(function(response){console.log(response.data)});}</script><input type="button" value="根据Id删除员工信息" onclick="fn04()"/><script src="/js/axios-0.18.0.js"></script><script>function fn04() {axios.get("http://localhost:8080/emp/deleteById?empId=61").then(function(response){console.log(response.data)});}</script><input type="button" value="添加员工信息" onclick="fn05()"/><script src="/js/axios-0.18.0.js"></script><script>function fn05() {axios.get("http://localhost:8080/emp/insertEmp?empName=james&empSalary=88.88").then(function(response){console.log(response.data)});}</script>
</body>
</html>
五.SpringMVC的统一异常处理
5.1 统一异常处理概述
系统中异常包括两类:编译时异常和运行时异常RuntimeException ,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。系统的 DAO 、 Service 出现都通过 throws Exception 向上抛出。所有的异常均抛出到表现层进行处理。表现层处理异常,每个方法中单独书写,代码书写量巨大且意义不强,使用 AOP思想进行解决。
5.2 项目异常处理代码实现
package com.cjx.exception;import com.cjx.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice
public class ProjectException{@ExceptionHandler(Exception.class)public Result doException(Exception e){Result result = new Result(20000,"页面走丢了",null);return result;}}
5.3 自定义异常处理
package com.cjx.exception;public class GlobalNullException extends RuntimeException{public GlobalNullException() {}public GlobalNullException(String message) {super(message);}
}
package com.cjx.exception;import com.cjx.pojo.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice
public class ProjectException{@ExceptionHandler(Exception.class)public Result doException(Exception e){Result result = new Result(20000,"页面走丢了",null);return result;}@ExceptionHandler(GlobalNullException.class)public Result doGlobalNullException(GlobalNullException e){Result result = new Result(400001, "李xxx来处理异常了", null);return result;}
}
ok家人们明天见byebye