SSM整合——后端全过程

一、SSM整合

1、创建工程

(1)新建模块

在这里插入图片描述
idea2021版整合maven之后,直接创建web工程就会有maven相关的文件。
在这里插入图片描述
第三页直接点击finish
在这里插入图片描述

(2)导入依赖

我用到的依赖有:

    <dependencies>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.27</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <!-- 日志依赖 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!--spring mvc依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.4.RELEASE</version>
        </dependency>
        <!--spring与thymeleaf整合依赖-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.15.RELEASE</version>
        </dependency>
        <!--c3p0依赖-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!-- druid依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.14.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.14.RELEASE</version>
        </dependency>


        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

<!--        验证码依赖-->
        <dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、ssm各个模块整合

(1)创建包结构

在这里插入图片描述

(2)定义配置类

  1. SpringConfig:spring配置总类
  2. MyBatisConfig:MyBatis配置总类
  3. JdbcConfig:数据库连接池配置总类
  4. WebInit:代替web.xml的配置类
  5. SpringMvcConfig:代替SpringMVC配置文件的配置类
  6. jdbc.properties:数据库连接配置信息
@Configuration
@ComponentScan({"com.cx.ssm.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
public class SpringConfig {
}

public class MyBatisConfig {
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setTypeAliasesPackage("com.cx.ssm.dto");
        return factoryBean;
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.cx.ssm.dao");
        return msc;
    }
}

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;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource =new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }
}
public class WebInit 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[]{"/"};
    }
}
@Configuration
@ComponentScan("com.cx.ssm.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
jdbc.driver= com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/fruits
jdbc.username = root
jdbc.password = 1234

3、功能模块

(1)创建表

我这里创建了两张表以及一些数据:user表用于存放用户登录注册信息,fruits表用于存放水果信息。

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE INDEX `username`(`username`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 32 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;



DROP TABLE IF EXISTS `fruits`;
CREATE TABLE `fruits`  (
  `f_id` char(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `s_id` int NOT NULL,
  `f_name` char(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `f_price` decimal(8, 2) NOT NULL,
  `quantity` int NULL DEFAULT 1000,
  PRIMARY KEY (`f_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of fruits1
-- ----------------------------
INSERT INTO `fruits` VALUES ('001', 100, '香蕉', 3.50, 1005);
INSERT INTO `fruits` VALUES ('002', 100, '苹果', 3.20, 975);
INSERT INTO `fruits` VALUES ('003', 100, '梨', 4.00, 1000);
INSERT INTO `fruits` VALUES ('004', 100, '香蕉', 3.60, 1000);
INSERT INTO `fruits` VALUES ('005', 100, '芒果', 4.90, 1000);
INSERT INTO `fruits` VALUES ('006', 100, '西瓜', 3.50, 1000);
INSERT INTO `fruits` VALUES ('007', 100, '芒果', 5.30, 1000);
INSERT INTO `fruits` VALUES ('010', 100, '西瓜', 3.02, 1000);

(2)创建表字段对应的实体类

注意生成setget方法以及toString方法。
在这里插入图片描述
在这里插入图片描述

(3)编写DAO层代码

由于我们使用MyBatis开发,所有的sql代码通过注解完成,DAO层只用写接口就行。

public interface UserDao {

    @Insert("insert into user values (null,#{username},#{password})")
    public void insertUser(User user);

    @Delete("delete from user where username = #{username} and password = #{password}")
    public void deleteUser(User user,Integer id);

    @Update("update user set username = #{username},password = #{password} where id = #{id}")
    public void updateUser(User user);

    @Select("select * from user where username = #{username} and password = #{password}")
    public User selectUser(User user);

    @Select("select * from user")
    public List<User> selectAllUser();
}

public interface FruitsDao {

    @Insert("insert into fruits values (#{f_id},#{s_id},#{f_name},#{f_price},#{quantity})")
    public void insertFruits(Fruits fruits);

    @Delete("delete from fruits where s_id = #{s_id} and f_id = #{f_id}")
    public void deleteFruits(String f_id,Integer s_id);

    @Update("update fruits set s_id = #{s_id}, f_name = #{f_name}, f_price = #{f_price}, quantity = #{quantity} where f_id = #{f_id}")
    public void updateFruits(Fruits user);

    @Select("select * from fruits where s_id = #{s_id} and f_id = #{f_id}")
    public User selectFruits(String f_id,Integer s_id);

    @Select("select * from fruits")
    public List<Fruits> selectAllFruits();
}

(4)编写Service层

接口:

public interface UserService {

    public boolean insertUser(User user);

    public boolean deleteUser(User user,Integer id);

    public boolean updateUser(User user);

    public User selectUser(User user);

    public List<User> selectAllUser();
}

public interface FruitsService {

    public boolean insertFruits(Fruits fruits);

    public boolean deleteFruits(String f_id,Integer s_id);

    public boolean updateFruits(Fruits fruits);

    public User selectFruits(String f_id, Integer s_id);

    public List<Fruits> selectAllFruits();

}

实现类:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public boolean insertUser(User user) {
        userDao.insertUser(user);
        return true;
    }

    @Override
    public boolean deleteUser(User user, Integer id) {
        userDao.deleteUser(user, id);
        return true;
    }

    @Override
    public boolean updateUser(User user) {
        userDao.updateUser(user);
        return true;
    }

    @Override
    public User selectUser(User user) {
        return userDao.selectUser(user);
    }

    @Override
    public List<User> selectAllUser() {
        return userDao.selectAllUser();
    }
}

@Service
public class FruitsServiceImpl implements FruitsService {

    @Autowired
    private FruitsDao fruitsDao;

    @Override
    public boolean insertFruits(Fruits fruits) {
        fruitsDao.insertFruits(fruits);
        return true;
    }

    @Override
    public boolean deleteFruits(String f_id, Integer s_id) {

        fruitsDao.deleteFruits(f_id, s_id);
        return true;
    }

    @Override
    public boolean updateFruits(Fruits fruits) {

        fruitsDao.updateFruits(fruits);
        return true;
    }

    @Override
    public User selectFruits(String f_id, Integer s_id) {
        return fruitsDao.selectFruits(f_id, s_id);
    }

    @Override
    public List<Fruits> selectAllFruits() {
        return fruitsDao.selectAllFruits();
    }
}

(5)编写Controller层

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public boolean insertUser(@RequestBody User user) {
        userService.insertUser(user);
        return true;
    }

    @DeleteMapping("/{id}")
    public boolean deleteUser(@RequestBody  User user, @PathVariable Integer id) {
        userService.deleteUser(user, id);
        return true;
    }

    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return true;
    }

    @GetMapping
    public User selectUser(@RequestBody User user) {
        return userService.selectUser(user);
    }

    @GetMapping
    public List<User> selectAllUser() {
        return userService.selectAllUser();
    }

}

@RestController
@RequestMapping("/fruits")
public class FruitsController {

    @Autowired
    private FruitsService fruitsService;

    @PostMapping
    public boolean insertFruits(@RequestBody Fruits fruits) {
        fruitsService.insertFruits(fruits);
        return true;
    }

    @DeleteMapping("/{f_id}/{s_id}")
    public boolean deleteFruits(@PathVariable String f_id, @PathVariable Integer s_id) {

        fruitsService.deleteFruits(f_id, s_id);
        return true;
    }

    @PutMapping
    public boolean updateFruits(@RequestBody Fruits fruits) {

        fruitsService.updateFruits(fruits);
        return true;
    }

    @GetMapping("/{f_id}/{s_id}")
    public User selectFruits(@PathVariable String f_id, @PathVariable Integer s_id) {
        return fruitsService.selectFruits(f_id, s_id);
    }

    @GetMapping
    public List<Fruits> selectAllFruits() {
        return fruitsService.selectAllFruits();
    }

}

4、测试接口

(1)测试service

1.测试添加用户

    @Test
    public void testInsertUser(){
        User user = new User();
        user.setUsername("cx");
        user.setPassword("123456");
        userService.insertUser(user);

    }

在这里插入图片描述
2.查询所有用户

    @Test
    public void testSelectAllUser(){
        List<User> users = userService.selectAllUser();
        System.out.println("1111");
        System.out.println(users);
    }

在这里插入图片描述
3.查询所有水果信息

    @Test
    public void testSelectAllFruits(){

        List<Fruits> fruits = fruitsService.selectAllFruits();
        System.out.println("111");
        System.out.println(fruits);
    }

在这里插入图片描述

(2)测试controller

查询所有用户信息
在这里插入图片描述
查询所有水果信息
在这里插入图片描述
通过s_id查询水果信息
在这里插入图片描述

(3)事务处理

1.开启注解事务驱动

在spring配置类里面加上@EnableTransactionManagement事务驱动注解

@Configuration
@ComponentScan({"com.cx.ssm.service"})
@PropertySource("classpath:jdbc.properties")
@Import({JdbcConfig.class,MyBatisConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

2.配置事务管理器

    /**
     * 配置事务管理器
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds = new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }

3.加事务
在service接口上加上注解@Transactional

5、表现层数据封装

(1)创建result类

result类主要用于前端与后端数据交互

public class Result {
    private Object data;
    private Integer code;
    private String msg;

    public Result() {
    }

    public Result(Object data) {
        this.data = data;
    }

    public Result(Object data, Integer code) {
        this.data = data;
        this.code = code;
    }

    public Result(Object data, Integer code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

(2)创建响应状态码类Code

public class Code {

    public static final Integer INSERT_OK = 20011;//添加成功
    public static final Integer DELETE_OK = 20021;//删除成功
    public static final Integer UPDATE_OK = 20031;//修改成功
    public static final Integer SELECT_OK = 20041;//查询成功

    public static final Integer INSERT_ERR = 20010;//添加失败
    public static final Integer DELETE_ERR = 20020;//删除失败
    public static final Integer UPDATE_ERR = 20030;//修改失败
    public static final Integer SELECT_ERR = 20040;//查询失败
}

(3)重写Controller方法

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result insertUser(@RequestBody User user) {
        boolean flag = userService.insertUser(user);
        return new Result(flag ? Code.INSERT_OK:Code.INSERT_ERR,flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@RequestBody  User user, @PathVariable Integer id) {
        boolean flag = userService.deleteUser(user, id);
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    @PutMapping
    public Result updateUser(@RequestBody User user) {
        boolean flag = userService.updateUser(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    @GetMapping("/user/select")
    public Result selectUser(@RequestBody User user) {
        User userResult =  userService.selectUser(user);
        Integer code = userResult != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = userResult != null ? "":"查询失败,请重试!";
        return new Result(code,userResult,msg);
    }

    @GetMapping
    public Result selectAllUser() {
        List<User> users = userService.selectAllUser();
        Integer code = users != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = users != null ? "":"查询失败,请重试!";
        return new Result(code,users,msg);
    }

}
@RestController
@RequestMapping("/fruits")
public class FruitsController {

    @Autowired
    private FruitsService fruitsService;

    @PostMapping
    public Result insertFruits(@RequestBody Fruits fruits) {
        boolean flag =fruitsService.insertFruits(fruits);
        return new Result(flag ? Code.INSERT_OK:Code.INSERT_ERR,flag);
    }

    @DeleteMapping("/{f_id}")
    public Result deleteFruits(@PathVariable String f_id, @PathVariable Integer s_id) {
        boolean flag =fruitsService.deleteFruits(f_id, s_id);
        return new Result(flag ? Code.INSERT_OK:Code.INSERT_ERR,flag);
    }

    @PutMapping
    public Result updateFruits(@RequestBody Fruits fruits) {
        boolean flag =fruitsService.updateFruits(fruits);
        return new Result(flag ? Code.INSERT_OK:Code.INSERT_ERR,flag);
    }

    @GetMapping("/{f_id}")
    public Result selectFruits(@PathVariable String f_id) {
        Fruits fruits = fruitsService.selectFruits(f_id);
        Integer code = fruits != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = fruits != null ? "":"查询失败,请重试!";
        return new Result(code,fruits,msg);
    }

    @GetMapping
    public Result selectAllFruits() {
        List<Fruits> fruits = fruitsService.selectAllFruits();
        Integer code = fruits != null ? Code.SELECT_OK:Code.SELECT_ERR;
        String msg = fruits != null ? "":"查询失败,请重试!";
        return new Result(code,fruits,msg);
    }

}

测试结果:
在这里插入图片描述

6、异常处理

(1)自定义异常

创建一个异常处理的包,定义异常
1.系统异常

public class SystemException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public SystemException() {
        super();
    }

    public SystemException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public SystemException(Integer code ,String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}

2.业务异常

public class BusinessException extends RuntimeException{
    private Integer code;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public BusinessException() {
        super();
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public BusinessException(Integer code , String message, Throwable cause) {
        super(message, cause);
        this.code = code;
    }
}

(2)定义异常状态码

在前面的Code类加上以下异常常量

    public static final Integer OTHER_ERR = 40001;//其它异常
    public static final Integer SYSTEM_ERR = 50001;//系统异常
    public static final Integer BUSINESS_ERR = 60001;//业务异常

(3)模拟异常

    @Override
    public Fruits selectFruits(String f_id) {
        if(f_id == "0"){
            throw new BusinessException(Code.BUSINESS_ERR,"业务异常,请重试");
        }
        try {
        	int i/0;
            Fruits fruits = fruitsDao.selectFruits(f_id);
        }catch (Exception e){
            throw new SystemException(Code.SYSTEM_ERR,"系统异常,请重试",e);
        }
        return fruitsDao.selectFruits(f_id);
    }

(4)处理异常


@RestControllerAdvice
public class ProjectExceptionAdvice {

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

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

    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        return new Result(Code.OTHER_ERR,null,"出现异常,请重试!");
    }
}

测试结果:
在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我没得冰阔落.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值