1.首先为了能直观地在jsp页面体现session的内容,我使用了jstl表达式,首先在pom.xml中引入jstl的依赖
<!-- jstl所需要的依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
2.编写登录界面以及登录成功界面
登录界面
<%@ page contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title>用户登录</title>
</head>
<body>
<form action="login" method="post">
<input type="text" name="uname" /><br/><br/>
<input type="password" name="pwd" /><br/><br/>
<input type="submit" value="登录"><br/><br/>
</form>
</body>
</html>
登录成功界面
<%@ page contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!-- 引入jstl库 -->
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8">
<title>成功</title>
</head>
<body>
<h1>${sessionScope.user.uname }登录成功!!!</h1>
<h2>欢迎您,${sessionScope.uname }</h2>
</body>
</html>
3.编写请求处理类以及实体类
实体类
package com.yc.entity;
public class User {
private String uname;
private String pwd;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String toString() {
return "User [uname=" + uname + ", pwd=" + pwd + "]";
}
}
请求处理类
package com.yc.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.yc.entity.User;
@Controller
@SessionAttributes({"user","uname"})
public class LoginController {
@RequestMapping("/login")
public String login(User user,ModelMap map) {
//user会自己注入session中
//将uname放入session作用域中,这样转发页面也可以取到这个数据。
map.addAttribute("uname", user.getUname());
return "loginSuccess";
}
}
4.运行测试
OK,到现在我们利用session实现的用户登录已经可以了