Servlet——HttpServletRequest、HttpServletResponse

HttpServletRequest对象

 

 

  范例:

package com.zgy.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class TestRequestServlet extends HttpServlet{

 

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

testGetNetInfo(req);

testGetURL(req,resp);

testGetHeader(req,resp);

testGetParameter(req);

}

void testGetNetInfo(HttpServletRequest req){

System.out.println("客户端的IP:"+req.getRemoteAddr());

System.out.println("客户端的Port:"+req.getRemotePort());

System.out.println("服务器IP:"+req.getLocalAddr());

}

void testGetURL(HttpServletRequest req, HttpServletResponse resp) throws IOException{

PrintWriter out = resp.getWriter();

out.println("请求方式:"+req.getMethod()+"<br />");

out.println("协议:"+req.getScheme()+"<br />");

out.println("web应用的目录:"+req.getContextPath()+"<br />");

out.println("URI:"+req.getRequestURI()+"<br />");

}

void testGetHeader(HttpServletRequest req,HttpServletResponse resp){

String str = req.getHeader("Accept-Language");

System.out.println("Accept-Language"+str);

Enumeration e = req.getHeaderNames();

while(e.hasMoreElements()){

System.out.println(e.nextElement());

}

}

void testGetParameter(HttpServletRequest req){

String u = req.getParameter("uname");

String p = req.getParameter("upass");

System.out.println("uname="+u);

System.out.println("upass="+p);

}

}


六、HttpServletResponse对象

1、响应信息的构成

a) response.getWriter()//输出文本信息

b) response.getOutputStream()//输出非文本信息

 

2、HttpServletResponse对象获取的打印流是同一个对象

范例:

package com.zgy.servlet;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class TestResponseServlet extends HttpServlet{

 

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// resp.setHeader("content-type", "text/html;charset=gbk");

// resp.setHeader("content-type", "text/xml;charset=gbk");

resp.setHeader("content-type", "text/plain;charset=gbk");

resp.setContentType("text/html;charset=gbk");

PrintWriter pw1 = resp.getWriter();

PrintWriter pw2 = resp.getWriter();

pw2.println("<man><name>科比</name><job>打篮球</job></man>");

System.out.println(pw1 == pw2);

}

}


技术分享

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。