Java Web學習總結(5)HttpServletRequest

一,HttpServletRequest介紹 css

HttpServletRequest對象表明客戶端的請求,當客戶端經過HTTP協議訪問服務器時,HTTP請求頭中的全部信息都封裝在這個對象中,經過這個對象提供的方法,能夠得到客戶端請求的全部信息。 html

二,jsp頁面引入js,css文件的方式 前端

在eclipse中新建一個web項目,目錄結構以下: java

在jsp頁面的最開始,獲取項目的根路徑: jquery

<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>

在<head></head>中,插入下述代碼: web

<base href="<%=basePath%>" />

這句代碼的做用是將整個頁面的根路徑設置爲項目路徑。 bootstrap

三,Request經常使用方法 數組

1,得到客戶機信息瀏覽器

getRequestURL()服務器

返回客戶端發出請求時的完整URL。

getRequestURI()

返回請求行中的資源名部分。

getQueryString ()

返回請求行中的參數部分。

getRemoteAddr()

返回發出請求的客戶機的IP地址。

getPathInfo()

返回請求URL中的額外路徑信息。額外路徑信息是請求URL中的位於Servlet的路徑以後和查詢參數以前的內容,它以"/"開頭。

getRemoteHost()

返回發出請求的客戶機的完整主機名。

getRemotePort()

返回客戶機所使用的網絡端口號。

getLocalAddr()

返回WEB服務器的IP地址。

getLocalName()

返回WEB服務器的主機名。

private void RequestMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException{
    String reqUrl = req.getRequestURL().toString();//獲得請求的URL地址
    String reqUri = req.getRequestURI();//獲得請求的資源
    String queryString = req.getQueryString();//獲得請求的URL地址中附帶的參數
    String remoteAddr = req.getRemoteAddr();//獲得來訪者的IP地址
    String remoteHost = req.getRemoteHost();
    int remotePort = req.getRemotePort();
    String remoteUser = req.getRemoteUser();
    String method = req.getMethod();//獲得請求URL地址時使用的方法
    String pathInfo = req.getPathInfo();
    String localAddr = req.getLocalAddr();//獲取WEB服務器的IP地址
    String localName = req.getLocalName();//獲取WEB服務器的主機名
    resp.setCharacterEncoding("UTF-8");//設置將字符以"UTF-8"編碼輸出到客戶端瀏覽器
    //經過設置響應頭控制瀏覽器以UTF-8的編碼顯示數據,若是不加這句話,那麼瀏覽器顯示的將是亂碼
    resp.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out = resp.getWriter();
    out.write("獲取到的客戶機信息以下:");
    out.write("<br/>");
    out.write("請求的URL地址:"+reqUrl);
    out.write("<br/>");
    out.write("請求的資源:"+reqUri);
    out.write("<br/>");
    out.write("請求的URL地址中附帶的參數:"+queryString);
    out.write("<br/>");
    out.write("來訪者的IP地址:"+remoteAddr);
    out.write("<br/>");
    out.write("來訪者的主機名:"+remoteHost);
    out.write("<br/>");
    out.write("使用的端口號:"+remotePort);
    out.write("<br/>");
    out.write("remoteUser:"+remoteUser);
    out.write("<br/>");
    out.write("請求使用的方法:"+method);
    out.write("<br/>");
    out.write("pathInfo:"+pathInfo);
    out.write("<br/>");
    out.write("localAddr:"+localAddr);
    out.write("<br/>");
    out.write("localName:"+localName);
}
private void RequestMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException{
    String reqUrl = req.getRequestURL().toString();//獲得請求的URL地址
    String reqUri = req.getRequestURI();//獲得請求的資源
    String queryString = req.getQueryString();//獲得請求的URL地址中附帶的參數
    String remoteAddr = req.getRemoteAddr();//獲得來訪者的IP地址
    String remoteHost = req.getRemoteHost();
    int remotePort = req.getRemotePort();
    String remoteUser = req.getRemoteUser();
    String method = req.getMethod();//獲得請求URL地址時使用的方法
    String pathInfo = req.getPathInfo();
    String localAddr = req.getLocalAddr();//獲取WEB服務器的IP地址
    String localName = req.getLocalName();//獲取WEB服務器的主機名
    resp.setCharacterEncoding("UTF-8");//設置將字符以"UTF-8"編碼輸出到客戶端瀏覽器
    //經過設置響應頭控制瀏覽器以UTF-8的編碼顯示數據,若是不加這句話,那麼瀏覽器顯示的將是亂碼
    resp.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out = resp.getWriter();
    out.write("獲取到的客戶機信息以下:");
    out.write("<br/>");
    out.write("請求的URL地址:"+reqUrl);
    out.write("<br/>");
    out.write("請求的資源:"+reqUri);
    out.write("<br/>");
    out.write("請求的URL地址中附帶的參數:"+queryString);
    out.write("<br/>");
    out.write("來訪者的IP地址:"+remoteAddr);
    out.write("<br/>");
    out.write("來訪者的主機名:"+remoteHost);
    out.write("<br/>");
    out.write("使用的端口號:"+remotePort);
    out.write("<br/>");
    out.write("remoteUser:"+remoteUser);
    out.write("<br/>");
    out.write("請求使用的方法:"+method);
    out.write("<br/>");
    out.write("pathInfo:"+pathInfo);
    out.write("<br/>");
    out.write("localAddr:"+localAddr);
    out.write("<br/>");
    out.write("localName:"+localName);
}

2,得到客戶機請求頭

getHeader(string name)方法:String

getHeaders(String name)方法:Enumeration

getHeaderNames()方法

private void RequestHead(HttpServletRequest req, HttpServletResponse resp) throws IOException{
    resp.setCharacterEncoding("UTF-8");//設置將字符以"UTF-8"編碼輸出到客戶端瀏覽器
    //經過設置響應頭控制瀏覽器以UTF-8的編碼顯示數據
    resp.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out = resp.getWriter();
    Enumeration<String> reqHeadInfos = req.getHeaderNames();//獲取全部的請求頭
    out.write("獲取到的客戶端全部的請求頭信息以下:");
    out.write("<br/>");
    while (reqHeadInfos.hasMoreElements()) {
        String headName = (String) reqHeadInfos.nextElement();
        String headValue = req.getHeader(headName);//根據請求頭的名字獲取對應的請求頭的值
        out.write(headName+":"+headValue);
        out.write("<br/>");
    }
    out.write("<br/>");
    out.write("獲取到的客戶端Accept-Encoding請求頭的值:");
    out.write("<br/>");
    String value = req.getHeader("Accept-Encoding");//獲取Accept-Encoding請求頭對應的值
    out.write(value);
    
    Enumeration<String> e = req.getHeaders("Accept-Encoding");
    while (e.hasMoreElements()) {
        String string = (String) e.nextElement();
        System.out.println(string);
    }
}

3,得到客戶機請求參數

getParameter(String name)

根據name獲取請求參數(經常使用)

getParameterValues(String name)

根據name獲取請求參數列表(經常使用)

getParameterMap()

返回的是一個Map類型的值,該返回值記錄着前端(如jsp頁面)所提交請求中的請求參數和請求參數值的映射關係。(編寫框架時經常使用)

以下表單:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表單提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/GetParameterRequest.html" role="form" method="post">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label">名字</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="請輸入名字">
            </div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label">年齡</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="age"
                    placeholder="請輸年齡">
            </div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label">性別</label>
            <div class="col-sm-3">
                <input type="radio" name="sex" value="男" checked><input type="radio" name="sex" value="女"></div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label">愛好</label>
            <div class="col-sm-3">
                <input type="checkbox" name="aihao" value="唱歌">唱歌
                <input type="checkbox" name="aihao" value="上網">上網
                <input type="checkbox" name="aihao" value="遊戲">遊戲
                <input type="checkbox" name="aihao" value="看書">看書
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
                <button type="reset" class="btn btn-default">重置</button>
            </div>
        </div>
    </form>
</body>
</html>

使用getParameter方法和getParameterValues方法接收表單參數:

public class GetParameterRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //客戶端是以UTF-8編碼提交表單數據的,因此須要設置服務器端以UTF-8的編碼進行接收,不然對於中文數據就會產生亂碼
        req.setCharacterEncoding("UTF-8");
        //獲取名字
        String name = req.getParameter("name");
        //獲取年齡
        String age = req.getParameter("age");
        //獲取性別
        String sex = req.getParameter("sex");
        //獲取愛好,由於能夠選中多個值,因此獲取到的值是一個字符串數組,所以須要使用getParameterValues方法來獲取
        String[] aihaos = req.getParameterValues("aihao");
        
        String aihao = "";
        if(aihaos != null){
            for (int i = 0; i < aihaos.length; i++) {
                if(i == aihaos.length - 1){
                    aihao += aihaos[i];
                } else {
                    aihao += aihaos[i] + ",";
                }
            }
        }
        System.out.println("名字:" + name);
        System.out.println("年齡:" + age);
        System.out.println("性別:" + sex);
        System.out.println("愛好:" + aihao);
        req.setAttribute("aihao", aihao);
        //設置服務器端以UTF-8編碼輸出數據到客戶端
        resp.setCharacterEncoding("UTF-8");
        this.getServletContext().getRequestDispatcher("/request.jsp").forward(req, resp);
    }
}

響應頁面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表單提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<table class="table">
   <thead>
      <tr>
         <th>名稱</th>
         <th>結果</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td>姓名</td>
         <td><%=request.getParameter("name") %></td>
      </tr>
      <tr>
         <td>年齡</td>
         <td><%=request.getParameter("age") %></td>
      </tr>
      <tr>
         <td>性別</td>
         <td><%=request.getParameter("sex") %></td>
      </tr>
      <tr>
         <td>愛好</td>
         <td><%=request.getAttribute("aihao") %></td>
      </tr>
   </tbody>
</table>
</body>
</html>

提交以下表單:

後臺打印:

運行結果以下:

四,request接收表單提交中文參數亂碼問題

1,以POST方式提交表單中文參數的亂碼問題

有以下表單:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表單提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/PostRequest.html" role="form" method="post">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label">名字</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="請輸入名字">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
                <button type="reset" class="btn btn-default">重置</button>
            </div>
        </div>
    </form>
</body>
</html>

後臺接收參數:

public class PostRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println("名字:" + name);
    }
}

提交數據:

運行結果:

之因此會產生亂碼,就是由於服務器和客戶端溝通的編碼不一致形成的,所以解決的辦法是:在客戶端和服務器之間設置一個統一的編碼,以後就按照此編碼進行數據的傳輸和接收。

因爲客戶端是以UTF-8字符編碼將表單數據傳輸到服務器端的,所以服務器也須要設置以UTF-8字符編碼進行接收,經過setCharacterEncoding方法統一編碼格式:

public class PostRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //設置服務器以UTF-8的編碼接收數據
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        System.out.println("名字:" + name);
    }
}

從新提交表單,中文亂碼解決:

2,以GET方式提交表單中文參數的亂碼問題

有以下表單:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + "://"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>表單提交</title>
<link href="css/bootstrap.css" rel="stylesheet">
<script src="js/jquery-3.2.1.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/GetRequest.html" role="form" method="get">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label">名字</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="請輸入名字">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
                <button type="reset" class="btn btn-default">重置</button>
            </div>
        </div>
    </form>
</body>
</html>

後臺接收參數:

public class GetRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println("名字:" + name);
    }
}

提交數據:

運行結果:

之因此會產生亂碼,對於以get方式傳輸的數據,默認的仍是使用ISO8859-1這個字符編碼來接收數據,客戶端以UTF-8的編碼傳輸數據到服務器端,而服務器端的request對象使用的是ISO8859-1這個字符編碼來接收數據,服務器和客戶端溝通的編碼不一致所以纔會產生中文亂碼的。

解決方法:

在接收到數據後,先獲取request對象以ISO8859-1字符編碼接收到的原始數據的字節數組,而後經過字節數組以指定的編碼構建字符串

public class GetRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        //以ISO8859-1字符編碼接收到的原始數據的字節數組,而後經過字節數組以指定的編碼構建字符串
        name = new String(name.getBytes("ISO8859-1") , "UTF-8");
        System.out.println("名字:" + name);
    }
}

從新提交表單,中文亂碼解決:

相關文章
相關標籤/搜索