JSP九大内置对象
所谓内置对象,简单的理解就是不需要new就可以使用的对象
out
request
response
pageContext
session
application
config
page
exception
out
out是输出对象,用于向客户端输出内容
如out.print(“zjj”);
request
request是请求对象,用于储存客户端发送的请求信息
主要方法:
String getParameter(String name)
通过一个key值返回value值,getParameter(“name”)返回"zjj"。
String[] getParameterValues(String name)
通过一个key返回value[ ] ,getParameterValues(“hobby”)返回{“唱”,“跳”,“rap”,“篮球”}。
void setCharacterEncoding(“utf-8”)
用于设置解析 post 请求的编码 ,
getRequestDispatcher(“b.jsp”).forward(request,response)
用于请求转发
1.在执行当前文件的过程中转向执行目标文件,两个文件(当前文件和目标文件)属于同一次请求,前后页共用一个request。
2.不能转向到本web应用之外的页面和网站,所以转向的速度要快。
ServletContext getServletContext()
获取ServletContext对象
questionnaire
问卷页面 questionnaire.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>
<form action = "show.jsp">
你的名字:<input type = "text" name = "name" /><br/>
你的年龄:<input type = "text" name = "age" /><br/>
你的性别:<input type = "radio" name = "sex" value = "男"/>男
<input type = "radio" name = "sex" value = "女"/>女<br/>
你的爱好:<input type = "checkbox" name = "hobby" value = "唱"/>唱
<input type = "checkbox" name = "hobby" value= "跳"/>跳
<input type = "checkbox" name = "hobby" value = "rap"/>rap
<input type = "checkbox" name = "hobby" value = "篮球"/>篮球
<input type = "checkbox" name = "hobby" value = "其他"/>其他<br/>
<input type = "submit" value = "提交" />
</form>
</body>
</html>
展示结果页面show.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("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
String[] hobbies = request.getParameterValues("hobby");
%>
你的名字是:<%= name %><br/>
你的年龄是:<%= age %><br/>
你的性别是:<%= sex %><br/>
<%
out.print("你的爱好是:<br/>");
for(String hobby : hobbies)
{
out.print(hobby+" ");
}
%>
</body>
</html>
结果:
跳转show.jsp的地址栏:
http://localhost:8080/JspProject/show.jsp?name=zjj&age=21&sex=%E7%94%B7&hobby=%E5%94%B1&hobby=%E8%B7%B3&hobby=rap&hobby=%E7%AF%AE%E7%90%83
因为form标签的 method 默认是 get ,可以加上method = “post”.
get post请求
get请求:
会在地址栏显示请求信息 (不安全),地址栏显示信息大小有限(浏览器限制),如果请求信息存在大文件,音频,图片就会报错。
form 默认是get 地址栏访问也是get 超链接也是 get
直接在地址栏输入
http://localhost:8080/JspProject/show.jsp?name=zjj&age=21&sex=%E7%94%B7&hobby=%E5%94%B1&hobby=%E8%B7%B3&hobby=rap&hobby=%E7%AF%AE%E7%90%83
也会跳转到show.jsp页面,和questionnaire.jsp页面无关。
http://xxxx/xxx.jsp?参数1=值1&参数2=值2&…
若是tomcat7及之前的版本,用get请求可能会出现中文乱码,
7之前get编码默认是 iso-8859-1 可以在Servers---->server.xml文件Connector标签加上
URIEncoding = "UTF-8"
或者采用 new String (name.getBytes( “iso-8859-1” ),“utf-8”)一个一个编码
post请求:
理论上容量无限大,上传文件必须用post,地址栏不显示
编码用setCharacterEncoding(“utf-8”)