您好,登錄后才能下訂單哦!
一、簡介
web服務器收到客戶端的Http請求后,會針對每一次請求,分別創建一個用于代表請求的request對象和代表響應的response對象。
request和response既然代表請求和響應,那么我們要獲取客戶端提交過來的數據,只需要找request對象就可以了,要向客戶機輸出數據,僅僅需要找response對象就行了。
Response對象
二、響應
響應行
public void setStatus(int sc)設置狀態碼
響應頭:key:value的形式,一個key可以對應一個value,一個key可以對應多個value
設置頭信息
public void setHeader(String name,String value) 一個key對應一個value,經常使用
public void setIntHeader(String name,int value)
public void setDateHeader(String name,long date)
public void addHeader(String name,tring value) 一個key對應多個value
public void addIntHeader(String name,int value)
public void addDateHeader(String name,long date)
響應體
public ServletOutputStream getOutputStream()throws IOException 字節輸出流
public PrintWriter getWriter() throws IOException 字符輸出流
三、response代碼案例之重定向(登錄頁面)
登錄頁面的重定向
狀態碼是302 響應頭是location
需求:登錄頁面,用戶名和密碼的登錄頁面,用戶名和密碼都是admin,如果有一個不是,重定向到登錄頁面,重新登錄。
在webRoot下新建login.html
<!DOCTYPE html> <html> <head> <title>loginl.html</title> <meta name="keywords" content="keyword1,keyword2,keyword3"> <meta name="description" content="this is my page"> <meta name="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body> <form action="/day10/login" method="post"> <table> <tr> <td>用戶名</td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td>密碼</td> <td> <input type="password" name="password"/> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="登錄"/> </td> </tr> </table> </form> </body> </html>
新建cn.servlet.LoginServlet類
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取用戶名 String username = request.getParameter("username"); //獲取密碼 String password = request.getParameter("password"); if("admin".equals(username) && "admin".equals(password)){ //登錄成功 response.setCharacterEncoding("utf-8"); response.getWriter().print("登錄成功!"); }else{ //登錄失敗,重定向到登錄頁面 // 設置302的狀態碼 response.setStatus(302); // 設置地址 response.setHeader("location", "/day10/login.html"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
public void sendRedirect(String path) 可以完成重定向
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取用戶名 String username = request.getParameter("username"); //獲取密碼 String password = request.getParameter("password"); if("admin".equals(username) && "admin".equals(password)){ //登錄成功 response.setCharacterEncoding("utf-8"); response.getWriter().print("登錄成功!"); }else{ //登錄失敗,重定向到登錄頁面 // 設置302的狀態碼 //response.setStatus(302); // 設置地址 //response.setHeader("location", "/day10/login.html"); response.sendRedirect("/day10/login.html"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml配置如下
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>cn.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>
四、response代碼案例之頁面定時刷新(頁面讀秒操作)
響應頭 refresh
新建cn.servlet.RefreshServlet.java
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 頁面的定時刷新 */ @SuppressWarnings("serial") public class RefreshServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); response.getWriter().println("<h2>頁面將在5秒后跳轉</h2>"); //通過refresh頭完成頁面刷新 response.setHeader("refresh", "5;URL=/day10/login.html"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>RefreshServlet</servlet-name> <servlet-class>cn.servlet.RefreshServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RefreshServlet</servlet-name> <url-pattern>/refresh</url-pattern> </servlet-mapping> </web-app>
在webRoot下新建refresh.html
<!DOCTYPE html> <html> <head> <!-- 5秒后跳轉 --> <meta charset="UTF-8"> <title>頁面的定時跳轉</title> <meta http-equiv="refresh" content="5;URL=/day10/login.html"/> </head> <body > <h3>頁面將在<span id="spanId">5</span>秒后跳轉</h3> </body> <script type="text/javascript"> /* 讀秒操作 頁面一加載,加載事件 onload 執行讀秒的操作,每隔一秒變一次 使用js的定時器 */ window.onload = function(){ var x = 5; window.setInterval(function() { var span = document.getElementById("spanId"); span.innerHTML = x; x--; }, 1000) } </script> </html>
五、response代碼案例之禁用瀏覽器緩存
應用:網銀等
Cache-Control:no-cache
Expires:-1 值是日期類型
Pragma:no-Cache
新建cn.servlet.DateServlet
package cn.servlet; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 禁用瀏覽器緩存 */ @SuppressWarnings("serial") public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * Cache-Control : no-cache * Expires: -1 值是日期類型(setDateHeader()) * Pragma : no-cache */ //設置三個頭信息 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", -1); response.setHeader("Pragma", "no-cache"); //向頁面輸出當前的事件 //獲取當前的時間 Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str = format.format(date); //輸出 response.getWriter().println(str); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>DateServlet</servlet-name> <servlet-class>cn.servlet.DateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DateServlet</servlet-name> <url-pattern>/date</url-pattern> </servlet-mapping> </web-app>
六、response代碼案例之中文輸出問題
新建cn.servlet.OutServlet.java類
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class OutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printWriter(response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * 字符輸出中文是否亂碼 * 一定亂碼 * response緩沖區的編碼默認是ISO-8859-1 * 設置瀏覽器打開文件所采用的編碼 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * @throws IOException * */ public void printWriter(HttpServletResponse response) throws IOException { response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getWriter().println("世界這么大 我想去看看"); } /** * 字節輸出中文 * 輸出“世界這么大 我想去看看”是否亂碼? * 不一定亂碼 * 解決辦法: * 設置瀏覽器打開文件時所采用的編碼 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * 獲取字符串byte[]數組的編碼和瀏覽器打開文件時候的編碼相同 * "世界這么大 我想去看看".getBytes("utf-8"); * @throws IOException * */ public void printOutPutStream(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getOutputStream().write("世界這么大 我想去看看".getBytes("utf-8")); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>OutServlet</servlet-name> <servlet-class>cn.servlet.OutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OutServlet</servlet-name> <url-pattern>/out</url-pattern> </servlet-mapping> </web-app>
簡寫
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class OutServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { printWriter(response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } /** * 字符輸出中文是否亂碼 * 一定亂碼 * response緩沖區的編碼默認是ISO-8859-1 * 設置瀏覽器打開文件所采用的編碼 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * * 簡寫: * response.setContentType("text/html;charset=UTF-8"); * @throws IOException * */ public void printWriter(HttpServletResponse response) throws IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().println("世界這么大 我想去看看"); } /** * 字節輸出中文 * 輸出“世界這么大 我想去看看”是否亂碼? * 不一定亂碼 * 解決辦法: * 設置瀏覽器打開文件時所采用的編碼 * response.setHeader("Content-Type", "text/html;charset=utf-8"); * 獲取字符串byte[]數組的編碼和瀏覽器打開文件時候的編碼相同 * "世界這么大 我想去看看".getBytes("utf-8"); * @throws IOException * */ public void printOutPutStream(HttpServletResponse response) throws IOException { response.setHeader("Content-Type", "text/html;charset=utf-8"); response.getOutputStream().write("世界這么大 我想去看看".getBytes("utf-8")); } }
六、response代碼案例之文件下載初級實現
超鏈接:瀏覽器可以解析直接打開
彈出下載窗口:
前提條件:先準備一個文件
讀取文件,讀取到輸入流中,通過response輸出到瀏覽器。
設置頭信息:
Content-Disposition attachement;filename=文件名稱
以附件的形式打開
新家cn.servlet.DownloadServlet.java類
package cn.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class DownloadServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //先獲取文件,讀入輸入流中 //獲取文件的絕對磁盤路徑 ServletContext context = this.getServletContext(); String path = context.getRealPath("/img/psb.jpg"); String filename = path.substring(path.lastIndexOf("/")+1); response.setHeader("Content-Disposition", "p_w_upload;filename="+filename); InputStream is = new FileInputStream(path); OutputStream os = response.getOutputStream(); byte[] b = new byte[1024]; int len = 0; while((len = is.read(b)) != -1){ os.write(b, 0, len); } is.close(); os.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>cn.servlet.DownloadServlet</servlet-class> </servlet> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/download</url-pattern> </servlet-mapping> </web-app>
七、response代碼案例之實現驗證碼
7.1驗證碼的熱身
package cn.servlet; import java.awt.Color; import java.awt.Graphics; import java.awt.p_w_picpath.BufferedImage; import java.io.IOException; import javax.p_w_picpathio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 驗證碼的熱身 */ @SuppressWarnings("serial") public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //在內存中生成圖片 BufferedImage p_w_picpath = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB); //獲取畫筆對象 Graphics g = p_w_picpath.getGraphics(); //設置顏色 g.setColor(Color.RED); //畫矩形 g.drawRect(80, 80, 150, 100); g.setColor(Color.YELLOW); //定義字符串 String str = "abc"; g.drawString(str, 85, 85); //把內存中的圖片輸出的瀏覽器端 ImageIO.write(p_w_picpath, "jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>cn.servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping> </web-app>
7.2驗證碼的實現
package cn.servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.p_w_picpath.BufferedImage; import java.io.IOException; import java.util.Random; import javax.p_w_picpathio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 驗證碼 */ @SuppressWarnings("serial") public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * 在內存中生成圖片(紙) ,沒有設置背景顏色,畫填充的矩形和紙的大小相同,并且矩形有顏色 * 獲取畫筆的對象(設置顏色、設置字體、畫字符串、畫矩形) * 先準備好數據,隨機生成4個字符,把字符畫到紙上 * 畫干擾線 * 把內存中的圖片輸出的客戶端 */ //在內存中生成圖片 int width = 120; int height = 30; BufferedImage p_w_picpath = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //獲取畫筆對象 Graphics2D g = (Graphics2D) p_w_picpath.getGraphics(); //設置灰色 g.setColor(Color.gray); //畫填充的矩形 g.fillRect(0, 0, width, height); //設置顏色 g.setColor(Color.BLUE); //畫邊框 g.drawRect(0, 0, width-1, height-1); //準備數據 String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; //設置顏色 g.setColor(Color.YELLOW); //設置字體 g.setFont(new Font("隸書", Font.BOLD, 20)); Random random = new Random(); int x = 20; int y = 20; for (int i = 0; i < 4; i++) { /* * void rotate(double theta,double x,double y) * theta弧度 * 弧度 = 角度 *Math.PI / 180 * 獲取正負30的角度 */ int jiaodu = random.nextInt(60) - 30; double hudu = jiaodu*Math.PI / 180 ; g.rotate(hudu, x, y); //獲取下標 int index = random.nextInt(words.length()); //返回指定下標位置的字符,隨機獲取下標 char ch = words.charAt(index); //寫字符串 g.drawString(""+ch, x, y); g.rotate(-hudu, x, y); x += 20; } g.setColor(Color.GREEN); int x1,x2,y1,y2; //畫干擾線 for (int i = 0; i < 4; i++) { x1 = random.nextInt(width); y1 = random.nextInt(width); x2 = random.nextInt(width); y2 = random.nextInt(height); g.drawLine(x1, y1, x2, y2); } //把內存中的圖片輸出到客戶端上 ImageIO.write(p_w_picpath,"jpg", response.getOutputStream()); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>CheckCodeServlet</servlet-name> <servlet-class>cn.servlet.CheckCodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckCodeServlet</servlet-name> <url-pattern>/checkCode</url-pattern> </servlet-mapping> </web-app>
Request對象
八、HttpServletRequest
HttpServletRequest對象代表客戶端的請求,當客戶端通過HTTP協議訪問服務器的時候,HTTP強求中所有信息都封裝在這個對象之中,開發人員通過這個對象的方法,可以獲取客戶的這心信息。
九、獲取客戶端的信息
public String getRemoteAddr() 獲取IP地址
public String getMethod() 獲取請求方法
public String getContextPath() 獲取上下文路徑(虛擬路徑)
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RequestDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取IP String ip = request.getRemoteAddr(); System.out.println("客戶機的IP是:"+ip); //獲取請求的方法 String method = request.getMethod(); System.out.println("請求的方法是:"+method); //獲取虛擬路徑的名稱 String contextPath = request.getContextPath(); System.out.println("虛擬路徑的名稱:"+contextPath); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>RequestDemo</servlet-name> <servlet-class>cn.servlet.RequestDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>RequestDemo</servlet-name> <url-pattern>/requestDemo1</url-pattern> </servlet-mapping> </web-app>
十、獲取請求頭的信息
public String getHeader(String name)
public long getDateHeader(String name)
public int getIntHeader(String name)
請求頭:
referer 記住網頁的來源
User-Agent 判斷瀏覽器
if-modified-since 控制緩存
package cn.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RequestDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲取請求頭 //網頁來源 防盜鏈 String referer = request.getHeader("referer"); System.out.println("網頁來源于:"+referer); //判斷瀏覽器 文件下載 String agent = request.getHeader("User-Agent"); System.out.println("瀏覽器版本:"+agent); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>day10</display-name> <servlet> <servlet-name>RequestDemo2</servlet-name> <servlet-class>cn.servlet.RequestDemo2</servlet-class> </servlet> <servlet-mapping> <servlet-name>RequestDemo2</servlet-name> <url-pattern>/request2</url-pattern> </servlet-mapping> </web-app>
十一、獲取請求參數
public String getParameter(String name)
public String[] getParameterValues(String name)
public Map getParameterMap()
public Enumeration getParameterNames()
register.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="/day10/register" method="post"> <table> <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="男"/>男 <input type="radio" name="sex" value="女"/>女 </td> </tr> <tr> <td>選擇愛好</td> <td> <input type="checkbox" name="love" value="籃球"/>籃球 <input type="checkbox" name="love" value="足球"/>足球 <input type="checkbox" name="love" value="排球"/>排球 <input type="checkbox" name="love" value="乒乓球"/>乒乓球 </td> </tr> <tr> <td>選擇城市</td> <td> <select name="city"> <option value="none">===請選擇城市====</option> <option value="北京">北京</option> <option value="上海">上海</option> <option value="廣州">廣州</option> </select> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="注冊"/> </td> </tr> </table> </form> </body> </html>
RegisterDemo.java
package cn.servlet; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") public class RegisterDemo extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); String sex = request.getParameter("sex"); String[] love = request.getParameterValues("love"); String city = request.getParameter("city"); System.out.println("用戶名:"+username+",密碼:"+password+",性別:"+sex); for (int i = 0; i < love.length; i++) { System.out.println("愛好"+love[i]); } System.out.println("城市:"+city); System.out.println("==================="); //獲取map集合 Map<String, String[]> parameterMap = request.getParameterMap(); //循環遍歷 for(Iterator<String> keys = parameterMap.keySet().iterator();keys.hasNext();){ String key = keys.next(); String[] value = parameterMap.get(key); System.out.println("key:"+key+",value="+Arrays.toString(value)); } for(Iterator<Map.Entry<String,String[]>> iterator= parameterMap.entrySet().iterator();iterator.hasNext();){ Map.Entry<String, String[]> entry = iterator.next(); String key = entry.getKey(); String[] value = entry.getValue(); System.out.println("key:"+key+",value="+Arrays.toString(value)); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
web.xml
<?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_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>RegisterDemo</servlet-name> <servlet-class>cn.servlet.RegisterDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterDemo</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping> </web-app>
十二、request獲取中文亂碼問題
POST請求亂碼:request.setCharacterEncoding("utf-8");
GET請求亂碼:
解決方案一:修改Tomcat/conf/server,xml
<Connector port="80" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="utf-8"/>
必須有修改Tomcat服務器配置文件的權限
解決方案二:逆向編解碼
username = URLEncoder.encode(username, "ISO-8859-1");
username = URLDecoder.decode(username, "utf-8");
解決方案三:簡寫形式
username = new String(username.getBytes("iso-8859-1"),"utf-8")
十三、利用請求域傳遞對象
public Object getAttribute(String name)
public void setAttribute(String name, Object o)
public void removeAttribute(String name)
十四、重定向和轉發的區別
request對象提供了getRequestDispather方法,該方法返回一個RequestDispatcher對象,調用這個方法的forward方法可以實現請求轉發,從而共享請求中的數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。