- springboot整合Thymeleaf
- springboot整合JSP
- springboot默认的JSON解析方案:不需要额外加依赖,应为springboot集成了JSON
- 使用Gson处理JSON
- springBoot 整合Fastjson
- SpringBoot默认的静态资源访问方案
- 两种方式自定义静态资源位置
- SpringBoot实现文件上传====fileupload
- SpringBoot中通过AJax实现文件上传
- SpringBoot实现多文件的上传
- @ControllerAdvice注解的三种用法:
- SpringBoot自定义错误页面
- SpringBoot自定义异常数据
- SpringBoot自定义异常视图 DefaultErrorViewResolver
- springboot整合Thymeleaf
是新一代的java模板引擎,支持HTML原型,可以直接打开查看样式,不需要后端渲染,提供了自动化配置解决方案,后缀为.html可以直接在浏览器打开。
- https://www.thymeleaf.org 官方文档
- springboot整合JSP
1、需要手动加入依赖,没有对应的模板依赖提供
<dependency>
<groupId>org.apache.tomact.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</denpency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</denpency>
2、添加web工程 open ModelSettings
3、新建 config implements WebMvcConfigurer
形如://配置视图解析器
@Configuration
public calss WebMvcConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegstry registry){
registry.jsp(prefix:"/jsp/",suffix:".jsp");
}
}
- springboot默认的JSON解析方案:不需要额外加依赖,因为springboot集成了JSON
- 使用Gson处理JSON
<exclusions>//排除掉json的依赖
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artigactId>
</exclusion>
</exclusions>
<dependency>//添加Gson的依赖
<groupId>con.google.code.gson</groupId>
<artifactId>gson</artifactId>
</denpency>
- springBoot 整合Fastjson
需要手动配置HTTPMessageConverter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artrifactId>
<version>1.2.49</version>
</dependency>
@Bean
FastJsonHttpMeassgerConvert fastJsonHttpMessageConverter(){
FastJsonHttpMessageConvert convert = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
converter.setFastJsonConfig(config);
returen converter;
}
- SpringBoot默认的静态资源访问方案:
/** 表示匹配任意层级的路径,Ant风格的路径匹配符 /* 表示匹配上一级层级的路径
resources目录下的static目录默认存放静态资源
static
META-INF.resources
resources
public 这四个文件夹都可以
WebMVCAutoConfiguration类下面的WebMvcProperties
- 两种方式自定义静态资源位置
在 application.properties文件下添加
spring.resources.static-locations=classpath:/zenghao/
//spring.mvc.static-path-pattern=/**
也可以自定义一个类来实现WebMvcConfigurer
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry){
registry.addResourceHandler("/**).addResourceLocations("classpath:/zenghao/");
}
}
- SpringBoot实现文件上传====fileupload
CommopnsMultipartResolver//SpringMVC
StandardServletMultipartResolver 需要支持Servlet3.0,springBoot使用这个
@RestController
public calss FileUploadController{
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd"); //用日期格式,为了区分不同路径
@PostMapping("/upload") //文件上传注释
public String upload (MultipartFile file,HTTPServletRequest req){
String format = sdf.format(new Date());
String realPath = req.gerServletContext()/getRealPath("/img")+format;
File folder = new File(realPath);
if(!folder.exists()){
folder.mkdirs();
}
String oldName = file.gerOriginalFilename();//获取文件旧的名称
String newName = UUID.randomUUID().toString()+oldName.subString(oldName.lastIndexof("."));
try{
file.transferTo(new File(floder,newName));
String url = req.getScheme() //动态获取协议,不要写死了,形如http或者https
+"://"+req.getServerName()+":"+req.getServerPort()+"/img"
+format+newName;
return url;
}catch(IOException e){
e.printStackTrace();
}
return "error";
}
}
在static下创建html页面
.....
<body>
<form action="/upload" metho="post" enctype="multipart/form-data">
<input type="file" name="frile">
<input type="submit" value="提交">
</form>
</body>
........
也可以在application.propertie中添加(如果文件上传有额外的配置,可以在这里面添加)
spring.servlet.multipart.location //临时文件的地址
spring.servlet.multipart.max-faile-size=1MB //上传单个文件大小
spring.servlet.multipart.enabled=true //是否启用mulitpartReslover
- SpringBoot中通过AJax实现文件上传
主要是前端需要变化
新创建html文件
.....
<script src="jquery3.3.1.js"></script> //需要引入jquery,js文件放在static文件夹下面
<body>
<div id="result"></div>
<input type="file id="file">
<input type="button" value="上传" onclick="uploadFile()">
<script>
function uploadFile(){
var file = $("#file")[0].files[0];
var formData = new FormData();
formData.append("file",file);
$.ajax({
type:'post',
url:'/upload',
processData:false,
contentType:false,
data:formData,
success:function(msg){
$("#result").html(msg);
}
})
}
</script>
- SpringBoot实现多文件的上传
@RestController
public calss FileUploadController{
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd"); //用日期格式,为了区分不同路径
@PostMapping("/upload") //文件上传注释
public String upload (MultipartFile[] files,HTTPServletRequest req){
String format = sdf.format(new Date());
String realPath = req.gerServletContext()/getRealPath("/img")+format;
File folder = new File(realPath);
if(!folder.exists()){
folder.mkdirs();
}
for(MultipartFile file : files){
String oldName = file.gerOriginalFilename();//获取文件旧的名称
String newName = UUID.randomUUID().toString()+oldName.subString(oldName.lastIndexof("."));
try{
file.transferTo(new File(floder,newName));
String url = req.getScheme() //动态获取协议,不要写死了,形如http或者https
+"://"+req.getServerName()+":"+req.getServerPort()+"/img"
+format+newName;
System.out.println(url);
}catch(IOException e){
e.printStackTrace();
}
return "success";
}
}
}
在static下创建html页面
.....
<body>
<form action="/upload" metho="post" enctype="multipart/form-data">
<input type="file" name="frile" multiple>
<input type="submit" value="提交">
</form>
</body>
- @ControllerAdvice注解的三种用法:
- 处理全局异常 //SpringBoot有提供异常处理,如果要用这个注解也可以
- 预设全局数据
- 请求参数预处理
1、处理全局异常
@ControllerAdvice
public class MyException{
@ExceptionHandler(MaxUploadSizeExceedeException.class)
public myException( MaxUploadSizeExceededException e,HttpServletResponse resp){
resp.setContentType("text/html:charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("上传文件大小超出限制");
out.flush();
out.close();
}
}
2、预设全局数据,任何一个controller都能获取到
@ControllerAdvice
public class GlobalData{
@ModeAttribute(value="info")
public Map<String,object> mydata(){
Map<String,Object> map = new HashMap<>();
map.put("name","zenghao");
map.put("sex","boy");
return map;
}
}
//新建一个controller
@RestController
public class HelloController{
@GetMapping("/hello")
public String hello(Model model){
Map<String,Object> map = new model.asMap();
Set<String> keySet = map.KeySet();
for (String key : keySet){
System.out.println(key+":"+map.get(key));
}
return "hello";
}
}
3、请求参数预设处理
post接收参数的时候,可能会存在同名的参数名的时候,需要分开进行处理
@ControllerAdvice
public class GloabData{
@InitBinder("a")//取别名
public void initA(WebDataBinder binder){
binder.setFiledDefaultPrefix("a.");
}
@InitBinder("b")
public void initA(WevDataBinder binder){
binder.setFiledDefaultPrefix("b.");
}
}
- SpringBoot自定义错误页面
//可以在Static下创建静态html页面
//在static下创建error目录
//在error目录下创建404html、500.html
//但是错误太多,这样写显然不好
//可以改成4xx.html,5xx.html,模糊匹配
//还可以用动态页面展示错误信息,Themelf 或者Freemaker
//就要在pom下加入依赖
//形如:
<denpency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymelf</artifactId>
</denpency>
//在tmeplate目录下创建error目录下创建404、500.html
//优先访问动态页面,前提:静态页面和动态页面同时存在的情况下,先精确后模糊
- SpringBoot自定义异常数据
<html lang="en" xmlns:th="http://www,thymeleaf.org">
......
<table border="1">
<tr>
<td>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>timestamp</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>message</td>
<td th:text="${message}"></td>
</tr>
<tr>
<td>error</td>
<td th:text="${error}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
<tr>
<td>myerror</td>
<td th:text="${myerror}"></td>
</tr>
</table>
//自定义异常,新建一个MyErrorAttribute类
@Compent
public class MyErrorAttribute extends DefaultErrorAttribute{
@Override
public Map<String,Object> getErrorAttributes(WebRequest wevRequest,boolean includeStackTrace){
Map<String,Object> map = super.getErrorAttributes(webRequest,includeStackTrace);
map.put("myerror","这是我自定义的异常信息");
return map;
}
}
- SpringBoot自定义异常视图 DefaultErrorViewResolver
@Compent
public class MyErrorViewResolver extends DefaultErrorViewResolver{
public MyErrorResolver(ApplicationContext applicationContext,ResourceProperties resourceProperties){
super(applicationContext,resourceProperties);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request,HttpStatus status,Map<string,Object>model){
ModelAndView mv = new ModelAndView();
mv.setViewName("zenghao");
mv.addAllObjects(model);
return mv;
}
}