通过<%=request.getContextPath() %>
可以将项目名写活,这样,即使项目名变了,仍可以运行。
request代码每一次请求的容器。浏览器每次请求都是一个新的request对象。因此放在request里面的属性request.getAttribute()
是空的,上一个request放的属性request.setAttribute()
是上一个的。与这次无关。但如果是转发的时候,那么request对象是共享的。这种情况下,两次的request是同一个。这种情况下,里面的属性可以共用的。
setCharacterEncoding()和getCharacterEncoding()
setCharacterEncoding()
只对post请求方式有效,因为它只设置请求体(正文)中内容的读取编码
如果不设置setCharacterEncoding(),那么默认的request.getCharacterEncoding()
是iso8859-1 返回的是null
getContentType()
如果是get提交则返回null
如果是post方式提交则返回:application/x-www-form-urlencoded
通过getMethod()判断请求方式,同时演示GET方式下的中文乱码解决
tomcat直接用iso8859-1解码,属于解码错误,如果非要用这种方式传中文,那么先还原再编码:
name = new String(name.getBytes("iso8859-1"),"utf-8");
注意,在get方式下的中文乱码解决不可靠。–如果避不开,那么就明确告诉用户,要使用什么浏览器访问!因为有的浏览器支持,而有的浏览器不支持。以上例子就有ie不支持,360支持。
获取客户端的国际化信息—浏览器Internet选项中设置的语言环境—-request.getLocale()
local.getCountry()
local.getDisplayCountry()
local.getDisplayLanguage()
local.getDisplayName()
参数接受–表单参数接受
单个参数值
request.getParameter("name");
多个参数值
方法1:
String hoby[]=request.getParameterValues("hoby");//如果某个参数的值有好几个,用这个方法
if (hoby!=null) {
for (String str : hoby) {
out.print( "<br/>"+str);
System.out.println(str);
}
}
方法2:一次将所有表单参数封装到map中,然后通过操纵map拿值
//演示getParameterMap()
Map<String, String[]> map = request.getParameterMap();
////遍历出所有参数及值
Iterator<Entry<String, String[]>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String, String[]> en = it.next();
String key = en.getKey();
String[] value = en.getValue();
out.println("参数名称:"+key);
for(String v:value){
out.print("参数值:"+v+" ");
}
}
获取客户端的ip和端口号
String ip= request.getRemoteHost();
int port = request.getRemotePort();
out.print("<br>"+ip+":"+port);
request.getQueryString()
request.getQueryString()是将get方式提交的请求地址 ? 后面的都封装成一个字符串。
文件上传
简易版:手动处理文件上传
在<form>
中加入属性:enctype="multipart/form-data"
这样拿到的就是多段字符串。而不是一个文件名。但是这种手动上传很麻烦,要自己去解析。我们在下一篇博客文章中使用阿帕奇公司-Commons-io.jar 和 Commos-fileupload.jar写好的去做文件上传
本文完整代码如下:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>演示request和response用法</title>
</head>
<body>
<!--通过request.getContextPath()可以把项目根目录(项目名)写活 -->
<form action="<%=request.getContextPath() %>/requestDemo" method="post">
姓名:<input type="text" name="name" /><br/>
<input type="submit" value="提交"/>
</form>
<!-- 演示表单参数的接受 -->
<form action="<%=request.getContextPath() %>/param" method="post">
姓名:<input type="text" name="name" /><br/>
年龄:<input type="text" name="age" /><br/>
<input type="checkbox" name="hoby" value="music" />音乐
<input type="checkbox" name="hoby" value="tv" />电视
<input type="checkbox" name="hoby" value="game" />游戏<br/>
<input type="radio" name="sex" value="0" checked="checked" >男
<input type="radio" name="sex" value="1">女
<input type="submit" value="提交"/>
</form>
<!-- 演示文件上传 -->
<h2>文件上传手动版</h2>
<form action="<%=request.getContextPath() %>/upload1" method="post" enctype="multipart/form-data">
文件名:<input type="file" name="fileName">
<input type="submit" value="上传">
</form>
<!-- 上面这种手动上传 的方法不好。要自己解析,麻烦,我们用阿帕奇公司-Commons-io.jar 和 Commos-fileupload.jar写好的去做文件上传 -->
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<servlet-name>RequestDemo</servlet-name>
<servlet-class>cn.hncu.servlets.RequestDemo</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Hello</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>ParamerServlet</servlet-name>
<servlet-class>cn.hncu.servlets.ParamerServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UpFileServlet</servlet-name>
<servlet-class>cn.hncu.servlets.UpFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RequestDemo</servlet-name>
<url-pattern>/requestDemo</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ParamerServlet</servlet-name>
<url-pattern>/param</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UpFileServlet</servlet-name>
<url-pattern>/upload1</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
RequestDemo
package cn.hncu.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestDemo extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(request);
//每一次请求,request对象是新的,因此这里读取的属性是null,因为之前放进去的属性是属于另一个request对象
//如果是转发,那么request对象是共享的即是同一个,这种情况下,里面的属性可以共用
int num = new Random().nextInt(200);
if(request.getAttribute("name")==null){
System.out.println("放入:"+num);
request.setAttribute("name", num);
}
//setCharacterEncoding()只对post请求方式有效,因为它只设置请求体(正文)中内容的读取编码
//以下演示setCharacterEncoding()和getCharacterEncoding()
request.setCharacterEncoding("utf-8");
String character = request.getCharacterEncoding();//utf-8
//如果没有设置的话 默认的request.getCharacterEncoding()是iso8859-1 返回的是null
// String character = request.getCharacterEncoding();//null
System.out.println(character);
//以下演示getContentType()----如果是get提交则返回null,
//如果是post方式提交则返回:application/x-www-form-urlencoded
String contextType = request.getContentType();
System.out.println(contextType);//application/x-www-form-urlencoded
//下面演示通过getMethod()判断请求方式,同时演示GET方式下的中文乱码解决--
//注意,不可靠!!!--如果避不开,那么就明确告诉用户,要使用什么浏览器访问!
String name = request.getParameter("name");
if(request.getMethod().equals("GET")){
System.out.println("DOGET...");
name = new String(name.getBytes("iso8859-1"),"utf-8");
System.out.println(name);
out.print("<br/>name:"+name);
}
//获取客户端的国际化信息---浏览器Internet选项中设置的语言环境
Locale local = request.getLocale();
out.println("<br/>Country:"+local.getCountry());//Country:CN
out.println("<br/>DisplayCountry:"+local.getDisplayCountry());//DisplayCountry:中国
out.println("<br/>DisplayLanguage:"+local.getDisplayLanguage());//DisplayLanguage:中文
out.println("<br/>DisplayName:"+local.getDisplayName());//DisplayName:中文 (中国)
out.println("<br/>"+request.getAttribute("name"));
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
ParamerServlet
package cn.hncu.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ParamerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
String name = request.getParameter("name");//读取单个参数值
String age = request.getParameter("age");
out.println("name:"+name);
out.println("age:"+age);
String hoby[]=request.getParameterValues("hoby");//如果某个参数的值有好几个,用这个方法
if (hoby!=null) {
for (String str : hoby) {
out.print( "<br/>"+str);
System.out.println(str);
}
}
String sex = request.getParameter("sex");
if ("1".equals(sex)) {
out.print("<br/>女" );
}else{
out.print("<br/>男" );
}
System.out.println("sex="+sex);
//演示getParameterMap()
Map<String, String[]> map = request.getParameterMap();
////遍历出所有参数及值
Iterator<Entry<String, String[]>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String, String[]> en = it.next();
String key = en.getKey();
String[] value = en.getValue();
out.println("参数名称:"+key);
for(String v:value){
out.print("参数值:"+v+" ");
}
}
////获取客户端的ip和端口号
String ip= request.getRemoteHost();
int port = request.getRemotePort();
out.print("<br>"+ip+":"+port);
String queryStr= request.getQueryString();
out.println("queryStr:"+queryStr);
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
UpFileServlet
package cn.hncu.servlets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
InputStream in = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line=br.readLine())!=null){
System.out.println(line);
}
}
}
时间: 2024-10-09 23:58:47