日记小程序使用Spring Boot实现简单的后端接口--发布模块

Posted 李猫er

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了日记小程序使用Spring Boot实现简单的后端接口--发布模块相关的知识,希望对你有一定的参考价值。


心血来潮,没事的时候想写一个自己的日记小程序(也叫帖子小程序)把,主要会实现前端页面和简单的后端接口:

大概页面如下:


目前前端页面不全,等我写完在补全吧,大概就这个调了,哈哈~

这篇先实现后端接口:新建一个项目,选择Spring Initializr,项目名自定义。

实现的目录结构:

建表

CREATE TABLE `tb_post` (
  `post_id` int(10) NOT NULL AUTO_INCREMENT,
  `post_title` varchar(20) NOT NULL,
  `post_content` varchar(200) NOT NULL,
  `post_type` varchar(5) NOT NULL,
  `priority` int(10) NOT NULL,
  `create_time` datetime NOT NULL,
  `last_time` datetime NOT NULL,
  PRIMARY KEY (`post_id`)
) DEFAULT CHARSET=utf8;

pom.xml

项目需要的坐标依赖:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.liyingxia</groupId>
    <artifactId>post</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>post</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 数据库 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- 连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

应用启动入口

PostApplication:

package com.liyingxia.post;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class PostApplication {

    public static void main(String[] args) {
        SpringApplication.run(PostApplication.class, args);
        System.out.println("启动成功~");
    }

}

配置类

DataSourceConfig:

package com.liyingxia.post.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.beans.PropertyVetoException;

/**
 * @Package: com.liyingxia.post.config
 * @Description: 配置datasource到ioc容器里面
 * @Author: liyingxia
 * @CreateDate: 2021/11/15 9:42
 */

@Configuration
// 配置mybatis mapper的扫描路径
@MapperScan("com.liyingxia.post.dao")
public class DataSourceConfig {
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;

    /**
     * 生成与spring-dao.xml对应的bean dataSource
     *
     * @return
     * @throws PropertyVetoException
     */
    @Bean(name = "dataSource")
    public ComboPooledDataSource createDataSource() throws PropertyVetoException {
        // 生成datasource实例
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        // 跟配置文件一样设置以下信息
        // 驱动
        dataSource.setDriverClass(jdbcDriver);
        // 数据库连接URL
        dataSource.setJdbcUrl(jdbcUrl);
        // 设置用户名
        dataSource.setUser(jdbcUsername);
        // 设置用户密码
        dataSource.setPassword(jdbcPassword);
        // 配置c3p0连接池的私有属性
        // 连接池最大线程数
        dataSource.setMaxPoolSize(30);
        // 连接池最小线程数
        dataSource.setMinPoolSize(10);
        // 关闭连接后不自动commit
        dataSource.setAutoCommitOnClose(false);
        // 连接超时时间
        dataSource.setCheckoutTimeout(10000);
        // 连接失败重试次数
        dataSource.setAcquireRetryAttempts(2);
        return dataSource;
    }
}

SessionFactoryConfig:

package com.liyingxia.post.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Package: com.liyingxia.post.config
 * @Description:
 * @Author: liyingxia
 * @CreateDate: 2021/11/15 9:43
 */

@Configuration
public class SessionFactoryConfig {
    // mybatis-config.xml.xml配置文件的路径
    private static String mybatisConfigFile;

    @Value("${mybatis_config_file}")
    public void setMybatisConfigFile(String mybatisConfigFile) {
        SessionFactoryConfig.mybatisConfigFile = mybatisConfigFile;
    }

    // mybatis mapper文件所在路径
    private static String mapperPath;

    @Value("${mapper_path}")
    public void setMapperPath(String mapperPath) {
        SessionFactoryConfig.mapperPath = mapperPath;
    }

    // 实体类所在的package
    @Value("${type_alias_package}")
    private String typeAliasPackage;

    @Autowired
    private DataSource dataSource;

    /**
     * 创建sqlSessionFactoryBean 实例 并且设置configtion 设置mapper 映射路径 设置datasource数据源
     *
     * @return
     * @throws IOException
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置mybatis configuration 扫描路径
        sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(mybatisConfigFile));
        // 添加mapper 扫描路径
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPath;
        sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        // 设置dataSource
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 设置typeAlias 包扫描路径
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasPackage);
        return sqlSessionFactoryBean;
    }
}

TransactionManagermentConfig:

package com.liyingxia.post.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

import javax.sql.DataSource;

/**
 * @Package: com.liyingxia.post.config
 * @Description: 对标spring-service里面的transactionManager,继承TransactionManagementConfigurer是因为开启annotation-driven
 * @Author: liyingxia
 * @CreateDate: 2021/11/15 9:47
 */

@Configuration
/**
 * 使用:
 * 1. 首先使用注解 @EnableTransactionManagement 开启事务支持后
 * 2. 在Service方法上添加注解 @Transactional 即可
 */
@EnableTransactionManagement
public class TransactionManagementConfig implements TransactionManagementConfigurer {

    @Autowired
    // 注入DataSourceConfiguration里边的dataSource,通过createDataSource()获取
    private DataSource dataSource;

    @Override
    /**
     * 关于事务管理,需要返回PlatformTransactionManager的实现
     */
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

controller

PostController:

package com.liyingxia.post.controller;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.liyingxia.post.entity.Post;
import com.liyingxia.post.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.liyingxia.post.controller
 * @Description:
 * @Author: liyingxia
 * @CreateDate: 2021/11/15 9:57
 */

@RestController
@RequestMapping("/manager")
public class PostController {

    @Autowired
    private PostService postService;

    /**
     * 获取所有列表信息
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    private Map<String,Object> listPost() {
        Map<String,Object> map = new HashMap<String, Object>();
        List<Post> list = new ArrayList<Post>();
        // 获取帖子列表
        list = postService.getPostList();
        map.put("postList",list);
        return map;
    }


    /**
     * 根据id 查询对应的列表
     * @param postId
     * @return
     */
    @RequestMapping(value = "/postId", method = RequestMethod.GET)
    private Map<String,Object> getPostId(Integer postId) {
        Map<String,Object> map = new HashMap<String,Object>();
        // 获取帖子信息
        Post post = postService.getPostById(postId);
        map.put("post",post);
        return map;
    }

    /**
     * 新增帖子
     * @param post
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @RequestMapping(value = "/addPost", method = RequestMethod.POST)
    private Map<String,Object> addPost(@RequestBody Post post) throws JsonParseException,JsonMappingException,IOException {
        Map<String,Object> map = new HashMap<String,Object>();
        // 添加贴子信息
        map.put("success",postService.addPost(post));
        return map;

    }


    /**
     * 修改帖子
     * @param post
     * @return
     * @throws JsonMappingException
     * @throws JsonParseException
     * @throws IOException
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    private Map<String,Object> modifyPost(@RequestBody Post post) throws JsonMappingException,JsonParseException,IOException {
        Map<String,Object> map = new HashMap<String,Object>();
        // 修改贴子信息
        map.Spring Boot系列JSR-303基于由Hibernate-Validitor实现的后端服务器数据校验

spring boot+jpa+mysql实现简单的登录注册

spring boot+jpa+mysql实现简单的登录注册

微信小程序后端Java接口开发

微信小程序云开发 | 微信小程序与Spring Boot整合开发

怎样用php开发微信小程序的后端?