JSP中request与response的⽤法详解
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),适⽤于单值毫秒类型的请求头
 *    Enumeration<String> getHeaders(String name),适⽤于多值请求头
*
*
*/
public class CServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ip = RemoteAddr();//获取IP地址
String method = Method();//获取请求⽅式
System.out.println(ip);
System.out.println(method);
getLiuLanQi(request);
protectMethod(request, response);
}
//防盗链
public void protectMethod(HttpServletRequest request,
HttpServletResponse response) {
String url = Header("referer");
System.out.println(url);
if(url != null && url.equalsIgnoreCase("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 = Header("User-Agent");
if(user != null) {
String userNoC = LowerCase();
ains("chrome")) {
System.out.println("浏览器类型:⾕歌" );
}
else ains("firefox/")) {
System.out.println("浏览器类型:⽕狐");
}
else {
System.out.println("浏览器类型:IE");
}
}
else {
System.out.println("null");
}
应⽤2获取URL路径
/**
* 获取请求URL
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,等于不包含参数的整个请求路径。localhost:8080/day10_2/AServlet  *
*
*/
public class DServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.Scheme());
System.out.ServerName());
System.out.ServerPort());
System.out.ContextPath());
System.out.ServletPath());
System.out.QueryString());
System.out.RequestURI());
System.out.RequestURL());
}
}
应⽤3获取请求参数
/**
*
* 请求参数:有⼀个参数⼀个值的,还有⼀个参数多个值!jsp帮助文档
    > *****String getParameter(String name):获取指定名称的请求参数值,适⽤于单值请求参数
    > String[] getParameterValues(String name):获取指定名称的请求参数值,适⽤于多值请求参数
    > Enumeration<String> getParameterNames():获取所有请求参数名称
    > *****Map<String,String[]> 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 = Parameter("name");
String password = Parameter("password");
String[] aihao = ParameterValues("aihao");
response.setHeader("content-type", "text/html;charset=utf-8");
PrintWriter pw = Writer();
pw.println("name:" + name + "<br/>");
pw.println("password:" + password + "<br/>");
pw.print("aihao");
for (int i = 0; i < aihao.length; i++) {
switch (i) {
case 1:
pw.print("吃饭");
break;
case 2:
pw.print("睡觉");
break;
case 3:
pw.print("打⾖⾖");
break;
default:
break;
}
}
pw.close();
}
<!-- ⽤于发送请求的html -->
<html>
<head>
<title>denglu.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="/day10/EServlet" method="post"><!-- 通过post⽅法提交 -->
姓名:<input type="text" name="name"/><br/>
密码:<input type="password" name="password"><br/>
爱好:<input type="checkbox" name="aihao" value="1"/>吃饭
<input type="checkbox" name="aihao" value="2"/>睡觉
<input type="checkbox" name="aihao" value="3"/>打⾖⾖
<input type="submit" value="提交">
</form>
</body>
</html>
应⽤4设置request对象属性
⽤来实现同⼀个应⽤程序servlet之间值得传递,我们还⽤到了转发
/**
*
** request域
    Servlet中三⼤域对象:request、session、application,都有如下三个⽅法:
    > void setAttribute(String name, Object value)
    > Object getAttribute(String name)
> void removeAttribute(String name);
    > 同⼀请求范围内使⽤request.setAttribute()、Attribute()来传值!前⼀个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 = RequestDispatcher("/GServlet");
rd.forward(request, response);
}
}
public class GServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = (Attribute("name");
String password = (Attribute("password");
response.setHeader("content-type", "text/html;charset=utf-8");
PrintWriter pw = Writer();
pw.println("name:" + name + "<br/>");
pw.println("password:" + password + "<br/>");
pw.close();
}
}
好了,request的⽤法⼤致就是这摸多了。
让我们来看看response对象吧。
response对象的使⽤
http协议定义了响应浏览器的格式:
响应⾏
响应头
空格
响应体
应⽤1设置响应正⽂
/**
* response的正⽂
* 1,字符流
* 2,字节流
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//String n = "hello javaweb";
//byte[] b = n.getBytes();
//字节流的使⽤
/*ServletOutputStream outputStream = OutputStream();
outputStream.write(b);
outputStream.close();*/
//字符流的使⽤
/*PrintWriter p = Writer();
p.write(n);
p.close();*/
/
/commoms⼯具包的使⽤
FileInputStream fileInputStream = new FileInputStream("C:/Users/74087/Desktop/6226354_994604.jpg");
byte[] b = ByteArray(fileInputStream);
ServletOutputStream outputStream = OutputStream();
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=www.baidu");
}
//重定向的使⽤
public void sendRe(HttpServletResponse response) {
response.setStatus(302);
response.setHeader("Location", "www.baidu");
}
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");
}
}
如有疑问请留⾔或者到本站社区交流讨论,感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。