自定义全局ObjectMapper
代替默认ObjectMapper
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration
public class JacksonConf {
// 此处根据返回值, 对原有的`ObjectMapper`进行替换
@Bean
public ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
return objectMapper;
}
}
下面例子是获取当前时间的请求
@GetMapping("/now.json")
public @ResponseBody Map now() {
Map map = new HashMap();
map.put("time", new Date());
return map;
}
// {"time": "2022-11-15 11:38:05"}
Controller
中重定向可以返回redirect:
为前缀的URI
, 内部重定向则可以使用前缀为forward:
的前缀
@RequestMapping("/order/saveorder.html")
public String saveOrder(Order order) {
Long orderId = service.addOrder(order);
return "redirect:/order/detail.html?orderId=" + orderId;
}
@RequestMapping("/bbs")
public String index() {
return "forward:/bbs/module/1-1.html"
}
@RequestMapping("/bbs/module/{type}-{page}")
public ModelAndView module(@PathVariable int type, @PathVariable int page) {
...
}
对于bbs
请求, 都会到module
方法, 因为forward
的URL
是bbs/module/1-1.html
在ModelAndView
中设置带有redirect:
前缀的URI
ModelAndView view = new ModelAndView("redirect:/order/detail.html?orderId=" + orderId);
// 或者使用`RedirectView`的类
RedirectView view = new RedirectView("/order/detail.html?orderId=" + orderId);