使用idea搭建springboot项目(html模板引擎、整合mybatis、异常处理、config注释、pageInfo分页实现)
一、新建web项目
然后就创建出来了!
导入jar包
<?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.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn</groupId>
<artifactId>boot_jsp3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot_jsp3</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--mybatis的启动jar-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--oracle驱动jar-->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc10</artifactId>
<version>11.2.0.2.0</version>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!--分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--fork:设置True,否则可能devtools不会起作用-->
<fork>true</fork>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<!--Mybatis自动生成映射文件、实体类、Mapper接口 插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<phase>deploy</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- generator 工具配置文件的位置 -->
<configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc10</artifactId>
<version>11.2.0.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>
其中自动生成pojo和mapper待会会说
新建目录结构
配置application.yaml
- application-dev.yaml:
server:
port: 8889
servlet:
#项目名
context-path: /boot_jsp3
spring:
devtools:
restart:
enabled: true
thymeleaf:
#前缀
prefix: classpath:/templates/
#后缀
suffix: .html
#文件类型 用非严格的 HTML
mode: LEGACYHTML5
# 编码
encoding: UTF-8
# 缓存
cache: false
datasource:
url: jdbc:oracle:thin:@localhost:1521:orcl1
driver-class-name: oracle.jdbc.driver.OracleDriver
username: c##ebuy
password: www123
tomcat:
max-active: 20
max-wait: 60000
min-idle: 2
initial-size: 1
redis:
cluster:
nodes: 127.0.0.1,127.0.0.2,127.0.0.3
mybatis:
mapper-locations: cn/boot_jsp3/mapper/*.xml
logging:
level:
cn.boot_mybatis: debug
至此项目大致构建完成
二、自动生成pojo和mapper层
其中
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--执行generator插件生成文件的命令: call mvn mybatis-generator:generate -e -->
<!-- 引入配置文件 -->
<properties
resource="mybatis-generator/mybatisGeneratorinit.properties" />
<!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
<!--<classPathEntry location="D:\generator_mybatis\mysql-connector-java-5.1.24-bin.jar"
/> -->
<!-- 一个数据库一个context -->
<!--defaultModelType="flat" 大数据字段,不分表 -->
<context id="MysqlTables" targetRuntime="MyBatis3Simple"
defaultModelType="flat">
<!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表; 一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
<property name="autoDelimitKeywords" value="true" />
<!-- 生成的Java文件的编码 -->
<property name="javaFileEncoding" value="utf-8" />
<!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<!-- 格式化java代码 -->
<property name="javaFormatter"
value="org.mybatis.generator.api.dom.DefaultJavaFormatter" />
<!-- 格式化XML代码 -->
<property name="xmlFormatter"
value="org.mybatis.generator.api.dom.DefaultXmlFormatter" />
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="false" /><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc_driver}"
connectionURL="${jdbc_url}" userId="${jdbc_user}"
password="${jdbc_password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成实体类地址 -->
<javaModelGenerator
targetPackage="cn.boot_jsp3.entity"
targetProject="${project}">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 生成mapxml文件 -->
<sqlMapGenerator targetPackage="cn.boot_jsp3.mapper"
targetProject="${resources}">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成mapxml对应client,也就是接口dao -->
<javaClientGenerator
targetPackage="cn.boot_jsp3.mapper"
targetProject="${project}" type="XMLMAPPER">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
<table tableName="system_userinfo" enableCountByExample="true"
enableUpdateByExample="true" enableDeleteByExample="true"
enableSelectByExample="true" selectByExampleQueryId="true">
<property name="useActualColumnNames" value="false" />
<!-- 数据库表主键 -->
<generatedKey column="id" sqlStatement="Oracle"
identity="true" />
</table>
</context>
</generatorConfiguration>
注意:其中有几行是根据自己包名进行修改
properties文件
project=src/main/java
resources=src/main/resources
jdbc_driver =oracle.jdbc.driver.OracleDriver
jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl1
jdbc_user=c##ebuy
jdbc_password=www123
测试生成
测试成功
三、写service业务逻辑层
先往mapper层追加一个login登录业务的方法
Mapper.xml:
<select id="login" resultMap="BaseResultMap">
select USERINFO_UID, USERINFO_LOGINID, USERINFO_NAME, USERINFO_PASSWORD, USERINFO_SEX,
USERINFO_EMAIL, USERINFO_MOBILE, USERINFO_STATUS, ROLE_ID
from SYSTEM_USERINFO where USERINFO_LOGINID=#{username} and USERINFO_PASSWORD=#{password}
</select>
mapper接口:
SystemUserinfo login(@Param("username") String username,@Param("password")String password);
service层接口
package cn.boot_mybatis.service;
import cn.boot_mybatis.pojo.SystemUserinfo;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface SystemUserinfoService {
int deleteByPrimaryKey(String userinfoUid);
int insert(SystemUserinfo record);
SystemUserinfo selectByPrimaryKey(String userinfoUid);
/**
*
* @param pageNum 页码
* @param pageSize 每页的长度
* @return
*/
PageInfo<SystemUserinfo> selectAll(int pageNum, int pageSize);
int updateByPrimaryKey(SystemUserinfo record);
/**
* 登录
* @param username
* @param password
* @return
*/
SystemUserinfo login(String username, String password);
}
service实现类:
package cn.boot_mybatis.service.impl;
import cn.boot_mybatis.mapper.SystemUserinfoMapper;
import cn.boot_mybatis.pojo.SystemUserinfo;
import cn.boot_mybatis.service.SystemUserinfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class SystemUserinfoServiceImpl implements SystemUserinfoService {
@Autowired
SystemUserinfoMapper systemUserinfoMapper;
@Override
public int deleteByPrimaryKey(String userinfoUid) {
return systemUserinfoMapper.deleteByPrimaryKey(userinfoUid);
}
@Transactional(rollbackFor = Exception.class)
@Override
public int insert(SystemUserinfo record) {
return systemUserinfoMapper.insert(record);
}
@Override
public SystemUserinfo selectByPrimaryKey(String userinfoUid) {
return systemUserinfoMapper.selectByPrimaryKey(userinfoUid);
}
@Override
public PageInfo<SystemUserinfo> selectAll(int pageNum, int pageSize) {
PageInfo<SystemUserinfo> pageInfo=null;
//告诉分页组件要显示的页码,和每页显示的条数
PageHelper.startPage(pageNum,pageSize);
//查询所有纪录
List<SystemUserinfo>list=systemUserinfoMapper.selectAll();
pageInfo=new PageInfo<>(list,pageSize);
return pageInfo;
}
@Override
public int updateByPrimaryKey(SystemUserinfo record) {
return systemUserinfoMapper.updateByPrimaryKey(record);
}
@Override
public SystemUserinfo login(String username, String password) {
return systemUserinfoMapper.login(username,password);
}
}
四、写一个登录业务
首先controller
package cn.boot_jsp3.controller;
import cn.boot_jsp3.entity.SystemUserinfo;
import cn.boot_jsp3.service.SystemUserinfoService;
import cn.boot_mybatis.pojo.SystemUserinfo;
import cn.boot_mybatis.service.SystemUserinfoService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
@Controller
public class SystemUserinfoController {
@Autowired
SystemUserinfoService systemUserinfoService;
@GetMapping("/toLogin")
public String toLogin(){
System.out.println("login");
return "login";
}
@PostMapping("/doLogin")
public String doLogin(String username, String password, HttpServletRequest request){
System.out.println("doLogin");
SystemUserinfo userinfo= systemUserinfoService.login(username,password);
if (userinfo!=null){
request.setAttribute("USERS",userinfo);
return "redirect:index";
}else{
request.setAttribute("MSG","用户名或者密码错误");
return "login";
}
}
}
前端页面
登录页:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="register" class="wrap">
<div class="shadow">
<em class="corner lb"></em>
<em class="corner rt"></em>
<div class="box">
<form id="loginForm" method="post" action="doLogin" onsubmit="return checkForm(this)">
<input type="hidden" name="op" value="login">
<table>
<tr>
<td class="field">用户名:</td>
<td><input class="text" type="text" id="userName" name="username" onfocus="FocusItem(this)" onblur="CheckItem(this);" /><span></span></td>
</tr>
<tr>
<td class="field">登录密码:</td>
<td><input class="text" type="password" id="passWord" name="password" onfocus="FocusItem(this)" onblur="CheckItem(this);" /><span></span></td>
</tr>
<span th:text="${MSG}" style="color: red"></span>
<tr>
<td></td>
<td><label class="ui-green"><input type="submit" name="submit" value="立即登录" /></label>
<label>
<a href="forgetpassword.jsp" style="color: dodgerblue">忘记密码</a>
</label>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
index页面:
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<link type="text/css" rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="scripts/function.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
index
</body>
</html>
然后启动项目进行测试通过