第73節:Java中的HTTPServletReauest和HTTPServletResponse

標題圖
第73節: Java
中的 HTTPServletReauest
和 HTTPServletResponse
HTTP
協議
客戶端與伺服器端通訊的一種規則。
request
:
請求行
請求頭
請求體
response
:
響應行
響應頭
響應體
Get
:
請求的時候帶上的資料,在 url
上拼接,資料長度有限制
POST
:
以流的方式寫資料,資料沒有限制
Content-Type: 資料型別 Content-Length: 多少長度的資料
Servlet
入門:
寫一個類,實現介面Servlet 註冊 web.xml <servlet> servlet-name: 自定義 servlet-class: 全路徑 <init-params> 不必要寫 -servletconfig </servlet> <servlet-mapping> <servlet-name>: 上面的servlet-name <url-patter>: 以正斜槓開頭 </servlet-mapping>
servlet的生命週期:
init: 預設情況下初次訪問時就會執行,伺服器啟動時,只能執行一次 提前: <servlet> servlet-name: servlet-class: <load-on-startup>2</load-on-startup> </servlet> service: 可以執行多次,只要進行請求 destory:銷燬的使用,銷燬在從伺服器中移除託管或shutdown.bat
// servlet public class Demo implements Servlet { @Override void service(){ ... } } // 優化 繼承介面已有的實現類 // 抽象類一定有抽象方法,不一定,有抽象方法的,一定是抽象類 class Demo2 extends HttpServlet { void doGet(); void doPost(); }
// 原始碼 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request; HttpServletResponse response; try{ request = (HttpServletRequest) req; response = (HttpServletResponse) res; }catch(ClassCastException e){ throw new ServletException("non-HTTP request or response"); } service(request,response); }
HttpServletRequest
和 HttpServletResponse

效果
package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Demo extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("來了一個請求。。。"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ServletRegister</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>demo</servlet-name> <servlet-class>com.dashucoding.servlet.Demo</servlet-class> </servlet> <servlet-mapping> <servlet-name>demo</servlet-name> <url-pattern>/demo</url-pattern> </servlet-mapping> </web-app>

效果

結果
建立 Server

效果
// 建立ServletRegister ->選擇Servlet package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletRegister */ @WebServlet("/ServletRegister") public class ServletRegister extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ServletRegister() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletRegister */ public class ServletRegister extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>TestRegister</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>ServletRegister</display-name> <servlet-name>ServletRegister</servlet-name> <servlet-class>com.dashucoding.servlet.ServletRegister</servlet-class> </servlet> <servlet-mapping> <servlet-name>ServletRegister</servlet-name> <url-pattern>/ServletRegister</url-pattern> </servlet-mapping> </web-app>

效果
Servlet
配置路徑方式:
* : 就是個萬用字元,匹配任意文字。 /a* *.aa
ServletContext
// web.xml // 用於配置全域性的引數 <context-param> <param-name>dashu</param-name> <param-value>dashucoding</param-value> </context-param> // <init-param></init-param>
// 獲取物件 ServletContext context = getServletContext(); // 獲取引數值 String name = context.getInitParameter("dashu"); System.out.println("name=" + name);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取物件 ServletContext context = getServletContext(); // 獲取引數值 String name = context.getInitParameter("dashu"); System.out.println("name=" + name); }
獲取資原始檔

效果
package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 獲取ServletContext物件 ServletContext context = getServletContext(); // 獲取給定的檔案在伺服器上面的絕對路徑 String path = context.getRealPath(""); System.out.println("path=" + path); /*// 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = new FileInputStream(path); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name=" + name);*/ } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果

效果
package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 獲取ServletContext物件 ServletContext context = getServletContext(); // 獲取給定的檔案在伺服器上面的絕對路徑 String path = context.getRealPath("/file/config.properties"); System.out.println("path=" + path); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = new FileInputStream(path); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name=" + name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果
package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //test01(); test02(); } // alt + shift + z private void test02() { try { // 獲取ServletContext物件 ServletContext context = getServletContext(); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = context.getResourceAsStream("/file/config.properties"); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name02=" + name); is.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // alt + shift + m private void test01() throws FileNotFoundException, IOException { // 獲取ServletContext物件 ServletContext context = getServletContext(); // 獲取給定的檔案在伺服器上面的絕對路徑 String path = context.getRealPath("/file/config.properties"); System.out.println("path=" + path); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = new FileInputStream(path); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name=" + name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果
package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //test01(); //test02(); test03(); } private void test03() { // TODO Auto-generated method stub try { // 獲取ServletContext物件 ServletContext context = getServletContext(); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = getClass().getClassLoader().getResourceAsStream("../../file/config.properties"); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name02=" + name); is.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // alt + shift + z private void test02() { try { // 獲取ServletContext物件 ServletContext context = getServletContext(); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = context.getResourceAsStream("/file/config.properties"); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name02=" + name); is.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } // alt + shift + m private void test01() throws FileNotFoundException, IOException { // 獲取ServletContext物件 ServletContext context = getServletContext(); // 獲取給定的檔案在伺服器上面的絕對路徑 String path = context.getRealPath("/file/config.properties"); System.out.println("path=" + path); // 建立屬性物件 Properties properties = new Properties(); // 指定載入的資料來源 InputStream is = new FileInputStream(path); properties.load(is); // 獲取屬性的值 String name = properties.getProperty("name"); System.out.println("name=" + name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果
ServletContext
可以獲取全域性配置引數,可以獲取 web
工程中的資源,儲存資料, servlet
簡共享資料。
使用 ServletContext
獲取資料

效果
package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 別人把資料給你了,你就要進行獲取資料 String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("usrName=" + userName + "==password==" + password ); // 校驗資料 if("dashu".equals(userName)&&"123".equals(password)) { System.out.println("登入成功"); }else { System.out.println("登入失敗"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登入</h2> <form action="LoginServlet" method="get"> 賬號:<input type="text" name="username"/><br> 密碼:<input type="text" name="password"/><br> <input type="submit" value="登入"/> </form> </body> </html>

效果

效果

效果

效果

效果
登入
package com.dashucoding.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 別人把資料給你了,你就要進行獲取資料 String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("usrName=" + userName + "==password==" + password ); // 校驗資料 // response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) { // System.out.println("登入成功"); pw.write("login success"); }else { // System.out.println("登入失敗"); pw.write("login failed"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果

效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登入成功</h2> <a href="CountSrevlet">獲取網站登入成功總數 </a> </body> </html>
package com.dashucoding.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 別人把資料給你了,你就要進行獲取資料 String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("usrName=" + userName + "==password==" + password ); // 校驗資料 // response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) { // System.out.println("登入成功"); // pw.write("login success"); // 成功跳轉 login_success.html // 設定狀態碼 response.setStatus(302); response.setHeader("Location", "login_success.html"); }else { // System.out.println("登入失敗"); pw.write("login failed"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
登入次數

效果
package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CountServlet */ public class CountServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 取值 int count = (int)getServletContext().getAttribute("count"); // 輸出介面 response.getWriter().write("login success count == "+count); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.dashucoding.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 別人把資料給你了,你就要進行獲取資料 String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("usrName=" + userName + "==password==" + password ); // 校驗資料 // response PrintWriter pw = response.getWriter(); if("dashu".equals(userName)&&"123".equals(password)) { // System.out.println("登入成功"); // pw.write("login success"); // 成功跳轉 login_success.html // 成功次數累加 存東西 // 獲取以前舊的值,然後給它賦新值 Object obj = getServletContext().getAttribute("count"); int totalCount = 0; if(obj != null) { totalCount = (int)obj; } System.out.println("登入成功的此時是" + totalCount); // 給count賦新值 set add put getServletContext().setAttribute("count",totalCount+1); // 設定狀態碼 response.setStatus(302); response.setHeader("Location", "login_success.html"); }else { // System.out.println("登入失敗"); pw.write("login failed"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登入成功</h2> <a href="CountServlet">獲取網站登入成功總數 </a> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登入</h2> <form action="LoginServlet" method="get"> 賬號:<input type="text" name="username"/><br> 密碼:<input type="text" name="password"/><br> <input type="submit" value="登入"/> </form> </body> </html>

效果

效果
路徑:
<form action="login" method="get"> 賬號:<input type="text" name="username"/><br> 密碼:<input type="text" name="password"/><br> <input type="submit" value="登入"/> </form>
<servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping>
// ServletContext 銷燬,伺服器移除,關閉伺服器 只要同一個應用程式就行
作用:
- 獲取全域性配置
- 獲取web工程中的資源
- 儲存資料
- 共享資料
HttpServletRequest
獲取請求頭
獲取所有的頭資訊:
package com.dashucoding.servlet; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // request封裝了客戶端提交過來的一切資料 // 拿所有的頭 得到一個列舉 List集合 Enumeration<String> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); System.out.println("name=" + name); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果
得到所有
package com.dashucoding.servlet; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // request封裝了客戶端提交過來的一切資料 // 拿所有的頭 得到一個列舉 List集合 Enumeration<String> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); System.out.println("name=" + name + ";value=" + value); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果
獲取提交的資訊
package com.dashucoding.servlet; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // request封裝了客戶端提交過來的一切資料 // 拿所有的頭 得到一個列舉 List集合 Enumeration<String> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); String value = request.getHeader(name); System.out.println("name=" + name + ";value=" + value); } System.out.println("----------"); // 請求體,拼接過來的資料 獲取客戶端提交過來的資料 String name = request.getParameter("name"); System.out.println("name=" + name); // http://localhost:8080/RequestDemo01/Demo01?name=dashucoding // http://localhost:8080/RequestDemo01/Demo01?name=dashucoding&address=GD System.out.println("----------"); // 獲取所有引數 // Enumeration<String> parameterNames = request.getParameterNames(); Map<String, String[]> map = request.getParameterMap(); Set<String> keySet = map.keySet(); Iterator<String> iterator = keySet.iterator(); while(iterator.hasNext()) { String key = (String) iterator.next(); System.out.println("key="+key+",的值總數" + map.get(key).length); String value = map.get(key)[0]; String value1 = map.get(key)[1]; String value2 = map.get(key)[2]; System.out.println(key+" == "+value + "=" + value1 + "=" + value2); // http://localhost:8080/RequestDemo01/Demo01?name=dashucoding&address=GD // name=zhangsan&name=lisi } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
如果看了覺得不錯
點贊!轉發!
達叔小生:往後餘生,唯獨有你
You and me, we are family !
90後帥氣小夥,良好的開發習慣;獨立思考的能力;主動並且善於溝通
簡書部落格: 達叔小生
https://www.jianshu.com/u/c785ece603d1結語
- 下面我將繼續對 其他知識 深入講解 ,有興趣可以繼續關注
- 小禮物走一走 or 點贊