<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
设置为8060端口
server:
port: 8060
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
Description:
Cannot determine embedded database driver class for database type NONE
Action:
If you want an embedded database please put a supported one on the classpath.
If you have database settings to be loaded from a particular profile you may need to
active it (no profiles are currently active).
Disconnected from the target VM, address: '127.0.0.1:49341', transport: 'socket'
Process finished with exit code 1
这是因为spring boot默认会加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration类,DataSourceAutoConfiguration类使用了@Configuration注解向spring注入了dataSource bean。因为工程中没有关于dataSource相关的配置信息,当spring创建dataSource bean因缺少相关的信息就会报错。
application.yml配置数据源
spring:
datasource:
url: jdbc:mysql://192.168.0.234:3306/tooth?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
username: root
password: root
filters: log4j,wall,mergeStat
//注解方式:
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
//配置文件配置方式:
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
@MapperScan("com.github.dge1992.ssm.dao")
mybatis:
type-aliases-package: com.github.dge1992.ssm.domain
mapper-locations: classpath:mappers/*.xml
configuration:
cache-enabled: false
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):
com.github.dge1992.ssm.dao.TestMapper.queayCat
配置的mapper-locations文件路径设置在src路径下,最好把mapper-locations设置为resource路径下
Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+,
5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance
with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly
disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
当前版本的MySQL要求使用SSL, url: jdbc:mysql://192.168.0.135:3306/test?
autoReconnect=true&useUnicode=true&characterEncoding=utf8&
zeroDateTimeBehavior=convertToNull**&useSSL=true**
logging:
level:
com.github.dge1992: debug
@EnableTransactionManagement(proxyTargetClass = true)
在方法上使用@Transactional注解即可
使用Mybatis-Plus的 通用mapper 和 自动生成代码 等功能,因为在实际项目中一些重复的, 简单sql查询 浪费着我们的时间,使用Mybatis-Plus使我们开发更加效率和便捷。
mybatis依赖
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.3.1version>
dependency>
mybatis-plus依赖
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plusartifactId>
<version>2.1.9version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatisplus-spring-boot-starterartifactId>
<version>1.0.5version>
dependency>
mybatis配置信息
mybatis:
type-aliases-package: com.github.dge1992.ssm.domain
mapper-locations: classpath:mappers/*.xml
configuration:
cache-enabled: false
log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
mybatis-plus配置信息
mybatis-plus:
mapper-locations: classpath:mappers/*.xml
typeAliasesPackage: com.github.dge1992.ssm.domain
global-config:
id-type: 0 #0:数据库ID自增 1:用户输入id 2:全局唯一id(IdWorker) 3:全局唯一ID(uuid)
db-column-underline: false
refresh-mapper: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: true #配置的缓存的全局开关
lazyLoadingEnabled: true #延时加载的开关
multipleResultSetsEnabled: true
分页插件配置
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocityartifactId>
<version>1.7version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.23version>
dependency>
太长了,不贴了,自己网上去找
基本上单表的操作都不需要在xml里写sql了
操作实体包装器 EntityWrapper
Page(int current, int size)
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
1) “File” -> “Settings” -> “Build,Execution,Deplyment” -> “Compiler”,选中打勾 “Build project automatically” 。
2) 组合键:“Shift+Ctrl+Alt+/” ,选择 “Registry” ,选中打勾 “compiler.automake.allow.when.app.running” 。
一般前端表单日历控件提交的是String类型,而我们用Date接收会报错
@DatetimeFormat是将String转换成Date
我们经常使用@ResponseBody把数据已json对象的形式返回,Date类型默认是时间戳,我们需要把Date转换成String返回
@JsonFormat(pattern=”yyyy-MM-dd HH:mm:ss”,timezone = “GMT+8”)
private MockMvc mockMvc;
@Autowired
private WebApplicationContext wac;
@Before
public void setup(){
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
//配置文件
my:
name: dong
//java代码
@Value("${my.name}")
private String myName;
我们新建一个bean类,如下:
@ConfigurationProperties(prefix = "my")
public class ConfigBean {
private String name;
private String age;
private String from;
//省略...
}
这里配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,在bean类那边添加
@SpringBootApplication
@EnableConfigurationProperties({ConfigBean.class})
public class SsmApplication {
public static void main(String[] args) {
SpringApplication.run(SsmApplication.class, args);
}
}
最后在Controller中引入ConfigBean使用即可,如下:
@RestController
public class UserController {
@Autowired
ConfigBean configBean;
@RequestMapping("/")
public String hexo(){
return configBean.getName()+configBean.getWant();
}
}
在实际开发过程中,我们会把部分开发好的模块放到服务器测试和给老板看,所以配置文件参数会改动
在java -jar (…)启动项目时可以动态切换环境
–spring.profiles.active=dev
spring boot两种方式进行多环境配置
spring:
profiles:
active: dev
2:在主配置文件 - - - 分割
---
spring:
profiles: dev
server:
port: 8081
---
spring:
profiles: pro
server:
port: 8082
在实际开发过程中,我们会向页面发送ajax格式的json格式返回数据,实现AjaxResult返回数据格式
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>
引入依赖后就在默认的模板路径==src/main/resources/templates==下编写模板文件即可完成。
通过xmlns:th=”http://www.thymeleaf.org“ 命令空间,将静态页面转换为动态的视图,需要进行动态处理的元素将使用“th:”前缀。
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>bootstrapartifactId>
<version>3.3.5version>
dependency>
<dependency>
<groupId>org.webjarsgroupId>
<artifactId>jqueryartifactId>
<version>3.1.1version>
dependency>
<script src="../webjars/jquery/3.1.1/jquery.min.js">script>
<script src="../webjars/bootstrap/3.3.5/js/bootstrap.min.js">script>
<link rel="stylesheet" href="../webjars/bootstrap/3.3.5/css/bootstrap.min.css" />
/resource/static/webjars
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
dependency>
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
dependency>
spring:
mvc:
view:
prefix: /WEB-INF/view/
suffix: .jsp
创建相应目录 webapp/WEB-INF/view,并把jsp页面放在这个目录下。
/**
* 测试使用jsp
* @return
*/
@RequestMapping("/testJsp")
public String testJsp(Model model){
List personList = personService.selectList(null);
model.addAttribute("personList", personList);
return "testJsp";
}
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en" class="no-js" >
<head>
<meta charset="utf-8" />
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>title>
<script src="../webjars/jquery/3.1.1/jquery.min.js">script>
<script src="../webjars/bootstrap/3.3.5/js/bootstrap.min.js">script>
<link rel="stylesheet" href="../webjars/bootstrap/3.3.5/css/bootstrap.min.css" />
head>
<body style="background-image: none;">
<div class="body_wrap">
<div class="container">
<table class="table table-striped table-bordered">
<c:forEach var="person" items="${personList}">
<tr class="text-info">
<td>${person.userName}td>
<td>${person.age}td>
tr>
c:forEach>
table>
div>
div>
body>
html>
启动项目,运行项目有三种方式,这里我都做过了一次测试,发现在maven中jasper依赖有加provided和注释掉该依赖范围运行的效果不大一样,具体对比如下:
有添加provided的情况:
把provided 注释掉的情况:
方法一:
1.移除对嵌入式Tomcat的依赖
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
exclusion>
exclusions>
dependency>
2.tomcat-embed-jasper中scope必须是provided
<dependency>
<groupId>org.apache.tomcat.embedgroupId>
<artifactId>tomcat-embed-jasperartifactId>
<scope>providedscope>
dependency>
方法二:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-tomcatartifactId>
<scope>providedscope>
dependency>
Spring Boot的默认配置方式,提供的静态资源映射如下:
classpath:/META-INF/resources
classpath:/resources
classpath:/static
classpath:/public
对应的配置文件配置
# 默认值为 /**
spring.mvc.static-path-pattern=
# 默认值为 classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.resources.static-locations=这里设置要指向的路径,多个使用英文逗号隔开
/**
* Web配置类
*/
@Configuration
public class WebMvcContext extends WebMvcConfigurerAdapter {
/**
* 配置静态资源访问
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/hello/**").addResourceLocations("classpath:/hello/");
super.addResourceHandlers(registry);
}
}
如果你想指定外部的目录也很简单,直接addResourceLocations指定即可:
/**
* 配置静态资源访问
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/hello/**").addResourceLocations("file:E:/hello/");
super.addResourceHandlers(registry);
}
自定义拦截器代码:
/**
* 登录拦截器
*/
public class LoginInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
boolean flag = false;
Person person = (Person) request.getSession().getAttribute("person");
if(person != null){
flag = true;
}else{
response.sendRedirect("/login/toLogin");
}
return flag;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
重写WebMvcConfigurerAdapter中的addInterceptors方法如下:
/**
* 配置自定义拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**").excludePathPatterns("/login/login", "/login/toLogin");
super.addInterceptors(registry);
}
@Configuration
public class ContainerConfig {
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new EmbeddedServletContainerCustomizer(){
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
}
};
}
}
局部异常主要用到的是@ExceptionHandler注解,此注解注解到类的方法上,当此注解里定义的异常抛出时,此方法会被执行。
如果@ExceptionHandler所在的类是@Controller,则此方法只作用在此类。
如果@ExceptionHandler所在的类带有@ControllerAdvice注解,则此方法会作用在全局。
进入Controller层的错误才会由@ControllerAdvice处理,拦截器抛出的错误以及访问错误地址的情况@ControllerAdvice处理不了,由SpringBoot默认的异常处理机制处理。
/**
* 全局的的异常拦截器
*/
@ControllerAdvice
public class BusinessExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public Object jwtException(Exception e) {
if(e instanceof ArithmeticException){
return "发生了除0异常";
}
return "发生了未定义异常";
}
}