SpringBoot相比于其他的框架,只有一个配置文件(application.properties),而且入门简单,使用方便。
SpringBoot使用步骤:
1.创建一个Controller来控制转发页面;
2.修改maven的配置文件(pron.xml),加入一些必要的插件
3.修改SpringBoot配置文件(application.properties);(包含spring、mybatis、log4j、JDBC等配置文件集合在一起)
4.编写jsp页面;
Controller代码示例:
//@Controller
@RestController // @RestController = @Controller + @ResponseBody
@RequestMapping("/user")//@RequestMapping表示必须在这个路径下才能调用,即url地址中必须包含这个路径
public class UserContoller {
@RequestMapping("/getUser")
// @ResponseBody
public User getUser() {
User u = new User();
u.setName("bob2");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("bob2");
u.setDesc("hello bob2~~");
return u;
}
@RequestMapping("/getUserJson")
// @ResponseBody
public IMoocJSONResult getUserJson() {
User u = new User();
u.setName("bob");
u.setAge(18);
u.setBirthday(new Date());
u.setPassword("bob");
u.setDesc("hello bob~~hello bob~~");
return IMoocJSONResult.ok(u);
}
}
springBoot中所有的java文件都必须放在src/main/java下面的文件夹中,这样才能确保读到所有的注释,例子如图:
其中SpringbootStarterApplication.java是Springboot的启动程序
@RestController = @Controller + @ResponseBody(这两个是在springMVC使用)
一、Jackson的基本演绎法:
@JsonIgnore, 不返回该字段 @JsonFormat(…) 对时间格式进行注解 , @JsonInclude(XXX) 里面可以设置为空时不包含
@JsonIgnore
private String password;
private Integer age;
@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss a", locale="zh", timezone="GMT+8")
private Date birthday;
@JsonInclude(Include.NON_NULL)
private String desc;
二、SpringBoot热部署
热部署作用是能使得修改代码后不需要重新启动服务器,直接可以生效,提高代码编辑效率。
1.首先在在pom.xml文件中添加依赖
<!-- 热部署 -->
<!-- devtools可以实现页面热部署(即页面修改后会立即生效,
这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实现) -->
<!-- 实现类文件热部署(类文件修改后不会立即生效),实现对属性文件的热部署。 -->
<!-- 即devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),
注意:因为其采用的虚拟机机制,该项重启是很快的 -->
<!-- (1)base classloader (Base类加载器):加载不改变的Class,例如:第三方提供的jar包。 -->
<!-- (2)restart classloader(Restart类加载器):加载正在开发的Class。 -->
<!-- 为什么重启很快,因为重启的时候只是加载了在开发的Class,没有重新加载第三方的jar包。 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true, 依赖不会传递, 该项目依赖devtools;
之后依赖boot项目的项目如果想要使用devtools, 需要重新引入 -->
<optional>true</optional>
</dependency>
2.修改属性配置文件application.properties,添加热部署相关配置
#spring.freemarker.cache=false
#spring.thymeleaf.cache=true
#\u70ed\u90e8\u7f72\u751f\u6548
spring.devtools.restart.enabled=true
#\u8bbe\u7f6e\u91cd\u542f\u7684\u76ee\u5f55,\u6dfb\u52a0\u90a3\u4e2a\u76ee\u5f55\u7684\u6587\u4ef6\u9700\u8981restart
spring.devtools.restart.additional-paths=src/main/java
# \u4e3amybatis\u8bbe\u7f6e\uff0c\u751f\u4ea7\u73af\u5883\u53ef\u5220\u9664
restart.include.mapper=/mapper-[\\w-\\.]+jar
restart.include.pagehelper=/pagehelper-[\\w-\\.]+jar
#\u6392\u9664\u90a3\u4e2a\u76ee\u5f55\u7684\u6587\u4ef6\u4e0d\u9700\u8981restart
#spring.devtools.restart.exclude=static/**,public/**
#classpath\u76ee\u5f55\u4e0b\u7684WEB-INF\u6587\u4ef6\u5939\u5185\u5bb9\u4fee\u6539\u4e0d\u91cd\u542f
#spring.devtools.restart.exclude=WEB-INF/**
三、SpringBoot资源文件属性配置
1.首先需要添加一个资源配置文件resource.properties,里面加入相应的值
com.imooc.opensource.name=bob
com.imooc.opensource.website=www.bob.com
com.imooc.opensource.language=java
2.添加一个资源类,用来封装对应的资源
@Configuration//表示引用配置文件
@ConfigurationProperties(prefix="com.imooc.opensource")//prefix表示对应的前缀
@PropertySource(value="classpath:resource.properties")//表示对应的资源文件
public class Resource {
private String name;
private String website;
private String language;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
}
3.直接在Controller中调用即可
@Autowired
private Resource resource;
@RequestMapping("/getResource")
public IMoocJSONResult getResource() {
Resource bean = new Resource();
BeanUtils.copyProperties(resource, bean);
return IMoocJSONResult.ok(bean);
}
四、SpringBoot整合freemaker和thymeleaf模板
1.首先在pom.xml文件中引入模板依赖
<!-- 引入 freemarker 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!-- 引入 thymeleaf 模板依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.properties文件中添加相应的属性
############################################################
#
# freemarker \u9759\u6001\u8d44\u6e90\u914d\u7f6e
#
############################################################
#\u8bbe\u5b9aftl\u6587\u4ef6\u8def\u5f84
spring.freemarker.template-loader-path=classpath:/templates
# \u5173\u95ed\u7f13\u5b58, \u5373\u65f6\u5237\u65b0, \u4e0a\u7ebf\u751f\u4ea7\u73af\u5883\u9700\u8981\u6539\u4e3atrue
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
############################################################
#
# thymeleaf \u9759\u6001\u8d44\u6e90\u914d\u7f6e
#
############################################################
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
# \u5173\u95ed\u7f13\u5b58, \u5373\u65f6\u5237\u65b0, \u4e0a\u7ebf\u751f\u4ea7\u73af\u5883\u9700\u8981\u6539\u4e3atrue
spring.thymeleaf.cache=false
3.建立对应的静态以及动态页面
如:center.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
FreeMarker模板引擎
<h1>center page</h1>
</body>
</html>
如:index.ftl
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
FreeMarker模板引擎
<h1>${resource.name}</h1>
<h1>${resource.website}</h1>
<h1>${resource.language}</h1>
</body>
</html>
4.使用controller调用模板
4.1freemaker形式
@Controller
@RequestMapping("ftl")
public class FreemarkerController {
@Autowired
private Resource resource;
@RequestMapping("/index")
//ModelMap相当于SpringMVC中的ModelAndView
public String index(ModelMap map) {
map.addAttribute("resource", resource);
return "freemarker/index";
}
@RequestMapping("center")
public String center() {
return "freemarker/center/center";
}
}
4.2Thymeleaf形式
@Controller
@RequestMapping("th")
public class ThymeleafController {
@RequestMapping("/index")
public String index(ModelMap map) {
map.addAttribute("name", "thymeleaf-imooc");
return "thymeleaf/index";
}
@RequestMapping("center")
public String center() {
return "thymeleaf/center/center";
}
@RequestMapping("test")//映射到后面的test.html中
public String test(ModelMap map) {
User u = new User();
u.setName("superadmin");
u.setAge(10);
u.setPassword("123465");
u.setBirthday(new Date());
u.setDesc("<font color='green'><b>hello imooc</b></font>");
map.addAttribute("user", u);
User u1 = new User();
u1.setAge(19);
u1.setName("imooc");
u1.setPassword("123456");
u1.setBirthday(new Date());
User u2 = new User();
u2.setAge(17);
u2.setName("LeeCX");
u2.setPassword("123456");
u2.setBirthday(new Date());
List<User> userList = new ArrayList<>();
userList.add(u);
userList.add(u1);
userList.add(u2);
map.addAttribute("userList", userList);
return "thymeleaf/test";
}
@PostMapping("postform")
public String postform(User u) {
System.out.println("姓名:" + u.getName());
System.out.println("年龄:" + u.getAge());
return "redirect:/th/test";
}
@RequestMapping("showerror")
public String showerror(User u) {
int a = 1 / 0;
return "redirect:/th/test";
}
}
<!-- 这边th标签(表示thymeleaf)可以渲染user对象,从前面的ThymeleafController中获取user数据 -->
<div>
用户姓名:<input th:id="${user.name}" th:name="${user.name}" th:value="${user.name}"/>
<br/>
用户年龄:<input th:value="${user.age}"/>
<br/>
用户生日:<input th:value="${user.birthday}"/>
<br/>
用户生日:<input th:value="${#dates.format(user.birthday, 'yyyy-MM-dd')}"/>
<br/>
</div>
五、thymeleaf常用的标签使用方法
渲染概念:根据标签里设置的属性进行页面的显示(例如input标签的value就可以进行显示文字)。
5.1、基本使用方式:标签里使用th:text="${}",这种形式可以获取到后端传过来的数据,其中th:后面可以是标签里的属性,像th:id,th:name,th:value等。
5.2、对象引用类型:不使用对象.属性这种方式,外边嵌套一层div,然后th:object=" 传 过 来 的 对 象 名 " , 然 后 {传过来的对象名}",然后 传过来的对象名",然后符号替换成*号即可。
5.3、时间类型转换:默认是Date类型显示,可以通过在#dates.format(传过来的日期参数,日期的格式)。如图
5.4、text与utext的比较:如果th:后面是text,那么它会把传过来的内容原样的显示出来。而utext它会解析这个数据如果是html里的样式及标签,则自动转换成相应样式。
5.5、URL的方式:thymeleaf的url方式,th:href="@{地址}",它也支持普通的方式。如图
5.6、引入静态资源文件js/css:thymeleaf要引入静态文件,需要在application.properties中进行设置。如图,也就是说该项目如果使用静态文件会到static中去找。
如下图方式进行引入和url的方式相差不多
thymeleaf支持的form表单绑定url形式,如图,其中th:field可以自动解析为id=“”,name=“”,value=“”,不推荐使用,可读性不好,普通的方式也支持。
5.7、条件判断th:if——》和el表达式使用相同,大于gt,大于等于ge,小于lt,小于等于le,如果条件不满足则该标签不起作用。
判断的常用使用场景:列表标签,默认的选择和eq比较相等的。如图,eq写在外面也可以。
5.8、th:unless与th:if——》与if作用相反的。
5.9、th:switch与th:case——》#{roles.manager}相当于资源文件的使用,前提是进行资源文件的配置
5.10、th:each——》循环的作用,userList为传过来的集合,而person相当于jstl中的每一个变量。
六、SpringBoot配置全局的异常捕获 ----- web和ajax兼容
配置异常捕获的原因:自带的异常机制返回的页面相对来说,不是很人性化,对于用户来说,抛出一个异常,可读性差,像500或者404。
步骤:
首先需要创建一个异常捕获类,在该类上添加@ControllerAdvice,并且需要实现errorHandler这个方法,该方法有三个参数分别为HttpServletRequest、HttpServletResponse、捕获的异常Exception,该方法上需要添加@ExceptionHandler这个注解,然后就可以在这个方法中对该异常进行处理 了,如图,它是先在后台打印该异常,并且返回一个ModelAndView,把e的内容放入,以及放入放生错误的地址,然后再放入了一个错误页面,该页面是自己定义的,而不是SpringBoot自带的页面,该页面也是需要进行配置的。
异常捕获类
@ControllerAdvice
public class IMoocExceptionHandler {
public static final String IMOOC_ERROR_VIEW = "error";
@ExceptionHandler(value = Exception.class)
public Object errorHandler(HttpServletRequest reqest,
HttpServletResponse response, Exception e) throws Exception {
e.printStackTrace();
if (isAjax(reqest)) {
return IMoocJSONResult.errorException(e.getMessage());
} else {
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", reqest.getRequestURL());
mav.setViewName(IMOOC_ERROR_VIEW);
return mav;
}
}
/**
*
* @Title: IMoocExceptionHandler.java
* @Package com.imooc.exception
* @Description: 判断是否是ajax请求
* Copyright: Copyright (c) 2017
* Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
*
* @author leechenxiang
* @date 2017年12月3日 下午1:40:39
* @version V1.0
*/
public static boolean isAjax(HttpServletRequest httpRequest){
return (httpRequest.getHeader("X-Requested-With") != null
&& "XMLHttpRequest"
.equals( httpRequest.getHeader("X-Requested-With").toString()) );
}
}
ErrorController类
@Controller
@RequestMapping("err")
public class ErrorController {
@RequestMapping("/error")
public String error() {
int a = 1 / 0;
return "thymeleaf/error";//表示用一个error.html页面来跳转
}
@RequestMapping("/ajaxerror")
public String ajaxerror() {
return "thymeleaf/ajaxerror";
}
@RequestMapping("/getAjaxerror")
@ResponseBody
public IMoocJSONResult getAjaxerror() {
int a = 1 / 0;
return IMoocJSONResult.ok();
}
}
error.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>捕获全局异常</title>
</head>
<body>
<h1 style="color: red">发生错误:</h1>
<div th:text="${url}"></div>
<div th:text="${exception.message}"></div>
</body>
</html>
ajax处理的代码自行补充;;