SpringBoot对静态资源的映射:
(1) 要在src/main/resources文件夹下创建static和templates两个文件夹staitc存储静态资源,templates存储模板引擎
(2)要在pom.xml依赖下导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如果导入依赖失败的话 可以尝试添加版本号
示例:创建名为success的页面 并可以访问
首先在templates文件夹下创建网页
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<div th:text="${hello}"> </div>
</body>
</html>
这里的${hello}可以联想成Vue中的{{}}表达式,这里调用了控制器中的方法
然后在控制器写方法
@RequestMapping("/success")
public String hello(Model model){
model.addAttribute("hello","<h1>zhangsan</h1>");
return "success";
}
启动服务器 就可以通过端口号进行访问
Thymeleaf语法
(1)变量表达式:
变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。如下所示: ${session.user.name}
它们将以HTML标签的一个属性来表示:
<span th:text="${book.author.name}">
(2)选择表达式
选择表达式很像变量表达式,不过它们用一个预先选择的对象来代替上下文变量容器(map)来执行,如下: *{customer.name}
被指定的object由th:object属性定义:
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
(3) URL表达式
URL表达式指的是把一个有用的上下文或回话信息添加到URL,这个过程经常被叫做URL重写。不需要指定项目名字
@{/order/list}
URL还可以设置参数:
@{/order/details(id=${orderId})}
让我们看这些表达式:
<form th:action="@{/createOrder}">
<a href="main.html" rel="external nofollow" th:href="@{/main}" rel="external n
表达式支持的语法
字面(Literals)
• 文本文字(Text literals): 'one text', 'Another one!',…
• 数字文本(Number literals): 0, 34, 3.0, 12.3,…
• 布尔文本(Boolean literals): true, false
• 空(Null literal): null
• 文字标记(Literal tokens): one, sometext, main,…
文本操作(Text operations)
• 字符串连接(String concatenation): +
• 文本替换(Literal substitutions): |The name is ${name}|
算术运算(Arithmetic operations)
• 二元运算符(Binary operators): +, -, *, /, %
• 减号(单目运算符)Minus sign (unary operator): -
布尔操作(Boolean operations)
• 二元运算符(Binary operators):and, or
• 布尔否定(一元运算符)Boolean negation (unary operator):!, not
比较和等价(Comparisons and equality)
• 比较(Comparators): >, <, >=, <= (gt, lt, ge, le)
• 等值运算符(Equality operators):==, != (eq, ne)
条件运算符(Conditional operators)
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
常用的thymeleaf标签
视图控制器:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.addViewController("/header").setViewName("header");
registry.addViewController("/index").setViewName("index");
registry.addViewController("/menu").setViewName("menu");
registry.addViewController("/add").setViewName("add");
registry.addViewController("/update").setViewName("update");
registry.addViewController("/test").setViewName("test");
}
拦截器
方法
package com.qcby.DruidConfig;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("前置拦截");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("后置拦截");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("最终拦截");
}
}
注册
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/hello2");
}
编写Servlet类:
@Bean
public ServletRegistrationBean myServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new
MyServlet(),"/myServlet");
return registrationBean;
}
编写测试类
package com.qcby.Controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
super.doGet(httpServletRequest,httpServletResponse);
System.out.println("get方法执行了");
}
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
super.doPost(httpServletRequest,httpServletResponse);
System.out.println("Post方法执行了");
}
}
网页编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/myServlet" method="post">
<input type="text"></br>
<input type="submit" value="提交">
</form>
</body>
</html>
输出结果
说明配置Servlet方法调用成功
编写Filter
@Bean
public FilterRegistrationBean myFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.setUrlPatterns(Arrays.asList("/hello","/test"));
return registrationBean;
}
@Bean中 要求对/hello /test路径的进行过滤
package com.qcby.Controller;
import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("处理中");
}
@Override
public void destroy() {
System.out.println("过滤器结束了");
}
}
监听器
@Bean
public ServletListenerRegistrationBean myListener(){
ServletListenerRegistrationBean<MyListener> registrationBean = new
ServletListenerRegistrationBean<>(new MyListener());
return registrationBean;
}
package com.qcby.Controller;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("监听器初始化成功");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("监听器摧毁");
}
}
SpringBoot数据层开发
需要导入的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
在application.yaml中配置数据库的驱动 用户名 密码
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/boot_demo
driver-class-name: com.mysql.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
配置druid数据库的话
导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
</dependency>
同上在yaml中配置数据库的基本信息
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/boot_demo
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
创建数据源注册类(可以写在启动类上 不要放在MvcConfig类中,也可以单独写一个配置类)
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource(){
return new DruidDataSource();
}
}