2025年JSP 内置对象request常见用法

JSP 内置对象request常见用法1 访问请求参数 传递参数 login jsp 关键 代码 说明 如果指定的参数不存在 将返回 null 如果指定了参数名 但未指定参数值 将返回空的字符串 因为所有的 request 请求都是 ISO 8859 1 的 而在页面采用的是 utf 8 编码方式 所以在遇到中文时 将获取到的数据通过 String 的构造方法使用指定的编码类型重新构造一个 String 对象 2 在作用域中管理属性

1、访问请求参数

传递参数

login.jsp关键 代码

<%= "name:"+new String(request.getParameter("name").getBytes("ISO-8859-1"),"utf-8") %>

<%= "sex:"+request.getParameter("sex") %>

<%= "id:"+request.getParameter("id") %>

<%= "pwd:"+request.getParameter("pwd") %>

说明:如果指定的参数不存在,将返回null;如果指定了参数名,但未指定参数值,将返回空的字符串”。

因为所有的request请求都是ISO-8859-1的,而在页面采用的是utf-8编码方式,所以在遇到中文时,将获取到的数据通过String的构造方法使用指定的编码类型重新构造一个String对象。

2、在作用域中管理属性

在进行请求转发时,需要把一些数据传递到转发后的页面进行处理,这时,需要用request对象的setAttribute方法将数据保存在request范围内的变量中。

	<%
try {
int money = 100;
int number = 0;
request.setAttribute("result", money / number);
} catch (Exception e) {
request.setAttribute("result", "很抱歉,页面产生错误!");
}
%>

<%= request.getAttribute("result").toString() %>

由于getAttribute方法返回值是Object,需要调用toString方法转换为字符串。

3、获取cookie

cookie是小段文本信息,在网络服务器上生成,并发送给浏览器。通过cookie可以标识用户身份,记录用户名和密码,跟踪重复用户等。以键值对形式保存在客户机的某个目录下。

	<%
Cookie[] cookies = request.getCookies();
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)) {
%>
游客您好,欢迎您初次光临!


<% } else { %>

欢迎
<%=user%> 再次光临



<% }%>

deal.jsp:

	<%
request.setCharacterEncoding("GB18030");
String user = URLEncoder.encode(request.getParameter("user"), "utf-8");
Cookie cookie = new Cookie("mrCookie", user + "#" + new Date().toLocaleString());
cookie.setMaxAge(60 * 60 * 24 * 30);
response.addCookie(cookie);
%>

4、获取客户端信息


客户提交信息的方式:<%=request.getMethod() %>

使用的协议:<%=request.getProtocol() %>

客户端地址:<%=request.getRequestURL() %>

客户端ip地址:<%=request.getRemoteAddr() %>

服务器端口号:<%=request.getServerPort() %>

服务器名称:<%=request.getServerName() %>

客户端主机名:<%=request.getRemoteHost() %>

客户端所请求的脚本文件的文件路径:<%=request.getServletPath() %>

Http协议定义的文件头信息Host的值:<%=request.getHeader("host") %>

Http协议定义的文件头信息User-Agent的值:<%=request.getHeader("user-agent") %>

Http协议定义的文件头信息accept-language的值:<%=request.getHeader("accept-language") %>

请求文件的绝对路径:<%=request.getRealPath("index.jsp") %>

5、显示国际化信息

浏览器可以通过accept-language的HTTP报头向Web服务器指明它所使用的本地语言。java.util.Local类型对象封装了一个国家和国家所使用的一种语言。示例如下:

	<%
Locale locale = request.getLocale();
String str = "";
if (locale.equals(Locale.US)) {
str = "Hello,welcome to access our company's web!";
}
if (locale.equals(Locale.CHINA)) {
str = "您好,欢迎访问我们公司网站!";
}
%>

<%=str%>
编程小号
上一篇 2025-02-13 14:21
下一篇 2025-08-16 08:30

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/144080.html