Jsp内置对象
Requset,当客户端请求一个jsp页面的时候,jsp页面所在的服务器端将客户端发出的所有请求信息封装在内置对象request中,因此用该对象可以获得客户端提交的信息
方法:
Void setAttribute(String key,Object obj)设置属性的属性值
Object getAttribute(String name)返回指定属性的属性值
String getParameter(String name)返回name指定的参数的参数值
String[] getParameterValues(String name)返回包含参数name的所有值的数组
举个例子:
这是NewFile1,NewFile文件
<%@ 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>
<form action="NewFile.jsp">
admin:<input type="text" name="admin"/></br>
</br>
password:<input type="text" name="password"/>
<input type="submit" value="点我"/>
</form>
</body>
</html>
<%@ 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 name = request.getParameter("admin");
String password = request.getParameter("password");
out.println(name);
out.println(password);
%>
</body>
</html>
response对象对客户端的请求做出动态响应,通常为改变contenttype属性值,设置响应表头和respon重定向
改变ontenttType属性值:
setContentType(String s)
<%@ 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>
<form action="">
<input type="submit" value="wendang" name="submit">
<input type="submit" value="excel" name="submit">
</form>
<%
String a = request.getParameter("submit");
if("wendang".equals(a)){
response.setContentType("application/msword");
}else if("excel".equals(a)){
response.setContentType("application/vnd.ms-excel");
}
%>
</body>
</html>
setHeader(String name,String value)
response.setHeader("refresh","3");3秒刷新一次
response.setHeader("refresh","3;url=another.jsp");3秒后跳转到another页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ page import="java.util.Calendar" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<%
Calendar c = Calendar.getInstance();
out.print(c.get(Calendar.SECOND));
response.setHeader("refresh", "3");
%>
</body>
</html>
c.get(Calendar.SECOND)
:获取Calendar
对象c
中的当前秒数。"" + c.get(Calendar.SECOND)
:将获取到的秒数转换为字符串。这是因为out.print
方法期望一个字符串参数,所以这里使用了字符串连接操作将整型秒数转换为字符串。out.print(...)
:这是PrintWriter
对象的一个方法,用于将字符串发送到客户端(通常是浏览器)。在这个上下文中,out
通常是HttpServletResponse
的输出流。
sendRedirect(String url)实现重定向
<%@ 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>
<form action="">
<input type="submit" value="wendang" name="submit">
<input type="submit" value="excel" name="submit">
</form>
<%
String a = request.getParameter("submit");
if("wendang".equals(a)){
response.sendRedirect("NewFile.jsp");
}else if("excel".equals(a)){
response.setContentType("application/vnd.ms-excel");
}
%>
</body>
</html>