Servlet5 - request

HttpServletRequest對象代表客戶端的請求


HTTP協(xié)議之請求
繼承關(guān)系

通過Request對象進行的常用操作

  • 獲取客戶機信息
  • 獲取請求頭信息
  • 獲取請求參數(shù)
  • 利用請求域傳遞對象(request域?qū)ο螅?/li>
  • 重定向和轉(zhuǎn)發(fā)的區(qū)別
獲取客戶機信息
獲取客戶機信息

獲取請求頭信息

獲取請求頭信息
  • referer 網(wǎng)頁來源
  • user-agent 瀏覽器類型
    • MSIE IE瀏覽器
    • Firefox 火狐瀏覽器
    • Chrome google瀏覽器
/**
 * 獲取客戶機的內(nèi)容 和請求頭內(nèi)容
 * @author limaoquan
 *
 */
public class RequestServlet1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取IP
        String ip = request.getRemoteAddr();
        String method = request.getMethod();
        String path = request.getContextPath();
        
        System.out.println("IP地址" + ip);
        System.out.println("虛擬路徑是 "+ path);
        System.out.println("請求方式"+ method);
        
        //獲取請求頭
        String referer=request.getHeader("referer");//網(wǎng)頁來源(防盜鏈)
        String agent = request.getHeader("user-agent");//判斷瀏覽器(文件下載)
        //遍歷所有請求頭
        Enumeration<String> names = request.getHeaderNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            System.out.println(name + ":" + request.getHeader(name));
        }
        System.out.println("------------");
        System.out.println("您使用瀏覽器:"+ request.getHeader("user-agent"));
        
        //判斷referer是否存在和有效
        if(referer!=null&&referer.startsWith("http://localhost/day")){
            //不屬于盜鏈
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("機密信息");
        }else{
            //盜鏈
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println("您的請求盜鏈");
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

獲取請求參數(shù)(重要)

獲取請求參數(shù)
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<form action="/day10/reg" method="post">
        <table border="1" width="50%">
            <tr>
                <td>輸入姓名</td>
                <td><input type="text" name="username"></td>
            </tr>
            <tr>
                <td>輸入密碼</td>
                <td><input type="password" name="password"></td>
            </tr>
            <tr>
                <td>選擇性別</td>
                <td>
                    <input type="radio" name="sex" value="man"/>男
                    <input type="radio" name="sex" value="woman"/>女
                </td>
            </tr>
            <tr>
                <td>選擇愛好</td>
                <td>
                    <input type="checkbox" name="love" value="lq"/>籃球
                    <input type="checkbox" name="love" value="zq"/>足球
                    <input type="checkbox" name="love" value="pq"/>排球
                </td>
            </tr>
            <tr>
                <td>選擇城市</td>
                <td>
                    <select name="city">
                        <option value="none">--請選擇--</option>
                        <option value="bj">北京</option>
                        <option value="sh">上海</option>
                        <option value="sz">深圳</option>
                    </select>
                </td>
            </tr>
            <tr>        
                <td colspan="2"><input type="submit" value="提交"></td>
            </tr>
        </table>
    </form>

</body>
</html>
html界面
public class RegServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * request獲取中文的亂碼
         *  post請求
         *      setCharacterEncoding(String env) 設置request緩沖區(qū)編碼
         *  
         *  get請求
         *      
         */
        //設置request緩沖區(qū)編碼
        request.setCharacterEncoding("UTF-8");
        //獲取內(nèi)容股淡,做其他操作
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        
        //獲取愛好伸但,有過個值
        String[] loves = request.getParameterValues("love");
        String city = request.getParameter("city");
        
        System.out.println("用戶名:" + username);
        System.out.println("密碼:" + password);
        System.out.println("性別:" + sex);
        System.out.println("愛好:" + Arrays.toString(loves));
        System.out.println("城市:" + city);
        System.out.println("==========================");
        //獲取map集合
        Map<String,String[]> map = request.getParameterMap();
        //循環(huán)遍歷
        Set<String> keys = map.keySet();
        for(String key:keys){
            String[] values = map.get(key);
            System.out.println(Arrays.toString(values));
        }
        
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
亂碼問題解決
  • POST請求亂碼 :
    request.setCharacterEncoding("utf-8");
  • GET請求亂碼
  • 解決方案一:修改server.xml (盡力不要用方案一)
    <Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>
    必須有修改tomcat服務器配置文件權(quán)限

  • 解決方案二:逆向編解碼(推薦用)
    username = URLEncoder.encode(username, "ISO8859-1");
    username = URLDecoder.decode(username, "utf-8");
    簡化
    username = new String(username.getBytes("ISO8859-1"),"utf-8");

重定向和轉(zhuǎn)發(fā)

域?qū)ο?ServletContext 與 request 的區(qū)別:

  • ServletContext: 服務器啟動,為每個web應用只創(chuàng)建一個ServletContext對象,所有應用共享
  • request 只有一次請求的范圍

兩者方法相似:

  • setAttribute();
  • getAttribute();
  • removeAttribute();
public class RequestServlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //request域設置內(nèi)容
        request.setAttribute("name", "Mango");
        
        //轉(zhuǎn)發(fā)(路徑服務器端的絕對路徑) 轉(zhuǎn)發(fā)可以共享request域
        request.getRequestDispatcher("/request3").forward(request, response);
        
        //完成重定向(客戶端路徑) 重定向無法共享request域
        //response.sendRedirect("/day10/request3");
                
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}




public class RequestServlet3 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取
        String value = (String)request.getAttribute("name");
        
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("訪問到 了 3 " + value);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
轉(zhuǎn)發(fā)和重定向的區(qū)別

轉(zhuǎn)發(fā)

  RequestDispatcher rd = request.getRequestDispatcher("/request3");
  rd.forward(request, response);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子疤估,更是在濱河造成了極大的恐慌,老刑警劉巖乞封,帶你破解...
    沈念sama閱讀 216,919評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件做裙,死亡現(xiàn)場離奇詭異,居然都是意外死亡肃晚,警方通過查閱死者的電腦和手機锚贱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來关串,“玉大人拧廊,你說我怎么就攤上這事监徘。” “怎么了吧碾?”我有些...
    開封第一講書人閱讀 163,316評論 0 353
  • 文/不壞的土叔 我叫張陵凰盔,是天一觀的道長。 經(jīng)常有香客問我倦春,道長户敬,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,294評論 1 292
  • 正文 為了忘掉前任睁本,我火速辦了婚禮尿庐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘呢堰。我一直安慰自己抄瑟,他們只是感情好,可當我...
    茶點故事閱讀 67,318評論 6 390
  • 文/花漫 我一把揭開白布枉疼。 她就那樣靜靜地躺著皮假,像睡著了一般。 火紅的嫁衣襯著肌膚如雪骂维。 梳的紋絲不亂的頭發(fā)上惹资,一...
    開封第一講書人閱讀 51,245評論 1 299
  • 那天,我揣著相機與錄音席舍,去河邊找鬼布轿。 笑死,一個胖子當著我的面吹牛来颤,可吹牛的內(nèi)容都是我干的汰扭。 我是一名探鬼主播,決...
    沈念sama閱讀 40,120評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼福铅,長吁一口氣:“原來是場噩夢啊……” “哼萝毛!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起滑黔,我...
    開封第一講書人閱讀 38,964評論 0 275
  • 序言:老撾萬榮一對情侶失蹤笆包,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后略荡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體庵佣,經(jīng)...
    沈念sama閱讀 45,376評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,592評論 2 333
  • 正文 我和宋清朗相戀三年汛兜,在試婚紗的時候發(fā)現(xiàn)自己被綠了巴粪。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,764評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖肛根,靈堂內(nèi)的尸體忽然破棺而出辫塌,到底是詐尸還是另有隱情,我是刑警寧澤派哲,帶...
    沈念sama閱讀 35,460評論 5 344
  • 正文 年R本政府宣布臼氨,位于F島的核電站,受9級特大地震影響芭届,放射性物質(zhì)發(fā)生泄漏储矩。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,070評論 3 327
  • 文/蒙蒙 一褂乍、第九天 我趴在偏房一處隱蔽的房頂上張望椰苟。 院中可真熱鬧,春花似錦树叽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至层皱,卻和暖如春性锭,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背叫胖。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評論 1 269
  • 我被黑心中介騙來泰國打工草冈, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人瓮增。 一個月前我還...
    沈念sama閱讀 47,819評論 2 370
  • 正文 我出身青樓怎棱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親绷跑。 傳聞我的和親對象是個殘疾皇子拳恋,可洞房花燭夜當晚...
    茶點故事閱讀 44,665評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 本文包括:1、Listener簡介2砸捏、Servlet監(jiān)聽器3谬运、監(jiān)聽三個域?qū)ο髣?chuàng)建和銷毀的事件監(jiān)聽器4、監(jiān)聽三個域?qū)?..
    廖少少閱讀 6,069評論 6 28
  • 一垦藏、簡介 (1) web服務器收到客戶端的http請求梆暖,會針對每一次請求,分別創(chuàng)建一個用于代表請求的request...
    yjaal閱讀 1,641評論 2 9
  • 這部分主要是與Java Web和Web Service相關(guān)的面試題掂骏。 96轰驳、闡述Servlet和CGI的區(qū)別? 答...
    雜貨鋪老板閱讀 1,404評論 0 10
  • 三兩白的 半箱啤的 我便醉了酒 搖曳在風中的低吟淺唱 入耳化作嘲笑 徘徊于流年的音容笑貌 是秋夜的迷幻寒涼 我是酒...
    萬里追風閱讀 375評論 2 9
  • 常見組件的git地址: MGJRouter : https://github.com/meili/MGJRoute...
    LeeLeCoder閱讀 166評論 0 0