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

SpringMvc day1101

ok了家人们,今天我们继续 studying springMvc,let‘me see see

.SSM整合

SpringMVC
Spring
MyBatis
WebConfig
SpringConfigMybatisConfig
SpringMvcSupport
jdbc.properties
表现层
业务层持久层
EmpController
EmpServiceEmpMapper
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


http://www.mrgr.cn/news/63705.html

相关文章:

  • 大数据新视界 -- 大数据大厂之大数据环境下的网络安全态势感知
  • 计算机组成原理之中央处理器
  • API接口开放与安全管控 - 原理与实践
  • 【02基础】- RabbitMQ基础
  • 746.使用最小花费爬楼梯
  • 基于Multisim的单双声道音频功率放大电路设计与仿真
  • L2.【LeetCode笔记】反转链表
  • vue3项目编码时相对合理的顺序推荐仅个人记录备用
  • elementplus组件库el-menu组件中的default-active属性使用
  • Mac “屏幕保护程序启动或显示器关闭后需要密码“无效
  • AIGC生成式人工智能——泼天的富贵(三)
  • 飞机布雷盖航程公式
  • python实战项目51:selenium结合requests获取某众点评评论
  • 价值为王,浅析基础大模型行业应用创新发展新路径
  • YOLO11改进 | Neck | 有效提升小目标检测效果,附完整代码结构图【论文必备】
  • C++之多态(上)
  • 推荐一款音乐制作软件:Ableton Live Suite
  • 不可能的任务:这款浏览器竟然可以同时满足速度与隐私
  • 深入解析 Transformers 框架(三):Qwen2.5 大模型的 AutoTokenizer 技术细节
  • HJ38 求小球落地5次后所经历的路程和第5次反弹的高度
  • ArcGIS影像调色(三原色)三原色调整
  • 基于SpringBoot和PostGIS的世界各国邻国可视化实践
  • buu easyRE
  • pandas计算相关性并画热力图
  • 文件描述符fd 和 缓冲区
  • javaScript-----一维数组和数组对象去重的多种方法