java Servlet响应和请求接口

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java Servlet响应和请求接口相关的知识,希望对你有一定的参考价值。

/**
 * RequestDispatcher 接口具有请求转发(forward)和请求包含(include)两种方法
 * 由于转发的是同一个request请求,所以可以在该请求中设置参数来传递数据
 * 当前代码使用forward转发请求,由转发后的ResultServlet显示结果可知,
 * 请求转发forward会改变uri,queryString根据getRequestDispatcher()函数的方法而变。
 * note:但是请求转发不会改变浏览器URL地址栏。
 */
package cn.itcast.chapter04.request;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestForwardServlet extends HttpServlet {
    public void doGet(HttpServletRequest request,HttpServletResponse response)  throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        // 将数据存储到request对象中
        request.setAttribute("company", "北京传智播客教育有限公司");
        // 从request接口中获取请求调度类实例
        RequestDispatcher dispatcher = request.getRequestDispatcher("/ResultServlet?p1=123");
        dispatcher.forward(request, response);
    }

    public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
            doGet(request, response);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>chapter04</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>PrintServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.response.PrintServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>PrintServlet</servlet-name>
    <url-pattern>/PrintServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>ChineseServlet</display-name>
    <servlet-name>ChineseServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.response.ChineseServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ChineseServlet</servlet-name>
    <url-pattern>/ChineseServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RefreshServlet</display-name>
    <servlet-name>RefreshServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.response.RefreshServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RefreshServlet</servlet-name>
    <url-pattern>/RefreshServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.response.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RequestLineServlet</display-name>
    <servlet-name>RequestLineServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.RequestLineServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestLineServlet</servlet-name>
    <url-pattern>/RequestLineServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RequestHeadersServlet</display-name>
    <servlet-name>RequestHeadersServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.RequestHeadersServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestHeadersServlet</servlet-name>
    <url-pattern>/RequestHeadersServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>DownManagerServlet</display-name>
    <servlet-name>DownManagerServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.DownManagerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownManagerServlet</servlet-name>
    <url-pattern>/DownManagerServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RequestParamsServlet</display-name>
    <servlet-name>RequestParamsServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.RequestParamsServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestParamsServlet</servlet-name>
    <url-pattern>/RequestParamsServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>RequestForwardServlet</display-name>
    <servlet-name>RequestForwardServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.RequestForwardServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RequestForwardServlet</servlet-name>
    <url-pattern>/RequestForwardServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>ResultServlet</display-name>
    <servlet-name>ResultServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.ResultServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ResultServlet</servlet-name>
    <url-pattern>/ResultServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>IncludingServlet</display-name>
    <servlet-name>IncludingServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.IncludingServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>IncludingServlet</servlet-name>
    <url-pattern>/IncludingServlet</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>IncludedServlet</display-name>
    <servlet-name>IncludedServlet</servlet-name>
    <servlet-class>cn.itcast.chapter04.request.IncludedServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>IncludedServlet</servlet-name>
    <url-pattern>/IncludedServlet</url-pattern>
  </servlet-mapping>
</web-app>
/**
 * output:
 URI:/ResultServlet
 QueryString:p1=123
 parameter p1:123
 公司名称:北京传智播客教育有限公司
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ResultServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
          // 获取PrintWriter对象用于输出信息
		PrintWriter out = response.getWriter();
		out.println("URI:" + request.getRequestURI() + "<br>");
		out.println("QueryString:" + request.getQueryString() + "<br>");
			out.println("parameter p1:" +
				request.getParameter("p1") + "<br>");
			// 获取request请求对象中保存的数据
			String company = (String) request.getAttribute("company");
			if (company != null) {
				out.println("公司名称:" + company + "<br>");
			}
		}
		public void doPost(HttpServletRequest request, 
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
/**
 * request.getParameter()
 * 尚不明确的是在不加上注释语句的情况下,获取中文参数是否会乱码,测试中是不会的,但书上说会
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestParamsServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		//设置request对象的解码方式
//		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("username");
//		name=new String(name.getBytes("iso8859-1"),"utf-8");
		String password = request.getParameter("password");
			System.out.println("用户名:" + name);
			System.out.println("密  码:" + password);
			// 获取参数名为“hobby”的值
			String[] hobbys = request.getParameterValues("hobby");
			System.out.println("爱好:");
			for (int i = 0; i < hobbys.length; i++) {
				System.out.print(hobbys[i] + ",");
			}
		}
		public void doPost(HttpServletRequest request,
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
/**
 * HttpServletRequest 接口中对获取请求行的相关方法,
 * 相关解释参照Evernote笔记
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestLineServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 获取请求行的相关信息
		out.println("getMethod : " + request.getMethod() + "<br>");
		out.println("getRequestURI : " + request.getRequestURI() + "<br>");
		out.println("getQueryString:"+request.getQueryString() + "<br>");
		out.println("getProtocol : " + request.getProtocol() + "<br>");
		out.println("getContextPath:"+request.getContextPath() + "<br>");
		out.println("getPathInfo : " + request.getPathInfo() + "<br>");
		out.println("getPathTranslated : "
                      + request.getPathTranslated() + "<br>");
		out.println("getServletPath:"+request.getServletPath() + "<br>");
		out.println("getRemoteAddr : " + request.getRemoteAddr() + "<br>");
		out.println("getRemoteHost : " + request.getRemoteHost() + "<br>");
		out.println("getRemotePort : " + request.getRemotePort() + "<br>");
		out.println("getLocalAddr : " + request.getLocalAddr() + "<br>");
		out.println("getLocalName : " + request.getLocalName() + "<br>");
		out.println("getLocalPort : " + request.getLocalPort() + "<br>");
		out.println("getServerName : " + request.getServerName() + "<br>");
		out.println("getServerPort : " + request.getServerPort() + "<br>");
		out.println("getScheme : " + request.getScheme() + "<br>");
		out.println("getRequestURL : " + request.getRequestURL() + "<br>");
	}
	public void doPost(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
		doGet(request, response);
	}
}
/**
 * 获取headers方法的相关方法,类似代码出现在servletConfig 和servletContext中
 * 
 * note: request有一个getHeaders方法(特殊情况下会用到),参见Evernote
 */
package cn.itcast.chapter04.request;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
public class RequestHeadersServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
	         // 获取请求消息中所有头字段
			Enumeration headerNames = request.getHeaderNames();
			// 使用循环遍历所有请求头,并通过getHeader()方法获取一个指定名称的头字段
			while (headerNames.hasMoreElements()) {
				String headerName = (String) headerNames.nextElement();
				out.print(headerName + " : "
	                       + request.getHeader(headerName)+ "<br>");
			}
		}
		public void doPost(HttpServletRequest request,
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
package cn.itcast.chapter04.response;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RefreshServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		// 2秒后刷新并跳转到传智播客官网首页
		response.setHeader("Refresh", "2;URL=http://www.itcast.cn");
		// 每隔3秒定时刷新当前页面
		//response.setHeader("Refresh", "3");
		response.getWriter().println(new java.util.Date());// 输出当前时间

		}
		public void doPost(HttpServletRequest request,
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
package cn.itcast.chapter04.response;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PrintServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
		    String data = "itcast";
		    // 获取字节输出流对象
//			OutputStream out = response.getOutputStream();
//			out.write(data.getBytes());// 输出信息
			//使用getWriter()方法发送消息体
			PrintWriter print = response.getWriter(); 
			print.write(data); // 输出信息

			
		}
		public void doPost(HttpServletRequest request, 
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
/**
 * HttpServletResponse 接口下的sendRedirect()方法实现重定向
 * 该方法通知客户端重新发送请求,浏览器的地址栏会发生变化。
 */
package cn.itcast.chapter04.response; 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		// 用HttpServletRequest对象的getParameter()方法获取用户名和密码
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			// 假设用户名和密码分别为:itcast和123
			if (("itcast").equals(username) &&("123").equals(password)) {
				// 如果用户名和密码正确,重定向到 welcome.html
	              response.sendRedirect("/chapter04/welcome.html");
			} else {
				// 如果用户名和密码错误,重定向到login.html
				response.sendRedirect("/chapter04/login.html");
			}
		}
		public void doPost(HttpServletRequest request, 
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
/**
 * 当前代码使用include请求包含,由转发后的IncludedServlet显示结果可知,
 * 请求包含不会改变uri,queryString。
 * 还由于在本代码中注释掉了ContentType的设置,所以最后输出的是纯文本(非html)并且中文显示为乱码,
 * 即使在Included代码中设置了也没用,因为在那之前response对象已经生成。
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class IncludingServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
//		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		RequestDispatcher rd = request
					.getRequestDispatcher("/IncludedServlet?p1=abc");
			out.println("before including" + "<br>");
			rd.include(request, response);
			out.println("after including" + "<br>");
		}
		public void doPost(HttpServletRequest request,
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
/**
 * output:
 before including<br>
 ??<br>
 URI:/IncludingServlet<br>
 QueryString:null<br>
 parameter p1:abc<br>
 after including<br>
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class IncludedServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
		// 设置响应时使用的字符编码
	    response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.println("中国" + "<br>");
		out.println("URI:" + request.getRequestURI() + "<br>");
		out.println("QueryString:" + request.getQueryString() + "<br>");
		out.println("parameter p1:" + 
                       request.getParameter("p1") + "<br>");
	}
	public void doPost(HttpServletRequest request,
        HttpServletResponse response)throws ServletException, IOException {
		doGet(request, response);
	}
}
/**
 * 	Referer头字段:当发送请求时,referer头字段的值为原网站地址,可用来查看请求来源。
 * 	本文件就是一个利用referer来判断下载请求的来源是否是本站的下载管理demo。
 *  简称为“防盗链”
 */
package cn.itcast.chapter04.request;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownManagerServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
	         // 获取referer头的值
			String referer = request.getHeader("referer"); 
	         // 获取访问地址
			String sitePart = "http://" + request.getServerName();
			// 判断referer头是否为空,这个头的首地址是否以sitePart开始的
			if (referer != null && referer.startsWith(sitePart)) {
				// 处理正在下载的请求
				out.println("dealing download ...");
			} else {
				// 非法下载请求跳转到download.html页面
				RequestDispatcher rd = request
						.getRequestDispatcher("/download.html");
				rd.forward(request, response);
			}
		}
		public void doPost(HttpServletRequest request,
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}
package cn.itcast.chapter04.response;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ChineseServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
        HttpServletResponse response)throws ServletException, IOException {
		//response.setCharacterEncoding("utf-8");
		// response.setHeader("Content-Type","text/html;charset=utf-8");
		//设置字符编码
		response.setContentType("text/html;charset=utf-8");
		String data = "中国";
		PrintWriter out = response.getWriter();
			out.println(data);
		}
		public void doPost(HttpServletRequest request, 
	        HttpServletResponse response)throws ServletException, IOException {
			doGet(request, response);
		}
	}

以上是关于java Servlet响应和请求接口的主要内容,如果未能解决你的问题,请参考以下文章

servlet

Servlet

java——Servlet

过滤器

Java Web之Servlet技术

JavaWeb核心——Servlet