Springboot搭建教程

本文主要记录我使用 idea 搭建 springboot 项目时小功能配置

欢迎访问我的博客

My Blog: https://coderblue.cn/
Github:https://github.com/CoderBleu
My Project:https://coderblue.cn/project/

连接数据库

连接 Mysql 数据库

<dependency>
  <groupId>mysqlgroupId>
  <artifactId>mysql-connector-javaartifactId>
  <scope>runtimescope>
dependency>

连接 Oracle 数据库

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-jdbcartifactId>
dependency>
<dependency>
    <groupId>com.oracle.ojdbcgroupId>
    <artifactId>ojdbc8artifactId>
    <scope>runtimescope>
dependency>

<dependency>
    <groupId>cn.easyprojectgroupId>
    <artifactId>orai18nartifactId>
    <version>12.1.0.2.0version>
dependency>

数据源配置


<dependency>
    <groupId>com.alibabagroupId>
    <artifactId>druidartifactId>
    <version>1.1.20version>
dependency>

yml 文件配置


spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mall_vue?serverTimezone=GMT%2b8
    username: root
    password: 密码


spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: oracle.jdbc.driver.OracleDriver
    url: jdbc:oracle:thin:@127.0.0.1:1521:orcl
    username: scott
    password: 密码

pom 文件


<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>2.1.0version>
dependency>

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-devtoolsartifactId>
    <scope>runtimescope>
    <optional>trueoptional>
dependency>

<dependency>
    <groupId>org.projectlombokgroupId>
    <artifactId>lombokartifactId>
    <optional>trueoptional>
dependency>

<dependency>
    <groupId>org.apache.logging.log4jgroupId>
    <artifactId>log4j-slf4j-implartifactId>
    <version>2.13.1version>
    <scope>testscope>
dependency>

启动类上 的配置

@SpringBootApplication
@MapperScan("cn.blue.mall.mapper")
public class MallApplication {

    public static void main(String[] args) {
        SpringApplication.run(MallApplication.class, args);
    }

}

Controller 上的配置

@Controller
@RequestMapping("/users")
public class UserInfoController {
  @Resource
  private UserInfoService userInfoService;
}

Sevice 上的配置

/**
 * @author Blue
 * @date 2020/3/5
 **/
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;

}

mapper 上的配置



<mapper namespace="cn.blue.mall.mapper.UserInfoMapper">
    <resultMap id="userInfoMapper" type="cn.blue.mall.bean.UserInfo">
        <id column="ID" property="id"/>
        <result column="NAME" property="name"/>
        <result column="EMAIL" property="email"/>
        <result column="PASSWORD" property="password"/>
        <result column="STATUS" property="status"/>
        <result column="TELEPHONE" property="telephone"/>
        
        <association property="roles" column="ROLE" javaType="cn.blue.mall.bean.Roles"
        select="cn.blue.mall.mapper.RolesMapper.findSetRoleByRoleId"/>
    resultMap>

    <sql id="Base_Column">ID ,NAME, PASSWORD, EMAIL, TELEPHONE, ROLE, STATUSsql>

    <sql id="Base_Where">
        <where>
            <if test="id != null and id != ''">
                AND ID=#{id}
            if>
            <if test="name != null and name != ''">
                AND NAME like concat(concat('%',#{name}),'%')
            if>
            <if test="email != null and email != ''">
                AND EMAIL=#{email}
            if>
            <if test="telephone != null and telephone != ''">
                AND TELEPHONE=#{telephone}
            if>
            <if test="role != null">
                AND ROLE=#{role}
            if>
            <if test="status != null">
                AND STATUS=#{status}
            if>
        where>
    sql>

    <sql id="Base_Update">
        <set>
            <if test="name != null and name != ''">
                NAME=#{name},
            if>
            <if test="telephone != null and telephone != ''">
                TELEPHONE=#{telephone},
            if>
            <if test="email != null and email != ''">
                EMAIL=#{email},
            if>
            <if test="password != null and password != ''">
                PASSWORD=#{password},
            if>
            <if test="role != null">
                ROLE=#{role},
            if>
            <if test="status != null">
                STATUS=#{status},
            if>
        set>
    sql>

    <select id="findAll" parameterType="cn.blue.mall.bean.UserInfo"
            resultMap="userInfoMapper">
        SELECT
        <include refid="Base_Column"/>
        FROM mall_users
        <include refid="Base_Where"/>
    select>

    <update id="updateStatusById" parameterType="cn.blue.mall.bean.UserInfo">
        UPDATE MALL_USERS
        SET status = #{userInfo.status}
        WHERE id=#{userInfo.id}
    update>

    <insert id="addUser" parameterType="cn.blue.mall.bean.UserInfo" keyProperty="id" keyColumn="id"
            useGeneratedKeys="true">
        INSERT INTO MALL_USERS(ID, NAME, PASSWORD, EMAIL, TELEPHONE)
        VALUES (#{id}, #{name}, #{password}, #{email}, #{telephone})
    insert>

    <delete id="deleteById" parameterType="string">
        DELETE FROM MALL_USERS
        WHERE ID = #{id}
    delete>
mapper>

PageHelper 分页

<dependency>
    <groupId>com.github.pagehelpergroupId>
    <artifactId>pagehelper-spring-boot-starterartifactId>
    <version>1.2.12version>
dependency>

代码示例: 前端分页,实现只需要将对应的参数传过来即可。

/**
  * @param pageNum 当前页码
  * @param pageSize 当前每页数据量
  */
@GetMapping
    @ResponseBody
    public Result findAll(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize,
            UserInfo user) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserInfo> list = userInfoService.findAll(null);
        PageInfo<UserInfo> pageInfo = new PageInfo<>(list);
        Result r = Result.success();
        r.add("total", pageInfo.getTotal());
        r.add("data", list);
        r.setMsg("查询成功");
        return r;
    }

SpringBoot 的 yml 文件配置

server:
  port: 80

logging:
  level:
    cn.blue: trace
    #优先级从高至低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE

# layui模板里的时间格式配置
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm
    time-zone: "GMT+8"
---
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/rbac?serverTimezone=GMT%2b8
    username: root
    password:

  # 开发阶段关闭thymeleaf的模板缓存
  thymeleaf:
    cache: false

mybatis:
  # 在eclipse可以这么配置
  # mapper-locations: classpath:cn/blue/mapper/sqlmap/*.xml
  # 在idea中mapper文件应该放在resources文件下
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

  #  配置别名扫描的包
  type-aliases-package: com.hm.publicraise.bean

#  头像存储位置
head-img-path: classpath:/static/upload/heads

#  头像存储位置
raise-img-path: classpath:/static/upload/raises

#  富文本编辑器
ue:
  server-url: /ueditor/jsp/controller

ueditor 富文本编辑器

  1. yml 文件配置
#  富文本编辑器
ue:
  server-url: /ueditor/jsp/controller
  1. 依赖导入
>
>cn.jasonone.ueditor>
>ueditor-spring-boot-starter>
>1.1.4>
>
  1. 导入 ueditor
<script type="text/plain" id="editor" name="sonContent"></script>

Invalid bound statement(not found),访问不到 mapper.xml

解决方法

application 配置文件中 mybatis 配置

mybatis:
  mapper-locations: classpath:/mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true

代码正确,无法访问 controller 层方法

其他包都得放在启动类包下

拦截器

登录拦截器

1.LoginController 主要代码

/**
  * 登录方法
  */
@PostMapping
public String login(UserInfo userInfo, HttpSession session) {
    try {
        UserInfo user = userInfoService.findOneUser(userInfo);
        if (user != null) {
            //存放引用常量的位置:ApplicationConst
            session.setAttribute(ApplicationConst.LOGIN_SESSION_STATUS, user);
            return "index";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //重定向回去会调用controller,但是请求转发只会访问目录下的资源文件
    return "redirect:/login";
}

2.LoginHandlerInterceptor 登录拦截器

@Component
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserInfo user = (UserInfo) session.getAttribute(ApplicationConst.LOGIN_SESSION_STATUS);
        if (user != null) {
            //放行
            return true;
        } else {
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }
    }
}

3.配置 WebMvcConfigurer 拦截器,将登录拦截器添加进去

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                //拦截所有
                .addPathPatterns("/**")
                //排除资源文件和登录、注销请求
                .excludePathPatterns("/login", "/logout")
                .excludePathPatterns("/layui/**", "/**/*.js")
                .excludePathPatterns("/**/*.jpg", "/**/*.png");
    }
}

你可能感兴趣的:(SpringBoot)