MVC方法返回值类型
ModelAndView返回值类型:
1.当返回为null时,页面不跳转。
2.当返回值没有指定视图名时,默认使用请求名作为视图名进行跳转。
3.当返回值指定了视图名,程序会按照视图名跳转。
/*添加*/
@RequestMapping("/getSale")
public ModelAndView addSale(Sale sale,HttpServletRequest request,ModelAndView mv){
if (sale!=null) {
Double totalPrice = sale.getPrice() * sale.getQuantity();
sale.setTotalPrice(totalPrice);
sale.setSaleDate(new Date());
Users user = (Users) request.getSession().getAttribute("user");
sale.setUserId(user.getUid());
int i = userService.addSale(sale);
if (i > 0) {
mv.setViewName("saleList");
} else {
mv.setViewName("prodectAdd");
}
}
return mv;
}
Objectl返回值类型;
/*绑定下拉框*/
@RequestMapping("/prodectName")
@ResponseBody
public Object getprodectName(){
List<Product> products = userService.getproductName();
return products;
}
String返回值类型:
1、如果返回值为null,那么以请求名作为视图名进行跳转
2、如果指定返回值,那么按照指定返回值作为视图名进行跳转,可以通过model,modeMap携带数据。
3、如果返回值带有forward或者redirect前缀,那么将会进行相应的请求或重定向,不过不能通过mvc的数据模型携带数据,可以通过ServletApi携带数据。
@RequestMapping("/welcome")
public String welcome(String userName, Model model){
//将用户名保存到对应的作用域中
model.addAttribute("userName",userName);
return "welcome";
}
MVC参数传递
请求参数自动类型转换
JSP页面
form class="loginForm" action="/user/getUser" method="post" >
<div class="inputbox" style="text-align:center; ">
<label for="user">用户名:</label>
<input id="user" type="text" name="userName" placeholder="请输入用户名" />
</div>
<div class="password" style="text-align:center; " >
<label for="mima">密码:</label>
<input id="mima" type="password" name="password" placeholder="请输入密码" />
</div>
<div class="subBtn" style="text-align:center; ">
<input type="submit" value="登录" />
<input type="reset" value="重置"/>
</div>
</form>
注意点*:控制器Controller中的方法参数名称必须和表单元素的name属性值保持一致
/*登录*/
@RequestMapping("/getUser")
@ResponseBody
private ModelAndView getUser(String userName, String password, ModelAndView mv, HttpServletRequest request, HttpServletResponse response, HttpSession session){
Users user = userService.getUser(userName,password);
System.out.println("user======"+user);
if (user!=null){
System.out.println("成功");
//登录成功
request.getSession().setAttribute("user",user);
//转发
mv.setViewName("index");
}else{
//登录失败
mv.setViewName("login");
}
return mv;
}
请求参数装配为POJO对象
新增Person
public class Person {
private String username;
private int age;
//省略get/set方法
}
控制器
//当实体类中的属性名和表单元素的name属性相同时,即可完成自动装配
@RequestMapping(value = "personObject",method = RequestMethod.POST)
public String personObject(Person person){
System.out.println(person);
return "hello";
}