`
hlsps
  • 浏览: 32666 次
社区版块
存档分类
最新评论

springboot + mysql + mybatis +maven 工程测试

阅读更多

今天,用STS4.11.1(springboot tools suite 4)开发了一个基于Springboot的测试工程,项目使用了mysql, mybatis,maven技术。
首先看工程目录结构,(不能上传图片),直接上代码吧

要新建一个工程,数据库是基础, 使用mysql数据库,在mysql库上建表做数据处理,数据库建库脚本:

DROP TABLE emp_info;

CREATE TABLE emp_info(

emp_id VARCHAR(20) NOT NULL   ,

emp_name VARCHAR(20) NOT NULL   ,

emp_passwd VARCHAR(64) NOT NULL,

emp_sex VARCHAR(1) NOT NULL,

emp_brithdate VARCHAR(10),

emp_age INT,

emp_email VARCHAR(30)

);



ALTER TABLE emp_info ADD PRIMARY KEY (emp_id);

INSERT INTO emp_info VALUES('111','111','11','1','2021-12-01',1,'28329@qq.com')

 开发工具使用的是STS4.11.1,操作流程,FILE->NEW->NEW Project->Spring Starter Project,新建工程名为demo。

选择java 版本时,选择8,group 命名com.example,artifact命名:demo, package命名:com.example.demo, 工程建好之后,POM.xml配置如下 :

<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.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</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-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.2.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
		
		
		<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
	</dependencies>

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

	</build>

</project>

sprintboot 的配置文件application.properties,可修改为application.yml,本次不做修改

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/mysql
spring.datasource.username=root
spring.datasource.password=mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
## Mybatis 配置
# 实体所在包,起别名
mybatis.type-aliasesPackage:com.example.entity
# 映射文件所在路径
mybatis.mapper-locations:classpath:com.example.dao/*.xml

#端口
server.port=8080

application.properties中增加thymeleaf模板

 

spring:
  thymeleaf:
    prefix: classpath:/templates/
    mode: HTML
    cache: false
    encoding: UTF-8
    #     新版本不支持content-type: text/html,故新写法
    servlet:
      content-type: text/html
 注意:增加的thymeleaf之后 ,需要将static,templates目录拷贝至resources目录下。

 

application.properties中增加log输出

 

#日志输出
  logging:
    path: C:\Users\x_houjianjie\Documents\workspace-spring-tool-suite-4-4.11.1.RELEASE\demo\logs #日志文件路径
    file: demo.log #日志文件名称
    level: debug
    root: debug #日志级别 root表示所有包,也可以单独配置具体包 fatal error warn info debug trace off
 日志输出也可以使用logback-spring.xml文件来控制,如果配置了logback-spring.xml文件,则application.properties中的配置会失效。
logback-spring.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
   <contextName>demo</contextName>
   <!--输出到控制台-->
   <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
           <pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
           <charset>UTF-8</charset>
       </encoder>
   </appender>

   <!--按天生成日志-->
   <appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
       <Prudent>true</Prudent>
       <!-- 过滤器,只打印ERROR级别的日志 -->
       <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
           <!--日志文件输出的文件名-->
           <FileNamePattern>
               d:/log/%d{yyyy-MM-dd}/%d{yyyy-MM-dd}.log
           </FileNamePattern>
           <!--日志文件保留天数-->
           <MaxHistory>15</MaxHistory>
       </rollingPolicy>
       <layout class="ch.qos.logback.classic.PatternLayout">
           <Pattern>
               %d{yyyy-MM-dd HH:mm:ss} -%msg%n
           </Pattern>
       </layout>
   </appender>

   <logger name="com.fishpro.log" additivity="false">
       <appender-ref ref="console"/>
       <appender-ref ref="logFile"/>
   </logger>
   
   <!-- 设置Spring&Hibernate日志输出级别 -->
   <logger name="org.springframework" level="DEBUG"/>
   <logger name="org.mybatis" level="DEBUG"/> 
   <logger name="com.ibatis" level="DEBUG"/> 
   <logger name="com.ibatis.common.jdbc.SimpleDataSource" level="DEBUG"/> 
   <logger name="com.ibatis.common.jdbc.ScriptRunner" level="DEBUG"/> 
   <logger name="com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate" level="DEBUG"/>


      
   <logger name="java.sql.Connection" level="DEBUG"/>  
   <logger name="java.sql.Statement" level="DEBUG"/> 
   <logger name="java.sql.PreparedStatement" level="DEBUG"/> 
   <logger name="com.ruidou.baoqian.mapper" level="DEBUG"/>

   <!-- 开发环境下的日志配置 -->
   <root level="debug">
       <appender-ref ref="console"/>
       <appender-ref ref="logFile"/>
   </root>
</configuration>
包目录结构说明:
com.example,工程启动包,
com.example.controller,controller控制包
com.example.dao , dao接口,mapper文件
com.example.dao.imp, service业务控制
com.example.entity , bean对象定义
com.example.utils,   工具类定义
DemoApplication.java
package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@MapperScan("com.example.dao")
public class DemoApplication {

	
    @RequestMapping("/")
    public String hello(){
        return "hello springboot,mybatis,mysql,maven";
    }
    
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
 
EmpInfoController.java
package com.example.controller;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.dao.impl.EmpInfoService;
import com.example.entity.EmpInfo;
import com.example.utils.CommonUtils;
import com.example.utils.StringUtils;

@Controller
public class EmpInfoController {
	
	@Autowired
	private EmpInfoService service;
	
    @PostMapping("/EmpInfo/register")
	public String addEmpInfo(@RequestParam  Map<String, Object> map){
		
		Logger logger =LoggerFactory.getLogger(this.getClass());
		
		EmpInfo obj = new EmpInfo();
		
		obj.setEmpId(StringUtils.toSafeStr(map.get("userid")));
		obj.setEmpName(StringUtils.toSafeStr(map.get("username")));
		obj.setEmpAge(CommonUtils.toSafeInt(map.get("age")));
		obj.setEmpEmail(StringUtils.toSafeStr(map.get("email")));
		obj.setEmpBrithDate(StringUtils.toSafeStr(map.get("brithdate")));
		obj.setEmpSex(StringUtils.toSafeStr(map.get("sex")));
		
		
		String sPassword1 = StringUtils.toSafeStr(map.get("password"));
		String sPassword2 = StringUtils.toSafeStr(map.get("password1"));
		
		logger.debug("sPassword1======" + sPassword1);
		logger.debug("sPassword2======" + sPassword2);
		
		if(!sPassword1.equals(sPassword2)) {
			return "error/error";
		}
		
		obj.setEmpPasswd(sPassword1);

		service.addEmpInfo(obj);
		
		return "user/success";
	}


}
 IndexController.java
package com.example.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.dao.impl.EmpInfoService;
import com.example.entity.EmpInfo;

@Controller
public class IndexController {
	
	 @Autowired
	 private EmpInfoService empInfoService;
	 
	 private Logger logger =LoggerFactory.getLogger(this.getClass());
	
	 @RequestMapping("index")
	 public String index(){
	     return "hello";
	 }
	 
	 @RequestMapping("login")
	 public String longin(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request){
		 			 
		EmpInfo obj1 = new EmpInfo();
		obj1.setEmpId(username);
		obj1.setEmpPasswd(password);
		 
		EmpInfo obj = empInfoService.empLogin(obj1);
		
		logger.debug("obj.name="+obj.getEmpName()); 
		
		if(obj != null) 
			return "user/success";
		else 
			return "error/error";		
	 }
	 
	 @RequestMapping("register")
	 public String register(){
	     return "user/register";
	 }
	 
}
 最重要的dao和mapper文件
EmpINfoDao.java
package com.example.dao;


import org.apache.ibatis.annotations.Mapper;

import com.example.entity.EmpInfo;

@Mapper
public interface EmpInfoDao {
	
    int addEmpInfo(EmpInfo empInfo);

	
     EmpInfo empLogin(EmpInfo empInfo);


}
EmpInfoDao.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.example.dao.EmpInfoDao">

  <resultMap id="BaseResultMap"  type="com.example.entity.EmpInfo" >
    <result column="emp_id" 	property="empId" 	jdbcType="VARCHAR"/>
    <result column="emp_name" 	property="empName" 	jdbcType="VARCHAR"/>
    <result column="emp_passwd" 	property="empPasswd" 	jdbcType="VARCHAR"/>
    <result column="emp_sex" 	property="empSex" 	jdbcType="VARCHAR"/>
    <result column="emp_age" 	property="empAge" 	jdbcType="INTEGER"/>
    <result column="emp_brithdate" 	property="empBrithDate" 	jdbcType="VARCHAR"/>
    <result column="emp_email" 	property="empEmail" 	jdbcType="VARCHAR"/>
  </resultMap>
  
  <insert id="addEmpInfo"  parameterType="com.example.entity.EmpInfo">
  	insert into emp_info (emp_id, emp_name, emp_passwd, emp_age, emp_sex, emp_brithdate, emp_email)
  	values (#{empId,jdbcType=VARCHAR}, 
  	#{empName,jdbcType=VARCHAR}, 
  	#{empPasswd,jdbcType=VARCHAR}, 
  	#{empAge,jdbcType=INTEGER},
  	#{empSex,jdbcType=VARCHAR}, 
  	#{empBrithDate,jdbcType=VARCHAR},
  	#{empEmail,jdbcType=VARCHAR})
  </insert>
  
 <select id="empLogin" parameterType="com.example.entity.EmpInfo" resultMap="BaseResultMap">
 SELECT emp_id,emp_name,emp_passwd,emp_age,emp_sex,emp_brithdate,emp_email
  FROM emp_info WHERE  emp_id= #{empId} AND emp_passwd = #{empPasswd}
 </select>
  
</mapper>
 EmpInfoService.java
package com.example.dao.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.dao.EmpInfoDao;
import com.example.entity.EmpInfo;

@Service
public class EmpInfoService  {
	
	 @Autowired
	private EmpInfoDao dao;
	 
	 
	public int addEmpInfo(EmpInfo empInfo) {
		return dao.addEmpInfo(empInfo);
	}
	
	
	public EmpInfo empLogin(EmpInfo empInfo){
		
		return dao.empLogin(empInfo);
	}

}实
实体bean类。Emoinfo.java
package com.example.entity;

/**
 * @author x_houjianjie
 *
 */
public class EmpInfo {
	
	public String empId;
	public String empName;
	public String empSex;
	public String empBrithDate;
	public int    empAge;
	public String empEmail;
	public String empPasswd;
	
	
	public String getEmpId() {
		return empId;
	}
	public void setEmpId(String empId) {
		this.empId = empId;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public String getEmpBrithDate() {
		return empBrithDate;
	}
	public void setEmpBrithDate(String empBrithDate) {
		this.empBrithDate = empBrithDate;
	}
	public int getEmpAge() {
		return empAge;
	}
	public void setEmpAge(int empAge) {
		this.empAge = empAge;
	}
	public String getEmpEmail() {
		return empEmail;
	}
	public void setEmpEmail(String empEmail) {
		this.empEmail = empEmail;
	}
	public String getEmpSex() {
		return empSex;
	}
	public void setEmpSex(String empSex) {
		this.empSex = empSex;
	}
	public String getEmpPasswd() {
		return empPasswd;
	}
	public void setEmpPasswd(String empPasswd) {
		this.empPasswd = empPasswd;
	}
	
}
  工具类:CommonUtils.java
package com.example.utils;

public class CommonUtils {
	
	public final static int toSafeInt(Object obj) {
		
		return obj == null ? 0 : Integer.parseInt(String.valueOf(obj));
	}

}
 StringUtil.java
package com.example.utils;

public class StringUtils {
	
	public final static String toSafeStr(Object obj){
		
		return obj == null ? "" : String.valueOf(obj);
	}
	
	

}
 
html文件目录结构,html文件必须在resources/templates目录下,
templates目录下包含:hello.html,user和error目录, user目录下包含:register.html和success.html,error目录下包含:error.html
hello.html, 注意,hello文件中使用from-data方式提交参数,conctroller中需要用request请求接受参数,@RequestParam("username") String username, @RequestParam("password") String password
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <link rel="stylesheet" href="test.css" type="text/css" />
</head>
<body>
请输入用户名与密码登录
<form action="/login" method="post" target='_parent' >
 用户名:<input type="text" name="username" /><br>
 密&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" /><br>
 <input type="submit" value="登录" />
 <a href="/register" target='_parent'>注册</a>
</form>
</body>
</html>
 register.html页面用json方式提交参数,controller中用haspmap<string,object>来接受参数@RequestParam  Map<String, Object> map
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <link rel="stylesheet" href="test.css" type="text/css" />
</head>
<body>
    <h1>user info</h1>
    <form action="/EmpInfo/register" method="post" enctype='application/json'>
 用户ID:<input type="text" name="userid" /></br>
 用户名:<input type="text" name="username" /></br>
 密码:<input type="password" name="password" /></br>
 确认密码:<input type="password" name="password1" /></br>
 出生日期:<input type="text" name="brithdate" /></br>
 年龄:<input type="text" name="age" /></br>
 性别:<input type="text" name="sex" /></br>
 邮箱:<input type="text" name="email" /></br>
 <input type="submit" value="注册">
</form>
</body>
</html>
 error.html页面用来跳转报错页面,处理流程中的错误
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <link rel="stylesheet" href="test.css" type="text/css" />
</head>
<body>
    <h1>Error occur!</h1>
</body>
</html>
 success.html跳转成功
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Title</title>
    <link rel="stylesheet" href="test.css" type="text/css" />
</head>
<body>
    <h1>Congratulations!</h1>
</body>
</html>
 最后附上test.css
body{
    color: red;
}
 
 
 
 
 
 

 




 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics