SSM整合——后端全过程

SSM整合——后端全过程,第1张

文章目录
  • 一、SSM整合
    • 1、创建工程
      • (1)新建模块
      • (2)导入依赖
    • 2、ssm各个模块整合
      • (1)创建包结构
      • (2)定义配置类
    • 3、功能模块
      • (1)创建表
      • (2)创建表字段对应的实体类
      • (3)编写DAO层代码
      • (4)编写Service层
      • (5)编写Controller层
    • 4、测试接口
      • (1)测试service
      • (2)测试controller
      • (3)事务处理
    • 5、表现层数据封装
      • (1)创建result类
      • (2)创建响应状态码类Code
      • (3)重写Controller方法
    • 6、异常处理
      • (1)自定义异常
      • (2)定义异常状态码
      • (3)模拟异常
      • (4)处理异常

一、SSM整合 1、创建工程 (1)新建模块


idea2021版整合maven之后,直接创建web工程就会有maven相关的文件。

第三页直接点击finish

(2)导入依赖

我用到的依赖有:

    <dependencies>

        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.27version>
        dependency>

        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.13.1version>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.1.4.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>ch.qos.logbackgroupId>
            <artifactId>logback-classicartifactId>
            <version>1.2.3version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.4.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
            <version>3.0.15.RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>c3p0groupId>
            <artifactId>c3p0artifactId>
            <version>0.9.1.2version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.2.8version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.14.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.1.14.RELEASEversion>
        dependency>


        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.5version>
        dependency>


        <dependency>
            <groupId>com.github.pengglegroupId>
            <artifactId>kaptchaartifactId>
            <version>2.3.2version>
        dependency>

        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.1version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-apiartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.junit.jupitergroupId>
            <artifactId>junit-jupiter-engineartifactId>
            <version>${junit.version}version>
            <scope>testscope>
        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,"出现异常,请重试!");
    }
}

测试结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/732816.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存