Servlet的请求HttpServletRequest
Posted Asu_PC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet的请求HttpServletRequest相关的知识,希望对你有一定的参考价值。
一、从容器到HttpServlet
1、web容器作了什么
web容器做的事情就是,创建Servlet实例,并完成Servlet的名称注册及URL模式的对应。在请求来到时,web容器会转发给正确的Servlet来处理请求。
当请求来到http服务器时,而http服务器转交请求给容器时,容器会创建一个代表档次请求的HttpServletRequest对象,并将请求相关信息设置给该对象。同时,容器会创建一个HttpServletResponse对象,作为稍后要对客户端进行相应的java对象。
接着,容器会根据读取的@webServlet标注或者xml的设置,找出处理该请求的servlet,调用它的service()方法,将创建的HttpServletRequest对象、HttpServletResponse对象传入作为参数,service()方法中会根据HTTP请求的方式,调用对应的doXXX()方法。接着再doXXX()方法中,可以使用request、resposne对象,如:getParameter()取得请求参数,使用getWriter()取得输出用的PrintWriter对象,并进行各项响应处理。对PrintWriter做的输出操作,最后由容器转换为HTTP响应,再由HTTP服务器对浏览器响应。之后容器将对象销毁。
2、关于HttpServletRequest
2.1 处理请求参数与标头
String username = request.getParameter("name");指定请求参数名称来取得对应的值。如果传来的是"123"这样的字符串值,必须使用Integer.parseInt()这类方法剖析为基本类型。
String[] values = request.getParameterValues("param");就像param=10¶m=20¶m=30,此时用getParameterValues()取得一个String数组。
如果想要知道请求中有多少请求参数,则可以使用getParameterNames()方法,会返回一个Enumeration对象。
Enumeration<String> e = request.getParameterNames();
while(e.hasMoreElements()){
String param = e.nextElement();
...
}
对于HTTP标头的信息(Header),可以通过以下方法取得:
1、getHeader():使用方式与getParameter类似。
2、getHeaders():与getParameterValues类似。
3、getHeaderNames():与getParameterNames类似。
以下的实例如何取得并显示浏览器送出的标头信息。
1 package cc.openhome; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Enumeration; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class HeaderServlet 15 */ 16 @WebServlet("/header.view") 17 public class HeaderServlet extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public HeaderServlet() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 28 /** 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 */ 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 // TODO Auto-generated method stub 33 PrintWriter out=response.getWriter(); 34 out.println("<html>"); 35 out.println("<head>"); 36 out.println("<title>HeadServlet</title>"); 37 out.println("</head>"); 38 out.println("<body>"); 39 out.println("<h1>HeaderServlet at "+request.getContextPath()+"</h1>");//取得应用程序环境路径 40 Enumeration<String> names=request.getHeaderNames();//取得所有标头名称 41 while(names.hasMoreElements()){ 42 String name=names.nextElement(); 43 out.println(name+": "+request.getHeader(name)+"<br>");//输出所有的标头值 44 } 45 out.println("</body>"); 46 out.println("</html>"); 47 out.close(); 48 } 49 50 /** 51 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 52 */ 53 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 54 // TODO Auto-generated method stub 55 } 56 57 }
运行结果:
2.2 getReader()、getInputStream()读取Body内容
getReader()方法,可以取得一个BufferedReader对象,可以读取Body数据。
例子1:读取请求Body内容
1 package cc.openhome; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.PrintWriter; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class BodyServlet 15 */ 16 @WebServlet("/body.view") 17 public class BodyServlet extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public BodyServlet() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 28 /** 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 */ 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 // TODO Auto-generated method stub 33 34 } 35 36 private String readBody(HttpServletRequest request) throws IOException { 37 // TODO Auto-generated method stub 38 BufferedReader reader=request.getReader();//取得BufferedReader对象 39 String input=null; 40 String requestBody=""; 41 while((input=reader.readLine())!=null){ 42 requestBody=requestBody+input+"<br>"; 43 } 44 return requestBody; 45 } 46 47 /** 48 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 49 */ 50 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 51 // TODO Auto-generated method stub 52 String body=readBody(request); 53 PrintWriter out=response.getWriter();//取得响应输出对象 54 out.println("<html>"); 55 out.println("<head>"); 56 out.println("<title>Servlet BodyView</title>"); 57 out.println("</head>"); 58 out.println("<body>"); 59 out.println(body); 60 out.println("</body>"); 61 out.println("</html>"); 62 out.close(); 63 } 64 65 }
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <form action="body.view" method="post"> 9 名称:<input type="text" name="user"><br> 10 密码:<input type="password" name="passwd"><br><br> 11 <input type="submit" name="login" value="送出"> 12 </form> 13 </body> 14 </html>
在名称字段上输入“良葛格”,密码上输入“123456”,单机送出按钮,得到:
2.3 getPart()、getParts()取得上传文件
Servlet3.0中,新增了Part接口,可以方便进行文件上传处理。可以通过request对象的getPart()方法取得Part对象。
例1:上传文件到指定目录。
1 package cc.openhome; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.MultipartConfig; 10 import javax.servlet.annotation.WebServlet; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.servlet.http.Part; 15 16 17 /** 18 * Servlet implementation class PhotoServlet 19 */ 20 @MultipartConfig(location="e:/java web/workspace/")//设置location属性 21 @WebServlet("/photo.do") 22 public class PhotoServlet extends HttpServlet { 23 private static final long serialVersionUID = 1L; 24 25 /** 26 * @see HttpServlet#HttpServlet() 27 */ 28 public PhotoServlet() { 29 super(); 30 // TODO Auto-generated constructor stub 31 } 32 33 /** 34 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 35 */ 36 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 37 // TODO Auto-generated method stub 38 } 39 40 /** 41 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 42 */ 43 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 44 // TODO Auto-generated method stub 45 request.setCharacterEncoding("UTF-8"); 46 Part part=request.getPart("photo"); 47 String filename=getFilename(part); 48 //writeTo(filename,part); 49 part.write(filename);//将文件写入location的指定目录 50 } 51 52 // private void writeTo(String filename, Part part) throws IOException { 53 // // TODO Auto-generated method stub 54 // InputStream in=part.getInputStream(); 55 // OutputStream out=new FileOutputStream("e:/java web/workspace/"+filename); 56 // byte[] buffer=new byte[1024]; 57 // int length=-1; 58 // while((length=in.read(buffer))!=-1){ 59 // out.write(buffer,0,length); 60 // } 61 // in.close(); 62 // out.close(); 63 // } 64 65 private String getFilename(Part part) { 66 // TODO Auto-generated method stub 67 String header=part.getHeader("Content-Disposition"); 68 String filename=header.substring(header.indexOf("filename=\\"")+10,header.lastIndexOf("\\"")); 69 return filename; 70 71 } 72 73 }
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" > 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <form action="photo.do" method="post" enctype="multipart/form-data"> 9 上传相片:<input type="file" name="photo" value="" /><br> 10 <input type="submit" name="upload" value="上传"> 11 </form> 12 </body> 13 </html>
在Tomcat中必须设置@MultipartConfig标注才能使用getPart()相关API。@MultipartConfig也可以设置属性,比如location。@MultipartConfig(location="c:/workspace"),则上例子就可以修改为:
1 package cc.openhome; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.MultipartConfig; 10 import javax.servlet.annotation.WebServlet; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.servlet.http.Part; 15 16 17 /** 18 * Servlet implementation class PhotoServlet 19 */ 20 @MultipartConfig(location="e:/java web/workspace/")//设置location属性 21 @WebServlet("/photo.do") 22 public class PhotoServlet extends HttpServlet { 23 private static final long serialVersionUID = 1L; 24 25 /** 26 * @see HttpServlet#HttpServlet() 27 */ 28 public PhotoServlet() { 29 super(); 30 // TODO Auto-generated constructor stub 31 } 32 33 /** 34 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 35 */ 36 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 37 // TODO Auto-generated method stub 38 } 39 40 /** 41 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 42 */ 43 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 44 // TODO Auto-generated method stub 45 request.setCharacterEncoding("UTF-8"); 46 Part part=request.getPart("photo"); 47 String filename=getFilename(part); 48 //writeTo(filename,part); 49 part.write(filename);//将文件写入location的指定目录 50 } 51 52 // private void writeTo(String filename, Part part) throws IOException { 53 // // TODO Auto-generated method stub 54 // InputStream in=part.getInputStream(); 55 // OutputStream out=new FileOutputStream("e:/java web/workspace/"+filename); 56 // byte[] buffer=new byte[1024]; 57 // int length=-1; 58 // while((length=in.read(buffer))!=-1){ 59 // out.write(buffer,0,length); 60 // } 61 // in.close(); 62 // out.close(); 63 // } 64 65 private String getFilename(Part part) { 66 // TODO Auto-generated method stub 67 String header=part.getHeader("Content-Disposition"); 68 String filename=header.substring(header.indexOf("filename=\\"")+10,header.lastIndexOf("\\"")); 69 return filename; 70 71 } 72 73 }
如果有多个文件要上传,可以使用getParts方法,这回返回一个Collection<Part>,其中是每个上传文件的part对象。
例子2:上传多个文件
1 package cc.openhome; 2 3 import java.io.DataInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.UnsupportedEncodingException; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 15 16 /** 17 * Servlet implementation class UploadServlet 18 */ 19 @WebServlet("/upload.do") 20 public class UploadServlet extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 /** 24 * @see HttpServlet#HttpServlet() 25 */ 26 public UploadServlet() { 27 super(); 28 // TODO Auto-generated constructor stub 29 } 30 31 /** 32 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 33 */ 34 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 35 // TODO Auto-generated method stub 36 } 37 38 /** 39 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 40 */ 41 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 42 在 servlet 中获取请求 url 的一部分