本章导读:
主要内容
request对象
response对象
session对象
out对象
application对象
难点
理解session对象
使用session对象存储数据
目录
4.1request对象
request对象可以通过getParameter()方法获取用户提交的信息,例如通过request.getParameter("username")可以获取提交的用户名。
4.1.1 获取用户提交的信息
request 对象获取用户提交的信息的最常用的方法是getParameter(String s )
下面的example4_2.jsp 通过表单向当前页面提交购物小票,当前页面负责计算购物小票的价格总和。
代码如下
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<%@ page import="java.util.regex.Pattern" %>
<%@ page import="java.util.regex.Matcher" %>
<style>
#tom{
font-family:宋体;font-size:22;color:blue
}
</style>
<HTML><body id ="tom" bgcolor = #ffccff>
输入购物小票内容(显示的是默认内容):
<%
String content = "牛奶:12.68元,面包:6.6元,"
+"苹果:28元,香皂:6.58元";
%>
<form action ="" method="post" id ="tom">
<textArea name="shopping" rows=5 cols=32 id ="tom">
<%= content %>
</textArea>
<input type="submit" id ="tom" name="submit" value="提交"/>
</form>
<% String shoppingReceipt=request.getParameter("shopping");
if(shoppingReceipt==null) {
shoppingReceipt="0";
}
Pattern pattern; //模式对象
Matcher matcher; //匹配对象
String regex="-?[0-9][0-9]*[.]?[0-9]*" ;//匹配数字,整数或浮点数的正则表达式。
pattern = Pattern.compile(regex); //初试化模式对象。
matcher =
pattern.matcher(shoppingReceipt); //matcher检索shoppingReceipt。
double sum = 0;
while(matcher.find()) {
String str = matcher.group();
sum += Double.parseDouble(str);
}
out.print("购物小票消费总额:"+sum);
%>
</body></HTML>
结果如下
tips:如果程序使用了空对象,Java解释器就会提示出现NullPointerReception异常。这个时候就需要使用如下代码:
<% String shoppingReceipt=request.getParameter("shopping");
if(shoppingReceipt==null) {
shoppingReceipt="0";
}
4.1.2 处理汉字信息
JSP页面文件的编码方式为utf-8编码,只要让request对象在获取对象之前调用setCharacterEncoding方法设置编码为utf-8就可以避免乱码的现象。
代码如下(示例):request.setCharacterEncoding("utf-8");
4.1.3 request对象的一些常用方法
我们可以通过下面例题example4_4.jsp学习到常用的方法
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<HTML><body bgcolor = #ffccff>
<p style="font-family:宋体;font-size:36;color:blue">
<% request.setCharacterEncoding("utf-8");
String jsp=request.getServletPath(); //请求的JSP页面
jsp = jsp.substring(1); //去掉JSP页面名称前面的目录符号/
String webDir = request.getContextPath();//获取当前Web服务目录的名称
webDir = webDir.substring(1); //去掉Web服务目录的名称前面的目录符号/
String clientIP=request.getRemoteAddr();//用户的IP地址
int serverPort=request.getServerPort(); // 服务器的端口号
out.print("<br>shenme:"+request.getServerName());
%>
用户请求的页面:<%= jsp %>
<br>Web服务目录的名字:<%= webDir %>
<br>用户的IP地址:<%= clientIP %>
<br>服务器的端口号:<%= serverPort %>
</p></body></HTML>
4.1.4 处理HTML标记
(1) form标记/form表单 :用于对象提交数据
一般格式:
< form action = "请求访问的页面或者servlet" method = get|post>
各种提交手段
提交键
</form>
其中form表单经常把 文本框,下拉列表,滚动列表等作为form表单的子标记
<input ...../>文本框
<select...></select>下拉框
<option...></option>滚动框
(2) input 标记:用来指定form表单中数据的输入方式以及form表单的提交键
基本格式:
<input type = "GUI对象" name = "GUI对象的名字" value= "GUI中的默认值"/>
(3)select,option标记
下拉式列表和滚动列表通过select和option标记来定义,经常作为form的子标记
下拉标记格式:
<select name = "myName">
<option value= "item1">文本描述</option>
<option value= "item2">文本描述</option>
...
</select>
滚动标记格式(在select中增加size属性的值):
<select name = "myName" size= "正整数">
<option value= "item1">文本描述</option>
<option value= "item2">文本描述</option>
...
</select>
example4_6.jsp展示了下拉列表和滚动标记的用法
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<style>
#tom{
font-family:宋体;font-size:26;color:blue
}
</style>
<% String music = request.getParameter("music");
String pic = request.getParameter("pic");
String onOrOff=request.getParameter("R");
if(music==null) music = "";
if(pic==null) pic = "";
if(onOrOff==null) onOrOff = "off";
%>
<HTML><body id=tom background="image/<%= pic %>" >
<form action="" method=post >
<b>选择音乐:<br>
<select id=tom name="music" >
<Option selected value="back1.mp3">绿岛小夜曲
<Option value="back2.mp3">我是一片云</option>
<Option value="back3.mp3">红河谷</option>
</select>
<input type="radio" name="R" value="on" />打开
<input type="radio" name="R" value="off" />关闭
<br><b>选择背景图像:<br>
<select id=tom name="pic" size = 2>
<option value="back1.jpg">荷花图</option>
<option value="back2.jpg">玫瑰图</option>
<option value="back3.jpg">校园图</option>
</select> <br>
<input id=tom type="submit" name="submit" value="提交"/>
</form>
<% if(onOrOff.equals("on")) {
%> <br><embed src="sound/<%= music %>" height=50 />
<% }
%>
</body></HTML>
4.1.5 处理超链接
HTML的超链接标记
<a href = 链接的页面地址> 文字说明</a>
超链接所链接的页面,使用request对象调用getParameter("参数")方法获取超链接参数传递过来的参数的值,即字符串(不允许含有ASCII字符,例如汉字等)。
String idStr = request.getParameter("id")
4.2response对象
1. response对象中的contentType属性是用于设置响应结果的MIME类型,也称为内容类型。例如,设置contentType为"text/html"表示响应结果是HTML文本。可以使用setContentType方法来设置contentType,例如:
response.setContentType("text/html")
2. response对象中的HTTP文件头可以使用setHeader()方法设置,常用的HTTP文件头包括:
Content-Disposition:用于设置响应结果的文件名和下载方式。
Expires:用于设置响应结果的过期时间。
Cache-Control:用于设置缓存控制信息。
Set-Cookie:用于设置Cookie值。
例如,可以通过以下代码设置Content-Disposition文件头:
(response.setHeader("Content-Disposition", "attachment;filename=file1.txt");
这样就可以将响应结果作为文件下载,并指定下载的文件名。 3. response对象中的重定位功能可以通过setHeader()方法设置HTTP响应状态码为302,并设置Location文件头来实现。例如,可以使用以下代码将请求重定向到新的URL:
response.setStatus(302);
response.setHeader("Location", "http://www.example.com/newPage.jsp");
这样就可以将当前请求重定向到http://www.example.com/newPage.jsp。
注意,在使用重定位功能时必须设置HTTP状态码为302,否则可能无法生效。
4.3 session对象
4.3.1seeion对象的id
Session对象的ID:Session ID 是一个由Web服务器生成的唯一标识符,用于标识特定的会话。当客户端与服务器建立连接时,服务器会为该连接生成一个Session ID,并将其存储在浏览器的cookie中。下面是一个获取Session ID 的示例代码:
HttpSession session = request.getSession();
String sessionId = session.getId();
out.println("Your session ID is: " + sessionId);
%>
4.3.2seeion对象与URL重写
Session对象与URL重写:另一种获取Session ID 的方法是使用URL重写。在URL重写中,服务器将Session ID 添加到每个URL中,然后将响应发送回客户端。客户端接收到响应后,将使用包含Session ID 的URL 发送后续请求。下面是一个使用URL重写获取Session ID 的示例代码:
HttpSession session = request.getSession();
String sessionId = session.getId();
String url = response.encodeURL("next.jsp");
out.println("<a href=\"" + url + "\">Click here</a>");
%>
4.3.3seeion对象存储数据
Session对象存储数据:Session对象可以用于在整个会话期间存储和检索数据。可以使用setAttribute() 方法将数据存储在Session对象中,然后使用getAttribute() 方法检索这些数据。下面是一个将用户名和密码存储在Session对象中的示例代码:
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
%>
在上述代码中,我们从请求对象中获取用户名和密码,并使用Session对象将其存储在会话中
4.3.4seeion对象的生存期限
Session对象的生存期限:Session对象有一个生命周期,即在一定时间内,如果没有任何活动,则会自动终止。这个时间可以通过web.xml文件中的session-timeout配置进行设置。例如,下面的代码将Session对象的生存期限设置为60分钟:
<session-config>
<session-timeout>60</session-timeout>
</session-config>
或者,可以使用setMaxInactiveInterval() 方法设置Session对象的生存期限,以秒为单位,如下所示:
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60 * 60); //设置为1小时
%>
在上述代码中,我们使用setMaxInactiveInterval() 方法将Session对象的存在时间为设置为1小时。
4.4 application对象
4.4.1application对象的常用方法
application对象是在JSP中的一个内置对象,代表的是整个Web应用程序。它的常用方法包括:
1. getAttribute(String name):获取指定名字的属性值。2. setAttribute(String name, Object value):设置指定名字的属性值。
3. removeAttribute(String name):删除指定名字的属性值。
4. getInitParameter(String name):获取指定名字的初始化参数值。
5. getServletContext():获取ServletContext对象。
4.4.2application留言板
以下是实现一个application留言板的代码示例,通过使用application对象来存储和获取留言信息:
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %>
<HTML>
<style>
#textStyle{
font-family:宋体;font-size:18;color:blue
}
</style>
<body id='textStyle' bgcolor = #ffccff>
<form action='example4_16_pane.jsp' method='post' >
留言者:<input type='text' name='peopleName' size = 40/>
<br>标题:<input type='text' name='title' size = 42/>
<br>留言:<br>
<textArea name='contents' id='textStyle' rows='10' cols=36 wrap='physical'>
</textArea>
<br><input type='submit' id='textStyle' value='提交留言' name='submit'/>
</form>
<a href='example4_16_show.jsp'>查看留言</a>
<a href='example4_16_delete.jsp'>删除留言</a>
</body></HTML>
结果如下
总结:
在学习本章内容之前我们要先对HTTP协议有一定的了解
从网站获取页面,浏览器在网站上打开一个对网络服务器的连接,并发出请求。服务器收到请求后反应,所以HTTP协议被称为“请求与响应”协议。
综合 以上便是本章的学习内容。