Spring Boot Web开发(四)

1.静态文件加载

在我们开发Web应用的时候,需要引用大量的js、css、图片等静态资源。
默认配置
Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:
/static
/public
/resources
/META-INF/resources
举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/D.jpg。如能显示图片,配置成功。
如下配置,可以直接访问到:
在这里插入图片描述
引用方法,如下:

<link rel="stylesheet" href="/css/index.css" type="text/css" />
<script src="/js/index.js"></script>

2.全局异常的处理

404错误的处理:

(1)在classpath下的error文件下建立404.html ,500.html根据相应的异常会进入对应的页面。
(2)实现ErrorController,出现异常走对应的逻辑,如下则是处理:

@Controller
public class NotFoundException implements ErrorController {
 
    @Override
    public String getErrorPath() {
        return "/error";
    }
 
    @RequestMapping(value = {"/error"})
    @ResponseBody
    public Object error(HttpServletRequest request) {
        Map<String, Object> body = new HashMap<>();
        body.put("error", "not found");
        body.put("code", "404");
        return body;
    }
}

注:不光是404异常,其他异常也会走到,不过进行了其他异常进行@ControllerAdvice异常处理,会走到改逻辑。

(2)@ControllerAdvice + @ExceptionHandler 处理异常‘
说明:’
@ControllerAdvice 是 controller 的一个辅助类,最常用的就是作为全局异常处理的切面类
@ControllerAdvice 可以指定扫描范围
@ControllerAdvice 约定了几种可行的返回值,如果是直接返回 model 类的话,需要使用 @ResponseBody 进行 json 转换
o返回 String,表示跳到某个 view
o返回 modelAndView
o返回 model + @ResponseBody

具体事例如下:

@ControllerAdvice
public class GolbalExceptionHandler {
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Map<String, Object> exceptionHandler() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorCode", "101");
		map.put("errorMsg", "系統错误!");
		return map;
	}
}

3.模板渲染页面
模板引擎
在动态HTML实现上Spring Boot依然可以完美胜任,并且提供了多种模板引擎的默认配置支持,所以在推荐的模板引擎下,我们可以很快的上手开发动态网站。
Spring Boot提供了默认配置的模板引擎主要有以下几种:
Thymeleaf
FreeMarker
Velocity
Groovy
Mustache

以FreeMarker渲染界面为例,配制如下:
(1)加入依赖包

<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

(2)在templates中建立文件,返回String类型即可匹配,如下:

@Controller
public class WebController {
	@RequestMapping("/web/index")
	public String index(Map<String,Object> result) {
		result.put("name", "yushengjun");
		result.put("sex", "0");
		List<String> listResult = new ArrayList<String>();
		listResult.add("zhangsan");
		listResult.add("lisi");
		listResult.add("itmayiedu");
		result.put("userlist", listResult);
		return "index";
	}
}

templates下的index.ftl页面:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>首页</title>
<link rel="stylesheet" href="/css/index.css" type="text/css" />
<script src="/js/index.js"></script>
</head>
<body>
	<img src="/image/d.png" />
	 <span class="a"> ${name}</span>
	 <span class="a">hhhhh</span>
<#if sex=="1">
            男
      <#elseif sex=="2">
            女
     <#else>
        其他      
	  
	  </#if>	  
	 <#list userlist as user>
	   ${user}
	 </#list>
	 <input type="button" onclick="c()" value="hello" />
</body> 
</html>

访问页面http://localhost:8080/web/index结果为:
在这里插入图片描述
(3)修改以下属性,可修改默认配置

spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
#comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved

4.jsp渲染页面

jsp渲染页面这种方式不推荐使用。

(1)添加依赖

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
		</dependency>

(2)配置文件中假如以下配置,即可一一映射访问

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

注::创建SpringBoot整合JSP,一定要为war类型,否则会找不到页面

猜你喜欢

转载自blog.csdn.net/qq_36831305/article/details/91863756