java 内置对象 - jhtchina
ava 内置对象
(1) Request请求对象
Request 对象是HttpServletRequest接口的一个事例,接收客户端的各种信息.
事例:
Jsp1.jsp
<div> <p><strong>爱好 (可以多选)</strong> </p> <form name="form1" method="post" action="jsp2.jsp"> <input type="checkbox" name="favorites" value="运动">运动 <input type="checkbox" name="favorites" value="读书">读书 <input type="checkbox" name="favorites" value="音乐">音乐 <input type="checkbox" name="favorites" value="书法">书法 <p><strong>性别</strong> </p> <input type="radio" name="sex" value="男">男 <input type="radio" name="sex" value="女">女 <p><input type="submit" name="Submit" value="提交"> </p> </form> </div>
Jsp2.jsp
<% boolean tag=true; String msg=null; request.setCharacterEncoding("utf-8"); //获得性别 String sex=request.getParameter("sex"); //获得爱好 String[] favorites=request.getParameterValues("favorites"); int len=favorites.length; if (sex==null) { msg="请选择性别"; } else { msg="你选择的性别是:"+sex; } if (len==0) { msg=msg+" 你没有爱好"; tag=false; } msg=msg+"<br> 你的爱好有:"; for (int i=0;i<len;i++) { msg=msg+favorites[i]+"、"; } out.print(msg); %>
String sex=request.getParameter(“sex”);
String[] favorites=request.getParameterValues(“favorites”);
当一个浏览器向Web网站提出页面请求时,首先向服务器发送连接请求,请求内容包括服务器地址,所请求页面路径等.然后服务器将请求响应返回到客户端.在Jsp页面通过Request对象获得响应数据中所包含的相关数据.
(2) Response对象应用
Response对象是javax.servlet.ServletResponse接口中一个针对http协议和实现的子类. Response对象对象包含服务器向客户机作出的信息应答信息.
Response对象响应信息的内容包括:MIME类型的定义,保存的Cookie,连接到Web资源的URL等.
事例1
<h3> <font color="red">当前刷新次数为:<%=count++%> </font> </h3> <h3> 当前时间是:<%=new java.util.Date() %> </h3> <%response.setHeader("Refresh","30"); %>
事例2
<%response.sendRedirect("jsp3.jsp"); %> //页面跳转
(3) `Session 对象应用
事例
session.setAttribute("msg",msg); //设置Session变量 out.print((String)session.getAttribute("msg")); //读取session变量
(4) Application 对象
Application对象保存了一个web应用系统中的一些公用数据,
使用方法和Session类似
(5) Exception 对象
(6) Cookie对象
写cookie事例:
String str = "我们都有一个家,名字叫中国!"; Cookie thisvalue=new Cookie("thisvalue",URLEncoder.encode(str, "UTF-8"));
读cookie事例
Cookie cooktemp[]=request.getCookies(); for (int i=0;i<cooktemp.length;i++) { if (cooktemp[i].getName().equals("thisvalue")) { out.print("Cookie:"); Cookie cooktemp1=cooktemp[i]; //URLEncoder.encode(str, "UTF-8") //out.println(URLDecoder.decode(str, "UTF-8")); out.print(URLDecoder.decode(cooktemp1.getValue(),"UTF-8")); } }