传统方式
@RequestMapping("/param01")
public String param01(HttpServletRequest request) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
request.setAttribute("msg","账号或密码错误");
System.out.println("id="+id);
return "success";
}
ModelAndView返回
@RequestMapping("/param02")
public ModelAndView param02(String name){
System.out.println("name="+name);
ModelAndView mv = new ModelAndView();
mv.setViewName("success");
mv.addObject("msg","账号或密码错误");
return mv;
}
字符串返回
@RequestMapping("/param12")
public String param12(String name, Model model){
System.out.println("name="+name);
model.addAttribute("msg","账号或密码错误");
return "success";
}
转发与重定向
默认返回页面是转发效果
如果需要重定向,需要在返回页面的时候,追加redirect:,后边需要追加视图后缀
@RequestMapping("/getUser")
public String getUser(Model model){
model.addAttribute("msg","测试数据");
return "redirect:hello.jsp";
}
Ajax返回
在方法上方添加注解@ResponseBody
如果整个类都为Ajax返回的方法则可在类的上方添加@RestController替代@Controller
Ajax返回json格式的数据需要在pom.xml中导入依赖坐标
<!--引入json的依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId><version>2.9.0</version>
</dependency>
前端调用Ajax方法从后台获取数据即可