JSP 中request与response的用法详解
概要:
在学习这两个对象之前,我们应该已经有了http协议的基本了解了,如果不清楚http协议的可以看我的关于http协议的介绍。因为其实request和response的使用大部分都是对http协议的操作。
request对象的介绍
我们先从request对象进行介绍:
我们知道http协议定义了请求服务器的格式:
请求行
请求头
空格
请求体(get请求没有请求体)
好了,这里我们就不详细介绍了,我们只看几个应用就可以了,没什么难度:
应用1 获取请求头
/** * 获取HTTP请求头 * String getHeader(String name),适用于单值头 * int getIntHeader(String name),适用于单值int类型的请求头 * long getDateHeader(String name),适用于单值毫秒类型的请求头 * EnumerationgetHeaders(String name),适用于多值请求头 * * */ public class CServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ip = request.getRemoteAddr();//获取IP地址 String method = request.getMethod();//获取请求方式 System.out.println(ip); System.out.println(method); getLiuLanQi(request); protectMethod(request, response); } //防盗链 public void protectMethod(HttpServletRequest request, HttpServletResponse response) { String url = request.getHeader("referer"); System.out.println(url); if(url != null && url.equalsIgnoreCase("http://localhost:8080/day10/MyHtml.html") ) { System.out.println("hi"); } else { response.setStatus(302); response.setHeader("Location","/day10/MyHtml.html"); System.out.println("重定向"); } } //判断浏览器的类型 public void getLiuLanQi(HttpServletRequest request) { String user = request.getHeader("User-Agent"); if(user != null) { String userNoC = user.toLowerCase(); if(userNoC.contains("chrome")) { System.out.println("浏览器类型:谷歌" ); } else if(userNoC.contains("firefox/")) { System.out.println("浏览器类型:火狐"); } else { System.out.println("浏览器类型:IE"); } } else { System.out.println("null"); } } }
应用2获取URL路径
/** * 获取请求URL http://localhost:8080/day10_2/AServlet?username=xxx&password=yyy > String getScheme():获取协议,http > String getServerName():获取服务器名,localhost > String getServerPort():获取服务器端口,8080 > *****String getContextPath():获取项目名,/day10_2 > String getServletPath():获取Servlet路径,/AServlet > String getQueryString():获取参数部分,即问号后面的部分。username=xxx&password=yyy > String getRequestURI():获取请求URI,等于项目名+Servlet路径。/day10_2/AServlet > String getRequestURL():获取请求URL,等于不包含参数的整个请求路径。http://localhost:8080/day10_2/AServlet * * */ public class DServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println(request.getScheme()); System.out.println(request.getServerName()); System.out.println(request.getServerPort()); System.out.println(request.getContextPath()); System.out.println(request.getServletPath()); System.out.println(request.getQueryString()); System.out.println(request.getRequestURI()); System.out.println(request.getRequestURL()); } }
应用3获取请求参数
/** * * 请求参数:有一个参数一个值的,还有一个参数多个值! > *****String getParameter(String name):获取指定名称的请求参数值,适用于单值请求参数 > String[] getParameterValues(String name):获取指定名称的请求参数值,适用于多值请求参数 > EnumerationgetParameterNames():获取所有请求参数名称 > *****Map getParameterMap():获取所有请求参数,其中key为参数名,value为参数值。 * */ public class EServlet 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");//调用他来解决乱码问题的,不会的可以看我写的解决乱码的那一篇 String name = request.getParameter("name"); String password = request.getParameter("password"); String[] aihao = request.getParameterValues("aihao"); response.setHeader("content-type", "text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.println("name:" + name + "
"); pw.println("password:" + password + "
"); pw.print("aihao"); for (int i = 0; i
姓名:
密码:
爱好:吃饭 睡觉 打豆豆
应用4设置request对象属性
用来实现同一个应用程序servlet之间值得传递,我们还用到了转发
/** * ** request域 Servlet中三大域对象:request、session、application,都有如下三个方法: > void setAttribute(String name, Object value) > Object getAttribute(String name) > void removeAttribute(String name); > 同一请求范围内使用request.setAttribute()、request.getAttribute()来传值!前一个Servlet调用setAttribute()保存值,后一个Servlet调用getAttribute()获取值。 * */ public class FServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("name","weijinhao"); request.setAttribute("password", "123"); RequestDispatcher rd = request.getRequestDispatcher("/GServlet"); rd.forward(request, response); } }
public class GServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = (String)request.getAttribute("name"); String password = (String)request.getAttribute("password"); response.setHeader("content-type", "text/html;charset=utf-8"); PrintWriter pw = response.getWriter(); pw.println("name:" + name + "
"); pw.println("password:" + password + "
"); pw.close(); } }
好了,request的用法大致就是这摸多了。
让我们来看看response对象吧。
response对象的使用
http协议定义了响应浏览器的格式:
响应行
响应头
空格
响应体
response对象的大致应用是用在设置响应码,设置响应头,及设置响应正文。
应用1设置响应正文
/** * response的正文 * 1,字符流 * 2,字节流 */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //String n = "hello javaweb"; //byte[] b = n.getBytes(); //字节流的使用 /*ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(b); outputStream.close();*/ //字符流的使用 /*PrintWriter p = response.getWriter(); p.write(n); p.close();*/ //commoms工具包的使用 FileInputStream fileInputStream = new FileInputStream("C:/Users/74087/Desktop/6226354_994604.jpg"); byte[] b = IOUtils.toByteArray(fileInputStream); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(b); outputStream.close(); } }
应用2 设置响应码和响应头
/** *response 的响应码 *1, sendError(int sc)//发送错误代码 *2, sendError(int sc, java.lang.String msg) //发送错误代码及描述 *3, setStatus(int sc) //发送成功响应代码 *response 的响应头 *1, setDateHeader(java.lang.String name, long date) *2, setHeader(java.lang.String name, java.lang.String value) *3, setIntHeader(java.lang.String name, int value) * 下面的和上面的作用一样但是是为了进行多值的添加 * addDateHeader(java.lang.String name, long date) * addHeader(java.lang.String name, java.lang.String value) * addIntHeader(java.lang.String name, int value) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //sendNum(response); //sendRe(response); //refresh(response); //noCache(response); } //禁用浏览器缓存 public void noCache(HttpServletResponse response) { response.setHeader("Cache-Control","no-cache"); response.setHeader("pragma","0"); response.setHeader("expires","no-cache"); } //自动跳转 public void refresh(HttpServletResponse response) { response.setHeader("refresh", "5;url=http://www.baidu.com"); } //重定向的使用 public void sendRe(HttpServletResponse response) { response.setStatus(302); response.setHeader("Location", "http://www.baidu.com"); } public void sendNum(HttpServletResponse response) throws IOException { response.setStatus(200); response.sendError(404); response.sendError( 404, "ser accept your request but i don't want to you see my web page"); } }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!