一.request对象
1.超链接的参数传递
<a href “”?id=1>//?可以用来传递参数
<% request.getParameter(“id”) %>//获取传递参数的值,如果要传递多个,参数之间加&即可
2.转发页面值处理
发送:request.setAttribute(name,value);
接收:request.getAttribute(name);
eg:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cul Page</title>
</head>
<body>
<%
try{
int total=100;
int person=0;
request.setAttribute("result", total/person);
}catch(Exception e){
request.setAttribute("result", "抱歉,计算结果错误!");
}
%>
<jsp:forward page="File2.jsp"></jsp:forward>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>63 4
<head>
<meta charset="UTF-8">
<title>Result Page</title>
</head>
<body>
<%=request.getAttribute("result").toString() %>
</body>
</html>
3.获取cookie
cookie是指小段文本信息,通过getName方法可获得名称,getValue可获得值。通常用于记录和获取用户名和密码。
eg:
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Login</title>
</head>
<body>
<%
Cookie[] cookies=request.getCookies();//获取cookie对象
String user="";
String date="";
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("mrCookie")){//通过名字筛选所需要的
user=URLDecoder.decode(cookies[i].getValue().split("#")[0]);
date=cookies[i].getValue().split("#")[1];
}
}
}
if("".equals(user)&&"".equals(date)){//说明没有注册
%>
欢迎初次光临!请输入您的信息!
<form action="File2.jsp" method="post">
请输入姓名:<input name="user" type="text" value="">
<input type="submit" value="确定">
</form>
<%
}
else {
%>
欢迎[<b><%=user%></b>]再次光临<br>
您的注册时间是:<%=date %>
<%
}//一遇到标签语言就要分开
%>
<jsp:forward page="File2.jsp"></jsp:forward>
</body>
</html>
<%@page import="java.net.URLEncoder"%>
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="UTF-8"%>
<%@page import="java.util.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Login Page</title>
</head>
<body>
<%
request.setCharacterEncoding("GB18030");//有中文字符
String user=request.getParameter("user");
user=URLEncoder.encode(user,"utf-8");
Cookie cookie=new Cookie("mrCookie",user+"#"+new Date().toLocaleString());//最后是获取当前时间
cookie.setMaxAge(60*60*24*30);//设置信息最大保留时间
response.addCookie(cookie);
%>
<script type="text/javascript">window.location.href="File1.jsp"</script>
</body>
</html>