第六章 用實體接收參

創(chuàng)建實體類User

package com.xbb.springboot.tutorial.entity;

import java.sql.Date;

public class User {
    private String id;
    private String username;
    private String password;
    private Date birthday;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

}

修改LoginController中l(wèi)ogin方法用User實體接收參數(shù)

@RequestMapping("login")
    public ModelAndView login(HttpServletRequest request, User user) {
        ModelAndView mav = new ModelAndView();
        
        if ("admin".equals(user.getUsername()) && "666666".equals(user.getPassword())) {
            request.getSession().setAttribute("user", user);
            mav.setViewName("redirect:/view/index");//客戶端跳轉
            return mav;
        } else {
            mav.addObject("errorMsg", "用戶名或密碼有誤");
            mav.setViewName("login");//服務器跳轉
            return mav;
        }
    }

修改index.html獲取用戶信息

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${user.username}<br/>
${user.password}
</body>
</html>

修改LoginInterceptor中preHandle方法

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
       User user = (User)request.getSession().getAttribute("user");
       if (user == null) {
           response.sendRedirect("/view/login");
           return false;
       }
       return true;
    }

重新登錄

http://localhost:8080/view/login

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容