RestFul風格和JSON字串
阿新 • • 發佈:2020-08-02
RestFul風格
特點:
- 簡潔
- 高效
- 安全
@Controller public class RestFulController { //原來的: http://localhost:8080/add?a=1&b=2 //RestFul: http://localhost:8080/add/a/b @RequestMapping("/add/{a}/{b}") //@RequestMapping(Value="/add/{a}/{b}",Method="RequestMethod.Post") public String test1 (@PathVariable int a, @PathVariable String b, Model model){ String res = a + b; model.addAttribute("msg","結果為"+res); return "test" ; } }
JSON
1、返回物件格式
@Controller
public class UserController {
@RequestMapping("/j1")
@ResponseBody //它就不會走檢視解析器,會直接返回一個字串
public String json1(){
//建立一個物件
User user = new User("張三",20,"男");
return user.toString();
}
}
2、返回 JSON格式
@Controller public class UserController{ @RequestMapping(value="/j1" , produces="application/json;charset=utf-8") @ResponseBody //它就不會走檢視解析器,會直接返回一個字串 public String json1() throws JsonProcessingException { //jackson, objectMapper ObjectMapper mapper = new ObjectMapper(); //建立一個物件 User user = new User("張三",20,"男"); String str = mapper.writeValueAsString(user); return str; } }
<!--固定的,使用了jackson包就需要配置--> <!--JSON亂碼問題配置--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name= "objectMapper"> <bean class="org.springframework.http.converter.json.Jackson20bjectMapperFactoryBean"> <property name= "failOnEmptyBeans" value="false" /> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
拓展:返回時間戳格式的 JSON字串
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
objectMapper mapper = new ObjectMapper();
Date date = new Date();
//objectMapper,時間解析後的預設格式為: Timestamp(時間戳)
return mapper.writeValueAsString(date);
}
或者:
@RequestMapping("/j3")
public String json3() throws JsonProcessingException {
objectMapper mapper = new objectMapper();
//不使用時間戳的方式
mapper.configure (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS , false);
//自定義日期的格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(sdf);
Date date = new Date();
//objectMapper,時間解析後的預設格式為: Timestamp, 時間戳
return mapper.writeValueAsString(date);
}