1 用@Controller返回json
RestController的返回数据默认为json,也就是自动转json只适用于RestController;使用Controller也能转json,那就使用一个注解ResponseBody
例:
SpTest 类要与启动类SpringbootApplication同级或者与该类同级的子包中
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpTest {
@RequestMapping(value = "/test",method = RequestMethod.GET)
public @ResponseBody
String getString(){
return "getString";
}
启动服务,在浏览器请求 http://127.0.0.1:8080/test
在类上用Controller控制器,在方法上添加@ReponseBody
直接在类上用@RestController
这两种方式返回的都是借口数据,接口级别的控制器默认返回json
可以返回 Set set、 List list、 Animal animal
在视图解析层对Animal做序列化处理,默认用Jackson序列化处理工具
2 RequestMapping多种映射:方法上修饰
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class SpTest {
@RequestMapping(value = "/test",
method = RequestMethod.GET,
params = {"userName","age!=18"},
headers = {"Host=127.0.0.1"})
public @ResponseBody
String getString(){
return "两个参数必须有,并且age参数不能等于18";
}
value:请求路径
method :请求方法
params :参数;userName和age参数必传,并且age参数不能等于18
headers :头信息;头信息有很多,host只是其中一个
2.1 请求时若请求没有要求传参,请求时传参也能请求到,因为是根据路径映射的
例:www.baidu.com/name=xx也是能请求到百度首页的
2.2 但是若该请求是要求传参的那么请求时必须传参,谷歌浏览器可以通过f12看到请求、返回…