一.equest对象
1.getParameter()方法,可以用来获取用户提交的数据
2.setAttribute()方法设置数据在request范围内存取
3.在JSP中,可以通过request对象中的getCookies()方法获取cookie中的数据
获取Cookie的方法:
Cookie[] cookie = request.getCookies();
request对象的getCookies()方法,返回的是Cookie[]数组
简单用户登录
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = "";
String pwd = "";
//读取cookie
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
if("username".equals(cookie.getName())){
username = cookie.getValue();
}
if("password".equals(cookie.getName())){
pwd = cookie.getValue();
}
}
%>
<form action="check.jsp" method="post">
用 户 名:<input type="text" name="userName" value="username"/><br/>
用户密码 :<input type="text" name="password" value="pwd"/><br/>
<input type="submit" value="登录"/>
<input type="reset" value="取消"/><br/>
</form>
</body>
</html>
check.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
String name = request.getParameter("userName");
String psw = request.getParameter("password");
if("username".equals(name)&& "pwd".equals(psw)){
Cookie cookie1 = new Cookie("username",name);
Cookie cookie2 = new Cookie("password",psw);
//存储cookie需要设置存活时间 秒
cookie1.setMaxAge(7*24*60*60);
cookie2.setMaxAge(7*24*60*60);
response.addCookie(cookie1);
response.addCookie(cookie2);
session.setAttribute("username", name);
session.setMaxInactiveInterval(1);
response.sendRedirect("success.jsp");
}
else{
response.sendRedirect("error.jsp");
}
%>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>成功页面</title>
</head>
<body>
<%
//String name = request.getParameter("userName");
//String name = (String)session.getAttribute("username");
%>
用户:<%= name %><br>
登录成功
</body>
</html>
error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误页面</title>
</head>
<body>
<p>登录失败</p><br/>
<a href="login.jsp">重新登录</a>
</body>
</html>
4.获取客户信息的方法