ssm的Demo

学习了SSM 后将其整合成一个小Demo

1 结构图

ssm的Demo

; 2 config层

2.1 JdbcConfig (jdbc配置)


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;
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager ds =new DataSourceTransactionManager();
        ds.setDataSource(dataSource);
        return ds;
    }
}

2.2 MyBatisConfig (MyBatis配置)

public class MyBatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean factoryBean =new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);

        factoryBean.setTypeAliasesPackage("com.itheima.domain");
        return factoryBean;

    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer msc =new MapperScannerConfigurer();

        msc.setBasePackage("com.itheima.dao");
        return msc;
    }
}

2.3 ServiceConfig (Service 配置)

public class ServiceConfig 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[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter();
        filter.setEncoding("UTF-8");
        return new Filter[]{filter};
    }
}

2.4 SpringConfig (Spring 配置)

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

public class SpringConfig {
}

2.5 SpringMvcConfig (SpringMvc 配置)

@Configuration
@ComponentScan({"com.itheima.controller","com.itheima.config"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {

    @Autowired
    private ProjectInterceptor projectInterceptor;
    @Autowired
    private ProjectInterceptor2 projectInterceptor2;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
        registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
    }
}

2.6 SpringMvcSupport (SpringMvc拦截器)


@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {

    @Autowired
    private ProjectInterceptor projectInterceptor;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
        registry.addResourceHandler("/css/**").addResourceLocations("/css/");
        registry.addResourceHandler("/js/**").addResourceLocations("/js/");
        registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");

    }

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
    }
}

2 Controller (控制器)

2.1 interceptor (拦截器)

2.11 ProjectInterceptor 拦截器一

@Component

public class ProjectInterceptor implements HandlerInterceptor {
    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String contentType = request.getHeader("Content-Type");
        HandlerMethod hm = (HandlerMethod)handler;
        System.out.println("preHandle..."+contentType);
        return true;
    }

    @Override

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}

2.11 ProjectInterceptor2 拦截器2


@Component
public class ProjectInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("preHandle...222");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...222");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...222");
    }
}

2.2 BookController Book控制器


@RestController
@RequestMapping("books")
public class BookController {
    @Autowired
    private BookService bookService;

    @PostMapping
    public Result save(@RequestBody Book book) {

        boolean save = bookService.save(book);

        Result result = new Result(save ? Code.Save_ok : Code.Save_ERR, save);

        return result;

    }

    @PutMapping
    public Result update(@RequestBody Book book) {
        boolean update = bookService.update(book);
        Result result = new Result(update ? Code.Update_ok : Code.Update_ERR, update);
        return result;
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean delete = bookService.delete(id);
        Result result = new Result(delete ? Code.DELETE_ok : Code.DELETE_ERR, delete);
        return result;
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        Book byId = bookService.getById(id);

        Integer code = byId != null ? Code.GET_ok : Code.GET_ERR;
        String msg =byId != null ? "":"数据查询失败,请重试";
        Result result = new Result(code,byId,msg);
        return result;
    }

    @GetMapping
    public Result getAll() {
        List<Book> all = bookService.getAll();

        Integer code = all != null ? Code.GET_ok : Code.GET_ERR;
        String msg =all != null ? "":"数据查询失败,请重试";
        Result result = new Result(code,all,msg);

        return result;
    }
}

2.3 Code (自定义异常编码)


public class Code {

    public static final Integer Save_ok =20011;
    public static final Integer DELETE_ok =20021;
    public static final Integer Update_ok =20031;
    public static final Integer GET_ok =20041;

    public static final Integer Save_ERR =20010;
    public static final Integer DELETE_ERR =20020;
    public static final Integer Update_ERR =20030;
    public static final Integer GET_ERR =20040;

    public static final Integer SYSTEM_ERR =50001;

    public static final Integer System_TIMEOUT_ERR =50002;

    public static final Integer BUSINESS_ERR =6002;

}

2.4 ProjectExceptionAdvice (异常处理器)


@RestControllerAdvice
public class ProjectExceptionAdvice {

    @ExceptionHandler(SystemException.class)
    public Result doSystemException(SystemException ex){

        return new Result(ex.getCode(), null,ex.getMessage());

    }

    @ExceptionHandler(BusinessException.class)
    public Result doSystemException(BusinessException ex){

        return new Result(ex.getCode(), null,ex.getMessage());

    }

    @ExceptionHandler(Exception.class)
    public Result doException(Exception ex){
        System.out.println("抓住异常"+ex.getLocalizedMessage());

        return new Result(666, null,"出现异常了");

    }
}

2.5 Result (返回结果)


public class Result {

    public Object data;

    public Integer code;

    public String msg;

    public Result() {
    }

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

    public Result(Integer code, Object data, 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;
    }
}

3 dao (数据访问接口)

3.1 BookDao (对Book表进行操作的接口)


public interface BookDao {

    @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
    public int save(Book book);

    @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
    public int update(Book book);

    @Delete("delete from tbl_book where id = #{id}")
    public int delete(Integer id);

    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);

    @Select("select * from tbl_book")
    public List<Book> getAll();
}

4 domain(实体类)

  • domain
    在domain包下面的实体类其中的属性不仅会包含数据库中的字段,还会包含其他自定义属性

4.1 Book (Book实体类)


public class Book {
    private Integer id;
    private String type;
    private String name;
    private String description;

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", type='" + type + '\'' +
                ", name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

5 Exception (异常)

  • 异常(exception)是在运行程序时产生的一种异常情况

5.1 BusinessException(业务异常类)


public class BusinessException extends RuntimeException {

    private Integer code;

    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;
    }

    public Integer getCode() {
        return code;
    }

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

5.1 SystemException(系统异常类)


public class SystemException extends RuntimeException {

    private Integer code;

    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;
    }

    public Integer getCode() {
        return code;
    }

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

6 service (服务端)

  • 服务端 对客户提供服务的

6.1 impl (服务端实现类)

  • 接口

6.11 BookServiceImpl (book实现类)


@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    public boolean save(Book book) {
        return bookDao.save(book) > 0;
    }

    public boolean update(Book book) {
        return bookDao.update(book) > 0;

    }

    public boolean delete(Integer id) {
        return bookDao.delete(id) > 0;

    }

    public Book getById(Integer id) {

        if (id  0) {
            throw new BusinessException(Code.BUSINESS_ERR, "请输入正确Id");
        }

        try {

        } catch (Exception e) {
            throw new BusinessException(Code.SYSTEM_ERR, "服务器超时,请重试");
        }

        return bookDao.getById(id);
    }

    public List<Book> getAll() {
        return bookDao.getAll();
    }
}

6.2 BookService (book接口)

@Transactional
public interface BookService {

    public boolean save(Book book);

    public boolean update(Book book);

    public boolean delete(Integer id);

    public Book getById(Integer id);

    public List<Book> getAll();
}

7 配置类

7.1 jdbc.properties (配置文件)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://81.68.155.110/demo01
jdbc.username=demo01
jdbc.password=****

pom (项目对象模型)

<?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>org.example</groupId>
  <artifactId>SpringMvcTest_01_ssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

    <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>

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

    <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>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>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <port>80</port>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <properties>
    <maven.compiler.source>11</maven.compiler.source>
    <maven.compiler.target>11</maven.compiler.target>
  </properties>

</project>

Original: https://blog.csdn.net/Rouehang/article/details/127811090
Author: 欲与宇语
Title: ssm的Demo

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/655746/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球