package com.zhp.action;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.zhp.entity.User;
/**
* 默认.action和.html都可访问
*
*/
@Controller
@SessionAttributes({"user"})
public class UserAction {
@RequestMapping("{index,main}")//数组,多个url映射
public String index(){
System.out.println("=======index()======");
return "index";
}
//传参数 默认和形参名字保持一致即可
@RequestMapping("login")
public String login(Model model,String uname,String upass){
System.out.println(uname+"==login()=="+upass);
model.addAttribute("username", uname);
return "index";
}
@RequestMapping("reg")
public String reg(User user){//直接属性名对应赋值
System.out.println("===reg():"+user);
return "redirect:index.jsp";
// return "forward:index.jsp";
}
//通过@RequestParam指定了页面参数和形参变量对应关系 但是默认要求必须传此参数 否则404
@RequestMapping("detail")
public String detail(@RequestParam("uname")String username){
System.out.println("======detail()======"+username);
return "detail";
}
//可以指定请求参数可有可无,但是注意数字类型最好使用包装类,否则null时异常,无法转为基本类型
@RequestMapping("query")
public String query(@RequestParam(required=false,value="id")Integer id){
System.out.println("======query()======"+id);
return "detail";
}
/**
* 确认信息
* @ModelAttribute:封装同时,放入request对象
* @param user 一定注意要有无参构造方法
* @return
*/
@RequestMapping("confirm")
// public String confirm(@ModelAttribute("user")User user){
// System.out.println("==confirm:"+user);
// return "confirm";
// }
public String confirm(Model model){
//默认使用user为key 放入request
model.addAttribute(new User("AAAA","BBBB","CCCC"));
System.out.println("-------confirm-----");
return "confirm";
}
/**
* 跳转到spring标签页面
* @return
*/
@RequestMapping("toadd")
// public String toAdd(Model model){
// model.addAttribute(new User());
// return "add";
// }
//也可以直接参数user
public String toAdd( User user){
return "add";
}
public String doAdd(User user){
return "index";
}
/**
* 列表
* @param model
* @return
*/
@RequestMapping("list")
public String list(Model model){
model.addAttribute("userlist", list);
return "list";
}
private static List<User> list = null;;
static{
list = new ArrayList<User>();
list.add(new User("曹操","2123","cao@sian.com"));
list.add(new User("张飞","2222","zhang@sian.com"));
list.add(new User("周瑜","3333","zhou@sian.com"));
}
}