1.基础配置
它是一个默认添加了许多依赖,完成了许多(公共)默认的配置,集成了主流的Spring+SpringMVC的框架。
1. 创建项目
- 打开网址 http://start.spring.io;
- 填写参数,选择额外依赖,点击Generate Project按钮
- 下载项目压缩包
- 解压压缩包并剪切到eclipse项目目录中
- eclipse中导入项目:Import> Existing Maven Projects,并自动下载依赖;
2. maven配置
自动添加
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32<!--SpringBoot默认:配置MVC或Mybatis时会被替换-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!--SpringBoot默认:junit下列框架默认都有-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mysql/jdbc驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--SpringMVC:替换Spring-starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!--Mybatis:替换Spring-starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
3. 默认配置
推荐把静态资源(html/图片/css/js素材)放到resources/static文件夹中
java文件夹中默认创建了
cn.tedu.groupiD名.项目名
包,Spring专属包;并在该包创建项目名Application.java文件
,该类时启动类项目内置独立Tomcat,并且不用部署,使用时直接执行启动类就行,直接访问http://localhost:8080/
默认配置了DispatcherServlet,处理路径是/*,后缀无(任意都行)
默认配置了StringHtppMessageConverter,字符集UTF-8
默认添加了jackson依赖,boot推荐服务器这样做,利于多客户端使用:@RestController=@ResponseBody+@Controller
2. 项目规范
在java文件中创建包
包名 存储类型 controller controller entity 实体类 mapper 接口类 util 工具类(返回类/实体类的一种) interceptor 拦截器 conf 拦截器String类 在resource文件中创建目录
目录名 存储类型 mappers 接口配置文件
4.JUnit
基础配置[不推荐]:
此处建议直接复制生成的测试文件,就不用了设置了
调用Spring文件
1
(SpringRunner.class);
其他
1
自动装配对象
无需new就可以自动声明
1
2
UserMapper mapper;报错解决
步骤文件中
@AutoWired
错误或@MapperScan
出错,导致找不到接口类;1
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.tedu.store.mapper.UserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Mapper.xml中
id
或者namespace
属性出错,导致查找不到接口类的方法1
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): cn.tedu.store.mapper.UserMapper.insert
Mapper.xml中
@param
定义的和引用的数量不一样导致数组下标越界1
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter '#modifiedUser' not found. Available parameters are [modifiedTime, modifiedUser, param3, aid, param1, param2]
1
Caused by: java.sql.SQLException: Parameter index out of range (1 > number o)
mapper.xml中sql语句字段名出错
一大坨
1
2
3org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: Unknown column '错误字段名' in 'field list'<!--错误的字段名-->
### The error may exist in file [D:\tts9\workspace\store\target\classes\mappers\UserMapper.xml]<!--错误文件所在系统位置-->mapper.xml中sql语句出错
一大坨
1
2
3org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1<!--错误的位置-->
### The error may exist in file [D:\eclipse_workspace\store09\target\classes\mappers\AddressMapper.xml]<!--错误文件在系统中的位置-->Mapper.java中方法出错
1
Caused by: java.lang.ClassNotFoundException: Cannot find class:
实体类中的某个属性错误
1
Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'phone' in 'class cn.tedu.store.entity.User'
junit报错,报错台无信息
测试类包名出错或者忘记写@Test
5.连接数据库
添加依赖
此时不添加数据源启动就会失败
1
2
3
4
5
6
7
8
9
10
11<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>配置数据源
配置resources下的application.properties文件
1
2
3jdbc:mysql://localhost:3306/tedu_ums?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai =
root =
root =Junn测试
用junit运行测试文件
在配置完数据源后,自动在test文件件中创建
项目名ApplicationTest.java
文件主要用于检测依赖是否正常,正常的话不报错
自行测试
复制java文件
test
1
2
3
4
DataSource datesource;
Connection conn = dataSource.getConnection();
syse(conn);
6.使用MyBatis
调用mapper.xml
acclication.properties
1
classpath:mappers/*.xml =
创建实体类
- 可用于MyBatis的数据库使用
- 可用于AJAX做返回值使用
1
2
3
4
5
6
7
8public class User {
private String username;
private String password;
private Integer age;
private String phone;
private String email;
创建get/set/toString方法
}扫描接口类
在接口类配置[不推荐,每一个都要配置]
1
2
3
public interface UserMapper {
}启动类配置
1
2
3"cn.tedu.boot.demo.mapper[,包2]")//要扫描的包,类似spring.xml (
public class DemoApplication{
}
- 配置SQL语句
使用注解[不推荐,不利于维护]
1
2(SQL语句)
Integer insert(User user);使用XML
跟MyBatis配置方式相同,在resources下新建mapper.xml文件
mapper.xml
1
2
3
4
5<mapper namespace="cn.tedu.boot.demo.mapper.UserMapper">
<insert id="insert"
useGeneratedKeys="true" keyProperty="id"> INSERT INTO t_user (username,password,age,phone,email,is_delete)VALUES(#{username},#{password},#{age},#{phone},#{email},#{isDelete})
</insert>
</mapper>测试
1
2
3
4
5
6
7
8
9
10
public void insert(){
UserMapper mapper;
User user = new User();
user.setUsername("springboot");
user.setPassword("8888");
Integer rows = mapper.insert(user);
System.err.println("rows"+rows);
}
7.拦截器
新建拦截器类
指定拦截的规则:不符合规则的拦截,并转发到指定位置
1
2
3
4
5
6
7
8
9public class LoginInterceptor implements HandlerInterceptor {//1.实现HandlerInterceptor类
//2.生成preHandle方法
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
if(uid==null){
return false;
}
return true;
}
}新建配置类
白名单和黑名单都可以传入List类型
1
2
3
4
5
6
7
8
9
10
11
12public class A implements WebMvcConfigurer{//1.实现WebMvcConfigurer类
//2.实现addIntercdptors方法
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor=new LoginInterceptor();//新建拦截器类对象
registry.addInterceptor(interceptor)
.addPathPatterns("/**")//白名单
.excludePathPatterns(patterns);//黑名单
/* InterceptorRegistration x = registry.addInterceptor(interceptor);
x.addPathPatterns(patterns);
x.excludePathPatterns(patterns);*/
}
}
8.实例流程
下面配置建立在上面配置完数据库的情况下
创建实体类
见上文
使用MyBatis--创建实体类
创建接口
UserMapper.java
1
2
3public interface UserMapper(){
User findByUsername(String username);
}创建返回类(工具类)
ResponseResult.java
1
2
3
4
5
6private Integer state;
private String message;
生成get/set/toString方法
生成无参构造器:防止框架找不到无参构造器报错
生成有参数构造器:用于做返回类使用;
生成只有state的有参构造器:值返回一个值时使用(灵活性,建议使用)创建Mapper文件
UserMapper.xml
1
2
3
4
5<mapper>
<select resultType="cn.tedu.boot.demo.entity.User">
SELECT id FROM t_user WHERE username = #{username}
</select>
</mapper>修改Application.properties
见上文
使用MyBatis
创建登录网页
reg.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38<form>
<h1>用户注册</h1>
<div>请输入用户名</div>
<div><input name="username"></div>
<div><span id="username-hint"></span></div>
<div>请输入密码</div>
<div><input name="password"></div>
<div><span id="password-hint"></span></div>
<div>请输入年龄</div>
<div><input name="age"></div>
<div>请输入手机号码</div>
<div><input name="phone"></div>
<div>请输入电子邮箱</div>
<div><input name="email"></div>
<div><input id="btn-reg" type="button" value="注册"></div>
</form>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$("btn-reg").click(function(){
$("#username-hint").html("");//防止第二次校验失效
$("#password-hint").html("");
$ajax({
"url":"user/reg",
"data":$("#from-reg").serialize(),
"type":"post",
"dataType":"json",
"success":function(json){
if(json.state==1){
alert("注册成功");
}else if(json.state==2){
$("#username-hint").html(json.message);
}else{//此处无需设置
$("#password-hint").html(json.message);
}
}
})
})
</script>创建controller
Controller.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15//设置ajax:相当于不返回给处理器;而返回给发送数据的html文件
"user") (
public class UserController{
//自动装配接口类,MVC不需要调用Spring文件
private UserMapper userMapper
"reg") (
public String reg(User user){//传入了一个User,前面都没有类似操作,可以直接传入数据
User user = userMapper.finByUsername();
if(user == null){//测试是要注册的用户名是否已存在
return new ResponseResult(1);//只有state的构造器
}else{
return new ResponseResult(2),"用户名已经被占用";
}
}
}直接访问127.0.0.1:8080即可
最后更新: 2019年11月06日 11:36