JSP 中request與response的用法詳解
概要:
在學(xué)習(xí)這兩個(gè)對(duì)象之前,我們應(yīng)該已經(jīng)有了http協(xié)議的基本了解了,如果不清楚http協(xié)議的可以看我的關(guān)于http協(xié)議的介紹。因?yàn)槠鋵?shí)request和response的使用大部分都是對(duì)http協(xié)議的操作。
request對(duì)象的介紹
我們先從request對(duì)象進(jìn)行介紹:
我們知道http協(xié)議定義了請(qǐng)求服務(wù)器的格式:
請(qǐng)求行
請(qǐng)求頭
空格
請(qǐng)求體(get請(qǐng)求沒有請(qǐng)求體)
好了,這里我們就不詳細(xì)介紹了,我們只看幾個(gè)應(yīng)用就可以了,沒什么難度:
應(yīng)用1 獲取請(qǐng)求頭
/**
* 獲取HTTP請(qǐng)求頭
* String getHeader(String name),適用于單值頭
* int getIntHeader(String name),適用于單值int類型的請(qǐng)求頭
* long getDateHeader(String name),適用于單值毫秒類型的請(qǐng)求頭
* EnumerationString> getHeaders(String name),適用于多值請(qǐng)求頭
*
*
*/
public class CServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String ip = request.getRemoteAddr();//獲取IP地址
String method = request.getMethod();//獲取請(qǐng)求方式
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");
}
}
}
應(yīng)用2獲取URL路徑
/**
* 獲取請(qǐng)求URL
http://localhost:8080/day10_2/AServlet?username=xxxpassword=yyy
> String getScheme():獲取協(xié)議,http
> String getServerName():獲取服務(wù)器名,localhost
> String getServerPort():獲取服務(wù)器端口,8080
> *****String getContextPath():獲取項(xiàng)目名,/day10_2
> String getServletPath():獲取Servlet路徑,/AServlet
> String getQueryString():獲取參數(shù)部分,即問號(hào)后面的部分。username=xxxpassword=yyy
> String getRequestURI():獲取請(qǐng)求URI,等于項(xiàng)目名+Servlet路徑。/day10_2/AServlet
> String getRequestURL():獲取請(qǐng)求URL,等于不包含參數(shù)的整個(gè)請(qǐng)求路徑。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());
}
}
應(yīng)用3獲取請(qǐng)求參數(shù)
/**
*
* 請(qǐng)求參數(shù):有一個(gè)參數(shù)一個(gè)值的,還有一個(gè)參數(shù)多個(gè)值!
> *****String getParameter(String name):獲取指定名稱的請(qǐng)求參數(shù)值,適用于單值請(qǐng)求參數(shù)
> String[] getParameterValues(String name):獲取指定名稱的請(qǐng)求參數(shù)值,適用于多值請(qǐng)求參數(shù)
> EnumerationString> getParameterNames():獲取所有請(qǐng)求參數(shù)名稱
> *****MapString,String[]> getParameterMap():獲取所有請(qǐng)求參數(shù),其中key為參數(shù)名,value為參數(shù)值。
*
*/
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");//調(diào)用他來解決亂碼問題的,不會(huì)的可以看我寫的解決亂碼的那一篇
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 + "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();
}
}
!-- 用于發(fā)送請(qǐng)求的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>
應(yīng)用4設(shè)置request對(duì)象屬性
用來實(shí)現(xiàn)同一個(gè)應(yīng)用程序servlet之間值得傳遞,我們還用到了轉(zhuǎn)發(fā)
/**
*
** request域
Servlet中三大域?qū)ο螅簉equest、session、application,都有如下三個(gè)方法:
> void setAttribute(String name, Object value)
> Object getAttribute(String name)
> void removeAttribute(String name);
> 同一請(qǐng)求范圍內(nèi)使用request.setAttribute()、request.getAttribute()來傳值!前一個(gè)Servlet調(diào)用setAttribute()保存值,后一個(gè)Servlet調(diào)用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 + "br/>");
pw.println("password:" + password + "br/>");
pw.close();
}
}
好了,request的用法大致就是這摸多了。
讓我們來看看response對(duì)象吧。
response對(duì)象的使用
http協(xié)議定義了響應(yīng)瀏覽器的格式:
響應(yīng)行
響應(yīng)頭
空格
響應(yīng)體
response對(duì)象的大致應(yīng)用是用在設(shè)置響應(yīng)碼,設(shè)置響應(yīng)頭,及設(shè)置響應(yīng)正文。
應(yīng)用1設(shè)置響應(yīng)正文
/**
* response的正文
* 1,字符流
* 2,字節(jié)流
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//String n = "hello javaweb";
//byte[] b = n.getBytes();
//字節(jié)流的使用
/*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();
}
}
應(yīng)用2 設(shè)置響應(yīng)碼和響應(yīng)頭
/**
*response 的響應(yīng)碼
*1, sendError(int sc)//發(fā)送錯(cuò)誤代碼
*2, sendError(int sc, java.lang.String msg) //發(fā)送錯(cuò)誤代碼及描述
*3, setStatus(int sc) //發(fā)送成功響應(yīng)代碼
*response 的響應(yīng)頭
*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)
* 下面的和上面的作用一樣但是是為了進(jìn)行多值的添加
* 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");
}
//自動(dòng)跳轉(zhuǎn)
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");
}
}
如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
您可能感興趣的文章:- jsp 使用request為頁面添加靜態(tài)數(shù)據(jù)的實(shí)例
- JSP中Servlet的Request與Response的用法與區(qū)別
- JSP的request對(duì)象實(shí)例詳解
- JSP request.setAttribute()詳解及實(shí)例
- jsp Request獲取url信息的各種方法對(duì)比
- JSP利用過濾器解決request中文亂碼問題
- JSP用過濾器解決request getParameter中文亂碼問題
- Jsp中request的3個(gè)基礎(chǔ)實(shí)踐