Springboot-MyBatis配置-配置端口号与服务路径(idea社区版2023.1.4+apache-maven-3.9.3-bin)

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: Springboot-MyBatis配置-配置端口号与服务路径(idea社区版2023.1.4+apache-maven-3.9.3-bin)


MyBatis的Maven包

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- 热部署 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    <!-- Web支持 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- JDBC -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- MySQL驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- 集成MyBatis -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.1.2</version>
    </dependency>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- 测试 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

引入后别忘记刷新Maven。

application.properties配置文件位置

添加以下内容:

# 配置数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置数据库url
spring.datasource.url=jdbc:mysql://rm-bp1zq3879r28p726lco.mysql.rds.aliyuncs.com:3306/test?characterEncoding=utf8
# 配置数据库用户名
spring.datasource.username=qwe8403000
# 配置数据库密码
spring.datasource.password=Qwe8403000
# 指定MyBatis配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
# 指定模型位置
mybatis.typeAliasesPackage=com.item.model
# 修改端口号避免冲突
server.port=8088
# 服务路径
server.servlet.context-path=/MyAPI

项目结构层次

编码过程

按照上图给的顺序一次创建文件并写入给与的示例代码,数据库里面有表,可以直接放心使用。

1、model/Users.java

package com.item.model;
 
public class Users {
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getUserName() {
        return userName;
    }
 
    public void setUserName(String userName) {
        this.userName = userName;
    }
 
    public String getPwd() {
        return pwd;
    }
 
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
 
    public String getNickName() {
        return nickName;
    }
 
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
 
    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", pwd='" + pwd + '\'' +
                ", nickName='" + nickName + '\'' +
                '}';
    }
 
    private int id;
    private String userName;
    private String pwd;
    private String nickName;
 
}

2、dao/UsersMapper.java

package com.item.dao;
 
import com.item.model.Users;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
 
import java.util.List;
/**
 * 数据访问组件
 */
@Repository
public interface UsersMapper {
    List<Users> GetInfo();
    List<Users> SelectName(@Param("nickName") String nickName);
    Users UsersSelectById(@Param("id") int id);
    int UsersAddInfo(
            @Param("userName") String userName,
            @Param("pwd") String pwd,
            @Param("nickName") String nickName
    );
    int UsersUpdateInfo(
            @Param("pwd") String pwd,
            @Param("id") int id
    );
    int UsersDeleteById(@Param("id") int id);
}

3、resources/mapper/UsersMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.item.dao.UsersMapper">
    <!-- 用作基础查询测试 -->
    <select id="GetInfo" resultType="Users">
        select * from users
    </select>
    <!-- 用做传递参数测试·支持空查询,返回所有信息 -->
    <select id="SelectName" resultType="Users">
        select * from users where nickName like "%${nickName}%"
    </select>
    <!-- id精准查询 -->
    <select id="UsersSelectById" resultType="Users">
        select * from users where id=#{id}
    </select>
    <!-- 增加 -->
    <insert id="UsersAddInfo">
        insert into users values(0,"${userName}","${pwd}","${nickName}");
    </insert>
    <!-- 修改 -->
    <update id="UsersUpdateInfo">
        update users set pwd="${pwd}" where id=#{id}
    </update>
    <!-- 删除 -->
    <delete id="UsersDeleteById">
        delete from users where id=#{id}
    </delete>
</mapper>

4、service/UsersService.java

package com.item.service;
 
import com.item.model.Users;
 
import java.util.List;
 
public interface UsersService {
    /**
     * 获取所有
     * @return
     */
    List<Users> GetInfo();
 
    /**
     * 获取nickName的模糊查询结果集
     * @param nickName
     * @return
     */
    List<Users> SelectName(String nickName);
 
    /**
     * id精准查询
     * @param id
     * @return
     */
    Users UsersSelectById(int id);
 
    /**
     * 添加信息
     * @param userName
     * @param pwd
     * @param nickName
     * @return
     */
    int UsersAddInfo(
            String userName,
            String pwd,
            String nickName
    );
 
    /**
     * 修改密码
     * @param pwd
     * @param id
     * @return
     */
    int UsersUpdateInfo(
            String pwd,
            int id
    );
 
    /**
     * 删除信息
     * @param id
     * @return
     */
    int UsersDeleteById(int id);
}

5、serviceimpl/UsersServiceImpl.java

package com.item.serviceimpl;
 
import com.item.dao.UsersMapper;
import com.item.model.Users;
import com.item.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
 
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
 
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersMapper usersMapper;
 
    @Override
    public List<Users> GetInfo() {
        return usersMapper.GetInfo();
    }
 
    @Override
    public List<Users> SelectName(String nickName) {
        return usersMapper.SelectName(nickName);
    }
 
    @Override
    public Users UsersSelectById(int id) {
        return usersMapper.UsersSelectById(id);
    }
 
    @Override
    public int UsersAddInfo(String userName, String pwd, String nickName) {
        pwd=encrypt(pwd);
        return usersMapper.UsersAddInfo(userName, pwd, nickName);
    }
 
    @Override
    public int UsersUpdateInfo(String pwd, int id) {
        pwd=encrypt(pwd);
        return usersMapper.UsersUpdateInfo(pwd, id);
    }
 
    /**
     * MD5加密
     * @param password
     * @return
     */
    private String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(password.getBytes("utf-8"));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }
 
    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
 
    @Override
    public int UsersDeleteById(int id) {
        return usersMapper.UsersDeleteById(id);
    }
}

6、controller/UsersController.java

package com.item.controller;
 
import com.item.model.Users;
import com.item.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
 
@RestController
@CrossOrigin
public class UsersController {
    @Autowired
    private UsersService usersService;
 
    @GetMapping("/GetInfoApi")
    public Object GetInfoApi(){
        List<Users> list=usersService.GetInfo();
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",list);
        return map;
    }
 
    @GetMapping("/GetName")
    public Object GetName(HttpServletRequest request,Model model){
        String nickName = request.getParameter("nickName");
        List<Users> list=usersService.SelectName(nickName);
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",list);
        return map;
    }
 
    /**
     * 添加接口,访问方式post
     * @param request
     * @param model
     * @return
     */
    @PostMapping(value = "/UserAddInfoApi")
    public Object UserAddInfoApi(HttpServletRequest request,Model model){
        String userName = request.getParameter("userName");
        String pwd = request.getParameter("pwd");
        String nickName = request.getParameter("nickName");
        usersService.UsersAddInfo(userName, pwd, nickName);
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }
 
    /**
     * 单个查询
     * @param request
     * @param model
     * @return
     */
    @GetMapping("/UsersSelectById")
    public Object UsersSelectById(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        Users users = usersService.UsersSelectById(Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result",users);
        return map;
    }
 
    /**
     * 修改api
     * @param request
     * @param model
     * @return
     */
    @PostMapping(value = "/UserUpdateInfoApi")
    public Object UserUpdateInfoApi(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        String pwd = request.getParameter("pwd");
        usersService.UsersUpdateInfo(pwd,Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }
 
    /**
     * 删除api
     * @param request
     * @param model
     * @return
     */
    @GetMapping(value = "/UsersDeleteById")
    public Object UsersDeleteById(HttpServletRequest request,Model model){
        String id = request.getParameter("id");
        usersService.UsersDeleteById(Integer.parseInt(id));
        HashMap<String,Object> map=new HashMap<String,Object>();
        map.put("state",true);
        map.put("msg","成功");
        map.put("result","");
        return map;
    }
}

7、Action.java

package com.item;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@MapperScan("com.item.dao")
@SpringBootApplication
public class Action extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Action.class);
    }
    public static void main(String[] args) {
        //一定是被@SpringBootApplication标记的类
        SpringApplication.run(Action.class, args);
    }
}

启动校验

查看端口号以及路由设置

端口号以及路由的路径已经设置,根据路径进行访问。

http://localhost:8088/MyAPI/GetName

访问成功。

总结

现在我们已经搭建了服务的基础环境,可以创建跨域的接口,也可以操作数据库,那么也就代表着我们可以正常的写接口项目了,不过我们写好的接口暂时没办法直接提供给前端人员,所以我们还需要配置一个swagger或者是使用Eolink插件一键上传接口来方便与前端人员交互。

源码下载地址:https://download.csdn.net/download/feng8403000/88083495

下节我们来配置swagger。

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
13天前
|
网络协议
iptables配置tcp端口转发
iptables配置tcp端口转发
24 1
|
14天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
36 0
|
3天前
|
Java Shell 测试技术
一次配置,多场景适用:Spring Boot多套配置文件的深度剖析
一次配置,多场景适用:Spring Boot多套配置文件的深度剖析
15 0
一次配置,多场景适用:Spring Boot多套配置文件的深度剖析
|
7天前
|
Java 容器
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
SpringBoot使用配置注解开启自动配置功能&整合spring-boot-configuration-processor
11 0
|
14天前
|
Java 应用服务中间件
Springboot启动的时候初始化的线程池默认配置tomcat
Springboot启动的时候初始化的线程池默认配置tomcat
11 1
|
15天前
|
Java
SpringBoot配置图片访问404SpringBoot配置图片访问路径springboot如何访问图片
SpringBoot配置图片访问404SpringBoot配置图片访问路径springboot如何访问图片
6 0
SpringBoot中maven项目打包时出现的问题
SpringBoot中maven项目打包时出现的问题
SpringBoot中maven项目打包时出现的问题
SpringBoot中maven项目打包时出现的问题
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project demo: Fatal error compiling
SpringBoot中maven项目打包时出现的问题
|
6天前
|
Java Linux
Springboot 解决linux服务器下获取不到项目Resources下资源
Springboot 解决linux服务器下获取不到项目Resources下资源
|
14天前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
54 2

推荐镜像

更多