springboot(二)

1.(八)SpringBoot之freeMarker基本使用
https://www.cnblogs.com/shyroke/p/8022940.html
freemarker官网:https://freemarker.apache.org/
一篇很全面的freemarker教程:
https://www.cnblogs.com/yijiayuyan12/p/8277664.html
1.1 静态文件默认目录如:static,templates包下放置模板文件
1.2

# template
<html>
<head>
  <title>Welcome!</title>
</head>
<body>
  <h1>Welcome ${user}!</h1>
  <p>Our latest product:
  <a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>

1.3 一个@controller类:

@RequestMapping(path= {"/ftl"})
public String news(Model model) {
	model.addAttribute("value1", "val1");
	List<String> colors = Arrays.asList(new String[] {"RED", "GREEN", "BLUE"});
	Map<String, String> map = new HashMap();
	for (int i = 0; i < 4; i++) {
		map.put(String.valueOf(i), String.valueOf(i * i));			
	}
	model.addAttribute("map", map);
	model.addAttribute("colors", colors);
	return "news";

news.ftl:

<#--如何遍历list和map-->
<#list colors as color>
${color}
</#list>

<#list map?keys as key>
key:${key}--value:${map["${key}"]}
</#list>

${map["2"]}<#--output:4-->
<#--${user.name}
${user.getName()}
-->

1.4
news.ftl:

<#--创建变量,包含ftl文件-->
<#assign title="coder">
<#include "header.ftl" parse=true>

header.ftl:

title<h>${title}</h>

2.@responseBody注解

2.1 @responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据,需要注意的呢,在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。

2.2 User字段:userName,pwd.那么在前台接收到的数据为:’{“userName”:“xxx”,“pwd”:“xxx”}’

	@RequestMapping("/login")
  @ResponseBody
  public User login(User user){
    return user;
  }
  效果等同于如下代码:
  @RequestMapping("/login")
  public void login(User user, HttpServletResponse response){
    response.getWriter.write(JSONObject.fromObject(user).toString());
  }

3.http状态码
301:永久转移
302:临时转移
4.IndexController类方法示例:

	@RequestMapping(path= {"/request"})
	@ResponseBody
	public String request(HttpServletRequest request,
			HttpServletResponse response,
			HttpSession session) {
		StringBuffer stringBuffer = new StringBuffer();
		Enumeration<String> headerNames = request.getHeaderNames();
	
		while (headerNames.hasMoreElements()) {
			String name = headerNames.nextElement();
			stringBuffer.append(name + ":" + request.getHeader(name) + "<br>");
		}
		return stringBuffer.toString();
	}
	
	@RequestMapping(value= {"/response"})
	@ResponseBody
	public String response(@CookieValue(value="coderid", defaultValue="a") String coderid,
			@RequestParam(value="key", defaultValue="key") String key,
			@RequestParam(value="value", defaultValue="value") String value,
			HttpServletResponse response) {
		response.addCookie(new Cookie(key, value));
		response.addHeader(key, value);
		return "coderidfrom cookie:" + coderid;
	}
	
	@RequestMapping(value= {"/redirect/{code}"})
	public String redirect(@PathVariable("code") int code,
			HttpSession session) {
		session.setAttribute("msg", "jump from redirect");
		return "redirect:/"; // 特殊句法吧,重定向:/;/request
	}
	/*public RedirectView redirect(@PathVariable("code") int code) {
		RedirectView red = new RedirectView("/", true);
		if (code == 301) {
			red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
		}
		return red;
	}*/
	
	@RequestMapping("/admin")
	@ResponseBody
	public String admin(@PathParam(value="key") String key) {
		if ("admin".equals(key)) {
			return "hello admin";
		}
		throw new IllegalArgumentException("key error");
	}
	
	@ExceptionHandler
	@ResponseBody
	public String error(Exception e) {
		return "error:" + e.getMessage();
	}

5.AspectJ是一个面向切面的框架
AOP注解

package com.example.toutiao.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {
	private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
	@Before("execution(* com.example.toutiao.controller.IndexController.*(..))")
	public void beforeMethod(JoinPoint joinPoint) {
		StringBuffer stringBuffer = new StringBuffer();
		for (Object arg : joinPoint.getArgs()) {
			stringBuffer.append("arg:" + arg.toString() + "|");
		}
		logger.info("before method: "
				+ stringBuffer.toString());
	}
	
	@After("execution(* com.example.toutiao.controller.IndexController.*(..))")
	public void afterMethod() {
		logger.info("after method: ");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_21122683/article/details/88091798