Java技术专题程序员

Springmvc之向JSP页面提供数据(request,ses

2018-10-07  本文已影响52人  爱撒谎的男孩

Springmvc之向JSP页面提供数据(request,session)

准备

<form action="<%=request.getContextPath()%>/user/login.do" method="post">
    username:<input type="text" name="username"> <br>
    password:<input type="text" name="password"> <br>
    age:<input type="text" name="age">
    <input type="submit" value="提交">
</form>
public class User {
    private String username;
    private String password;
    int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", password=" + password + "]";
    }

}

使用HttpServletRequest转发

    /**
     * @param user 接收请求参数
     * @param request   添加属性值request域中
     */
    @RequestMapping(value = "/login.do")
    public String login(User user,HttpServletRequest request,HttpServletResponse response) {
        System.out.println(user);
        request.setAttribute("user", user);
        return "error";
    }

【不常用】使用ModelAndView转发

    @RequestMapping(value = "/login.do")
    public ModelAndView login(User user) {
        System.out.println(user);
        //创建一个Map,存储数据
        Map<String, User> map=new HashMap<String, User>();
        //将获取的user对象存储进去
        map.put("user", user);
        //返回一个ModelAndView对象,第一个参数是视图,第二个是Map存储数据
        return new ModelAndView("error", map);
    }

【推荐使用】使用ModelMap转发

    @RequestMapping(value = "/login.do")
    public String login(User user,ModelMap map) {
        System.out.println(user);
        //将数据存储在ModelMap中
        map.addAttribute("user", user);
        return "error";
    }

拓展

    @RequestMapping(value = "/login.do")
    public String login(User user,Map<String, Object> map) {
        System.out.println(user);
        //将数据存储在ModelMap中
        map.put("user", user);
        return "error";
    }

Session

使用HttpSession

    @RequestMapping(value = "/login.do")
    public String login(User user,HttpSession session) {
        //将id存储在session中
        session.setAttribute("uid", "9527");
        return "error";
    }
上一篇下一篇

猜你喜欢

热点阅读