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

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管理
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        //数据源需要数据库的连接信息
        dataSource.setDriverClassName(driverName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
    //Spring事务管理需要的平台事务管理器对象
    @Bean
    public 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管理
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean ssfb=new SqlSessionFactoryBean();
        ssfb.setDataSource(dataSource);
        ssfb.setTypeAliasesPackage("com.cjx.pojo");
        return ssfb;
    }

    //扫描mapper文件 生成mapper代理对象
    @Bean
    public 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的配置类
    @Override
    protected WebApplicationContext createServletApplicationContext() {
        AnnotationConfigWebApplicationContext webApplicationContext
                = new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(SpringMvcConfig.class);
        return webApplicationContext;
    }
    //拦截所有的请求
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
    //加载spring的配置类
    @Override
    protected WebApplicationContext createRootApplicationContext() {
        AnnotationConfigWebApplicationContext rootApplicationContext
                =new AnnotationConfigWebApplicationContext();
        rootApplicationContext.register(SpringConfig.class);
        return rootApplicationContext;
    }

    //解决post中文乱码

    @Override
    protected 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 {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当访问/pages/xxxx时候,从/pages目录下查找内容
        //http://loclahost:8080/js/axios-0.18.0.js
        registry.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
@AllArgsConstructor

public 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 mapper
        PUBLIC "-//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 {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public Emp findEmpById(Integer empId) {
        return  empMapper.findById(empId);
    }

    @Override
    public List<Emp> findAllEmp() {
        return empMapper.findAll();
    }

    @Override
    public Integer updateEmpById(String empName,Double empSalary,Integer empId) {
        return empMapper.updateById(empName, empSalary,empId);
    }

    @Override
    public Integer deleteEmpById(Integer empId) {
        return empMapper.deleteById(empId);
    }

    @Override
    public 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 {

    @Autowired
    private EmpService empService;

    @RequestMapping("/findById")
    @ResponseBody
    public Result findById(Integer empId){
        Emp emp = empService.findEmpById(empId);
        System.out.println(emp);
        Result result = new Result(20000,"查询成功",emp);

        return result;
    }

    @RequestMapping("/findAll")
    @ResponseBody
    public Result findAll(){
        List<Emp> empList = empService.findAllEmp();
        Result result = new Result(20000,"查询成功",empList);

        return result;
    }

    @RequestMapping("/updateById")
    @ResponseBody
    public 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")
    @ResponseBody
    public Result deleteById(Integer empId){
        Integer row = empService.deleteEmpById(empId);
        Result result = new Result(20000,"查询成功",row);

        return result;
    }

    @RequestMapping("/insertEmp")
    @ResponseBody
    public 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: Administrator
  Date: 2024/11/1
  Time: 11:09
  To 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.kler.cn/a/383273.html

相关文章:

  • Debian 12 安装配置 fail2ban 保护 SSH 访问
  • Java基础面试题19:解释什么是Servlet链
  • 0.96寸OLED显示屏详解
  • Mybatis分页插件的使用问题记录
  • javaEE--计算机是如何工作的-1
  • 解析在OceanBase创建分区的常见问题|OceanBase 用户问题精粹
  • 基于布局的3D场景生成技术:SceneCraft
  • 美创科技以韧性数据安全防护体系助力畜牧业数字化发展
  • 计算机专业开题报告写法,该怎么写好?
  • 头歌——机器学习(线性回归)
  • NewStarCTF2024-Week5-WebMisc-WP
  • yolov8涨点系列之轻量化主干网络替换
  • Android中的跨进程通信方案总结一-AIDL运行原理
  • 机器学习—构建一个神经网络
  • 新能源汽车的未来:车载电源与V2G技术的前景
  • 音箱与功放功率解析
  • 第11章 LAMP架构企业实战
  • 深度学习:Transformer Decoder详解
  • 导师双选系统设计与实现:Spring Boot框架优势
  • 厘清红黑层
  • el-date-picker 设置开始时间和结束时间
  • 数据库基础(6) . DDL
  • 数据管理的四大支柱:揭秘数据中台、数据仓库、数据治理和主数据
  • 2025生物发酵展(济南)为生物制造产业注入新活力共谱行业新篇章
  • 2-142【软件无线电原理与应用作业】基于matlab的圆形阵列的波束形成进行仿真
  • Flutter鸿蒙next 中的 Expanded 和 Flexible 使用技巧详解