Spring MVC
2021-01-10 18:32
自己定义的类型转换器(Date)
配置文件的位置
public class DateConvert implements Converter
@Override
public Date convert(String str) {
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date date = sf.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
静态资源处理问题
Springmvc跳转(转发重定向):
转发,重定向
不会帮你加前后缀
Forward:路径
Redirect:路径
@Controller
@RequestMapping("/person/")
public class HelloController {
@RequestMapping("for")
public String jump(Model model){
model.addAttribute("info","这是我的转发数据");
return "forward:/view/ok.jsp";
}
@RequestMapping("red")
public String jump2(Model model){
model.addAttribute("info","这是我的转发数据");
return "redirect:/view/ok.jsp";
}
}
默认参数绑定
1.Form-controller
2.Controller 本质上就是servlet的扩展,有关servlet的内容可以直接使用
3.HttpServletRequest ,Model ,ModelMap ,Map
@Controller
@RequestMapping("/jump/")
public class JumpController {
@RequestMapping("p1")
public String p1(HttpServletRequest request, HttpServletResponse response, HttpSession session){
request.setAttribute("info","request");
session.setAttribute("username","张三");
return "ok";
}
@RequestMapping("p2")
public String p2(Model m){
m.addAttribute("info","model穿过来的参数");
return "ok";
}
@RequestMapping("p3")
public String p3(ModelMap m){
m.addAttribute("info","ModelMap穿过来的参数");
return "ok";
}
@RequestMapping("p4")
public String p4(Map m){
m.put("info","Map穿过来的参数");
return "ok";
}
}
返回值处理
1.可以返回modelview
ModelAndView mv=new ModelAndView();
mv.setViewName("ok");
mv.addObject("info","这是我的第一次");
2.String 直接认为你是资源,帮你自动加前后缀
3.Void 比如直接在session中保存数据,不涉及页面的跳转
4.public void saveSession(HttpSession session){
session.setAttribute("username","admin");
}
5.异步返回数据(ajax)
希望后台返回一串json数据
(1):导入jsckson.....jar
(2):加注解@Resposebody代表响应的文本内容,如果返回的对象,自动转成json字符串
@Controller
@RequestMapping("/json/")
public class JsonController {
@RequestMapping("j1")
@ResponseBody
public String jsonTest1(){
return "hello";
}
@RequestMapping("j2")
@ResponseBody
public DogBean jsonTest2(){
DogBean dog=new DogBean();
dog.setColor("红色");
dog.setSex("男");
return dog;
}}
@RestController注解放在类名上,会将该类中的所有的方法上面统一加上@ResponseBody