web服務(wù)器收到客戶端的HTTP請(qǐng)求,會(huì)針對(duì)每一次請(qǐng)求分別創(chuàng)建一個(gè)用于代表請(qǐng)求的request對(duì)象和代表響應(yīng)的response對(duì)象。
1.要得到客戶機(jī)提交過來的數(shù)據(jù),只需要找request對(duì)象就行了。
2、要向客戶機(jī)輸出數(shù)據(jù),只需要找response對(duì)象就行了。
一、response對(duì)象
1.1向客戶端發(fā)送數(shù)據(jù),以字節(jié)為單位(一定要先設(shè)置編碼方式,再輸出)
- String data = "你好,中國(guó)1";
- OutputStream out = response.getOutputStream();
- out.write(data.getBytes());//查找本機(jī)默認(rèn)編碼進(jìn)行編碼
- String data = "你好,中國(guó)2";
- OutputStream out = response.getOutputStream();
- out.write(data.getBytes("UTF-8"));//以UTF-8進(jìn)行編碼
- //告訴瀏覽器編碼方式
- response.setHeader("Content-Type","text/html;charset=UTF-8" );
- String data = "你好,中國(guó)3";
- OutputStream out = response.getOutputStream();
- out.write("<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>".getBytes());////通過meta標(biāo)簽?zāi)M請(qǐng)求頭
- out.write(data.getBytes("UTF-8"));//以UTF-8進(jìn)行編碼
- String data = "你好,中國(guó)4";
- OutputStream out = response.getOutputStream();
- response.setContentType("text/html;charset=UTF-8");
- out.write(data.getBytes("UTF-8"));//以UTF-8進(jìn)行編碼
- response.setContentType("text/html;charset=UTF-8");
等價(jià)于下面兩句代碼的效果:
response.setCharacterEncoding("UTF-8");//更改服務(wù)器發(fā)送數(shù)據(jù)的默認(rèn)編碼
response.setHeader("Content-Type","text/html;charset=UTF-8");//還要通知客戶端解碼方式
- int x=97;
- OutputStream out = response.getOutputStream();
- out.write((x+"").getBytes());////向客戶端發(fā)送數(shù)字
1.2 以字符為單位向客戶端發(fā)送數(shù)據(jù)
String data = "你是誰?";
response.setCharacterEncoding("UTF-8"); //設(shè)置編碼為UTF-8
response.setHeader("Content-Type", "text/html;charset=UTF-8");//告訴客戶端編碼方式
// 第二種方法:相當(dāng)于以上兩句代碼
//response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();//默認(rèn)編碼是iso-8859-1 創(chuàng)建該對(duì)象前必須設(shè)置好編碼方式
writer.write(data);
System.out.println(response.getCharacterEncoding());
1.3 讓客戶端以下載方式打開文件,解決中文文件名亂碼問題(URLEncoder.encode(name, "UTF-8"))
- //得到文件的真實(shí)路徑
- String realPath = getServletContext().getRealPath("/files/漂亮美眉.jpg");
- //獲取文件名
- String name = realPath.substring(realPath.lastIndexOf("\\"));
-
- //設(shè)置響應(yīng)頭,通知客戶端以下載的方式打開文件
- response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(name, "UTF-8"));
-
- //構(gòu)建輸入流
- InputStream in = new FileInputStream(realPath);
-
- //輸出到客戶端的流
- OutputStream out = response.getOutputStream();
- int len = -1;
- byte buf[] = new byte[1024];
- while((len=in.read(buf))!=-1)
- {
- out.write(buf, 0, len);
- }
-
- in.close();
1.4 輸出隨機(jī)數(shù)字生成驗(yàn)證碼圖片
- //設(shè)置不要緩存(3種方式,建議三種都設(shè)置,防止瀏覽器不支持)
- response.addHeader("Pragma", "no-cache");
- response.setHeader("Cache-Control", "no-cache");
- response.setHeader("Expires", "0");
-
- //1.內(nèi)存圖像 BufferedImage
- BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
-
- //2.創(chuàng)建畫筆
- Graphics g = image.getGraphics();
-
- //2.1畫邊框
- g.setColor(Color.GRAY);//設(shè)置邊框顏色
- g.drawRect(0, 0, WIDTH, HEIGHT);//畫矩形邊框
- //2.2填充邊框
- g.fillRect(1, 1, WIDTH-1, HEIGHT-1);
-
- //2.3輸出驗(yàn)證隨機(jī)數(shù)字4個(gè)
- Random r = new Random();
- g.setColor(Color.BLUE);
- int x = 5;
- for(int i=0;i<4;i++)
- {
-
- g.setFont(new Font("宋體",Font.BOLD,20));
- g.drawString(r.nextInt(10)+"", x, 20);
- x+=30;
- }
-
- //2.4畫干擾線
- g.setColor(Color.YELLOW);
- for(int i = 0;i<9;i++)
- {
-
- g.drawLine(r.nextInt(WIDTH),r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
- }
-
- //3 利用response輸出流輸出image
- ImageIO.write(image,"jpeg",response.getOutputStream());<pre name="code" class="java"> //response.setHeader("Expires", (System.currentTimeMillis()+24*3600*10*1000)+"");//緩存10天
- response.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);</pre><br>
- <pre></pre>
- <p></p>
- <pre></pre>
- 1.5 控制客戶端刷新時(shí)間
- <p></p>
- <p></p>
- <pre name="code" class="java"> //response.setHeader("Refresh", "5;URL=/day05/default.html");//5秒后跳轉(zhuǎn),url是跳轉(zhuǎn)的鏈接
- response.getOutputStream().write("<meta http-equiv=\"Refresh\" content=\"3;URL=/day05/login.html\">".getBytes());</pre>1.6 控制客戶端緩存時(shí)間
- <p></p>
- <p></p>
- <pre name="code" class="java"> //response.setHeader("Expires", (System.currentTimeMillis()+24*3600*10*1000)+"");//緩存10天
- response.setDateHeader("Expires",System.currentTimeMillis()+10*24*1000*60*60);</pre><br>
- 1.7 用response實(shí)現(xiàn)請(qǐng)求重定向
- <p></p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_13292204202s0e.gif" alt=""></p>
- <p>特點(diǎn):地址欄會(huì)變,發(fā)送兩次請(qǐng)求,增加服務(wù)器負(fù)擔(dān)。</p>
- <p>實(shí)現(xiàn)方式:response.sendRedirect()<br>
- 實(shí)現(xiàn)原理:302狀態(tài)碼和location頭即可實(shí)現(xiàn)重定向<br>
- </p>
- <pre name="code" class="java"> //response.sendRedirect("/day05/servlet/ResponseDemo5");//絕對(duì)路徑
- 注意 // response.sendRedirect("/servlet/ResponseDemo5");//相對(duì)路徑這里用是錯(cuò)誤的,因?yàn)橹囟ㄏ蚴怯煽蛻舳税l(fā)起的
- response.setStatus(307);//302 或者 307都可
- response.setHeader("location", "http://localhost:8080/day05/servlet/ResponseDemo1");</pre><br>
- 1.8 小細(xì)節(jié)
- <p></p>
- <p></p>
- <pre name="code" class="java"> String s1 = "abc";
- String s2 = "def";
- response.getOutputStream().write(s1.getBytes());
- //response.getWriter().write(s2);
- //注:getOutputStream和getWriter這兩個(gè)方法互相排斥,
- //調(diào)用了其中的任何一個(gè)方法后,就不能再調(diào)用另一方法,會(huì)拋異常。
- //java.lang.IllegalStateException:
- //getOutputStream() has already been called for this response</pre><br>
- <p><br>
- </p>
- <p>二、request(HttpServletRequest)對(duì)象</p>
- <p>2.1.get方法</p>
- <p></p><pre name="code" class="java"> String locale = request.getLocalName();//傳輸協(xié)議
- String url = request.getRequestURL().toString();//請(qǐng)求的地址
- String uri = request.getRequestURI();//沒有主機(jī)名的地址
- String protocol = request.getProtocol();//獲取協(xié)議
- String add = request.getRemoteAddr();//客戶端IP
- String host = request.getRemoteHost();//客戶端主機(jī)名
- String port = request.getRemotePort()+"";//客戶端端口號(hào)
- String method = request.getMethod();//客戶端的請(qǐng)求方式
- String localAddr = request.getLocalAddr();//獲取服務(wù)器地址
- String username = request.getParameter("username");//地址后面?請(qǐng)求的參數(shù)
- String serverPort = request.getServerPort()+"";//服務(wù)器端口號(hào)
- String serverName = request.getServerName();//服務(wù)器名</pre><br>
- 2.2 獲取客戶端請(qǐng)求頭<p></p>
- <p></p><pre name="code" class="java"> response.setContentType("text/html;charset=UTF-8");
-
- PrintWriter out = response.getWriter();
- //獲取單個(gè)請(qǐng)求頭的值
- out.write(request.getHeader("Accept-Language")+"<br/>");
- //獲取單個(gè)請(qǐng)求頭多個(gè)值
- Enumeration headers = request.getHeaders("user-agent");
- while(headers.hasMoreElements())
- {
- out.println(headers.nextElement()+"<hr/>");
- }
-
- //獲取所有的請(qǐng)求頭名
- Enumeration names = request.getHeaderNames();
- while(names.hasMoreElements())
- { //根據(jù)請(qǐng)求頭名得到對(duì)應(yīng)的值
- String name = (String)names.nextElement();
- out.println(name+"="+request.getHeader(name)+"<br/>");
- }</pre><br>
- 2.3獲取請(qǐng)求參數(shù)<p></p>
- <p>String usernameValue = request.getParameter("username");//參數(shù)不存在為null<br>
- </p>
- <p></p><pre name="code" class="java">String names[] = request.getParameterValues("username");
- for(String name:names)
- {
- System.out.println(name);////得到某個(gè)請(qǐng)求參數(shù)的所有值
-
- }</pre><pre name="code" class="java"> //獲取所有的請(qǐng)求參數(shù)名
-
- Enumeration names = request.getParameterNames();
- while(names.hasMoreElements())
- { //根據(jù)參數(shù)名得到值
- String name = (String)names.nextElement();
- System.out.println(name+"------->"+request.getParameter(name));
- }</pre><br>
- 2.4 封裝到bean<br>
- <pre name="code" class="java">public class Student {
- private String[] username;
- private String password;
-
- public String[] getUsername() {
- return username;
- }
- public void setUsername(String[] username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
-
-
- }
-
- </pre><pre name="code" class="java">//利用BeanUtils和 getParameterMap()將對(duì)象封裝到bean
- private void test5(HttpServletRequest request) {
- // TODO Auto-generated method stub
- Map map = request.getParameterMap();
- Student s = new Student();
- try {
- BeanUtils.populate(s, map);
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- String[] names = s.getUsername();
- System.out.println(names[0]);//aa
- System.out.println(names[1]);//bb
- System.out.println(s.getPassword());//123
- }//從客戶端傳過來的值username兩個(gè)(假如是aa和bb) 和一個(gè)password值(假如是123)</pre><br>
- 2.5 得到請(qǐng)求正文<br>
- <pre name="code" class="java"> //獲取請(qǐng)求正文
- InputStream in = request.getInputStream();
- byte[] buf =new byte[1024];
- int len = -1;
- while((len=in.read(buf))!=-1)
- {
- System.out.println(new String(buf,0,len));
- }</pre><br>
- 2.6解決請(qǐng)求參數(shù)的中文亂碼<p></p>
- <p> get方式:先按照原編碼得到原始字節(jié)碼,然后再重新編碼。如:name = new String(name.getBytes("ISO-8859-1"),"UTF-8");</p>
- <p>post方式:客戶端是什么編碼,發(fā)送的請(qǐng)求數(shù)據(jù)就是什么編碼,根據(jù)客戶端的編碼,告知服務(wù)器編碼方式。</p>
- <p>如:request.setCharacterEncoding("UTF-8");// 只適合POST請(qǐng)求方式</p>
- <p><br>
- </p>
- <p>2.7請(qǐng)求轉(zhuǎn)發(fā) forward</p>
- <p><span style="white-space:pre"></span>RequestDispatcher rd = request.getRequestDispatcher("path");//得到轉(zhuǎn)發(fā)器,path可以是相對(duì)路徑或者絕對(duì)路徑(因?yàn)槭欠?wù)器發(fā)起的)<br>
- <span style="white-space:pre"></span>rd.forward(request, response);<br>
- </p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_1329238218CM8E.gif" alt=""><br>
- </p>
- <p>2.8 包含include</p>
- <p><span style="white-space:pre"></span>RequestDispatcher rd = request.getRequestDispatcher("/servlet/RequestDemo9");<br>
- <span style="white-space:pre"></span>rd.include(request, response);<br>
- </p>
- <p><img src="http://hi.csdn.net/attachment/201202/14/0_1329238034rHHG.gif" alt=""><br>
- </p>
- <p>三 、路徑的寫法:<br>
- a、絕對(duì)路徑寫法:ServeltContext都必須用絕對(duì)路徑?!?”開始 (如ServletContext.getRequestDispatcher("path") path必須是絕對(duì)路徑)<br>
- b、相對(duì)路徑:其他情況都可以使用相對(duì)路徑,也可以使用絕對(duì)路徑<br>
- <br>
- <br>
- c、在使用絕對(duì)路徑時(shí),要不要加"/"或者是項(xiàng)目名:如果是服務(wù)器調(diào)用的,不用加項(xiàng)目名,用“/”就可以代表了當(dāng)前應(yīng)用根目錄<br>
- 如果是客戶端調(diào)用的,必須加上項(xiàng)目名<br>
- <br>
- <br>
- 1、轉(zhuǎn)發(fā):request.getRequestDispather(String url)<br>
- 絕對(duì)路徑:url /servlet/ServletDemo<br>
- 2、重定向:response.sendRedirect(String url)<br>
- 絕對(duì)路徑:url /day05/servlet/ServletDemo<br>
- <br>
- <br>
- 3、超鏈接:<a href="url"/><br>
- 絕對(duì)路徑:url /day05/servlet/ServletDemo<br>
- 4、類加載文件的路徑<br>
- web應(yīng)用中只能用相對(duì)路徑,相對(duì)于classes目錄的<br>
- 5、<fomr action="url"/><br>
- 絕對(duì)路徑:/day05/servlet/ServletDemo<br>
- 6、頁面分幀(frame)<br>
- 絕對(duì)路徑:/day05/servlet/ServletDemo<br>
- 7、ServletContext.getRealPath(url)<br>
- 絕對(duì)路徑:url /servlet/ServletDemo<br>
- <br>
- <br>
- URLEncoder.encode("name", "UTF-8")//解決文件下載名中文亂碼</p>
- <p><br>
- </p>
- <p></p>
-
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。