java中獲取網頁的get或post數據的方法有以下三種:
本次的實例主要是關於getParameter(), getParameterValues()的。
實例:
HTML:
1 <!DOCTYPE html> 2 <!--為了簡潔,不寫注釋啦--> 3 <html> 4 <head> 5 <meta charset="utf-8" /> 6 <title>entity</title> 7 <meta name="description" content="this is description" /> 8 <meta name="keywords" content="keyword1,keyword2,keyword3" /> 9 </head> 10 <body> 11 <h1>Get Form Information</h1> 12 <hr/> 13 <form action="servlet/Test" method="post"> 14 <table><tbody> 15 <tr> 16 <td>姓名:</td> 17 <td><input type="text" name="username" /></td> 18 </tr> 19 <tr> 20 <td>愛好:</td> 21 <td><input type="checkbox" name="hobby" value="NBA" />NBA <input type="checkbox" name="hobby" value="旅游" 22 23 />旅游 <input type="checkbox" name="hobby" value="看書" />看書 24 </td> 25 </tr> 26 <tr> 27 <td><input type="submit" value="提交數據"/></td> 28 <td><input type="reset" value="重置數據" /></td> 29 </tr> 30 <tr></tr> 31 </tbody></table> 32 </form> 33 </body> 34 </html>
Servlet代碼:servlet/Test.java:
1 package servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.text.SimpleDateFormat; 6 import java.util.Date; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 14 15 public class Test extends HttpServlet { //實現HttpServlet中的doGet的方法 44 public void doGet(HttpServletRequest request, HttpServletResponse response) 45 throws ServletException, IOException { //get方式和post差不多,亂碼問題比較難解決 54 55 } 56 //實現HttpServlet中的doPost的方法 67 public void doPost(HttpServletRequest request, HttpServletResponse response) 68 throws ServletException, IOException { 69 //解決Post中的中文亂碼 70 request.setCharacterEncoding("utf-8"); 71 73 String username,mypassword ; 74 String[] favorite; PrintWriter out = response.getWriter(); 76 77 78 try 79 {
//通過getParameter獲得單參數值 80 username = request.getParameter("username");
//向後台輸出 81 System.out.println("Post method username = "+username); 82 out.println("姓名:"+usrname);
//通過getParameterValues方法獲得復選框的的值 83 favorite = request.getParameterValues("hobby"); out.println("愛好:"+favorite); 99 } 100 catch(Exception ex) 101 { 102 ex.printStackTrace(); 103 } 104 105 106 } 118 }
Servlet代碼中第80行和83行是getParameter()和getParameterValues()的使用。
此處沒有寫get方式,一是因為要解決中文亂碼,二和post方式一樣,就不多寫啦,掌握其思想就行,getParameterNames()我感覺不太常用,也不寫啦。