JavaWeb筆記,request接值與處理動態網頁
阿新 • • 發佈:2018-12-01
在servlet中,使用
String lname = request.getParameter(“lname”);
來接收html中表單提交的內容,注意,html中提交的內容需要新增name=“lname”
這個request方法是用過元素的name來獲取資料
以後在servlet中,所有的程式都在dopost中寫,然後在doget中呼叫dopost
Dopost方式不能直接獲得中文,正常需要新增轉碼程式碼:
request.setCharacterEncoding(“tuf-8”);
html中的程式碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="http://localhost:8080/20181129/RegistServlet" method="post"> 使用者名稱:<input type="text" name="lname"><br> 密碼:<input type="password" name="lpass"><br> 密碼確認:<input type="password" name="rpass"><br> 性別:<input type="radio" name="lsex" value="1">男 <input type="radio" name="lsex" value="2">女 <input type="radio" name="lsex" value="3">保密 地區:<select name="larea"> <option value="china">china</option> <option value="japan">japan</option> <option value="korean">korean</option> </select><br> 愛好:<input type="checkbox" name="ah" value="chifan">chi,fan <input type="checkbox" name="ah" value="heshui">he,shui <input type="checkbox" name="ah" value="shuijiao">shui,jiao <input type="submit" value="提交"> </form> </body> </html>
servlet中的程式碼:
package com.neuedu.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; @WebServlet("/RegistServlet") public class RegistServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String lname = request.getParameter("lname"); String lpass = request.getParameter("lpass"); String rpass = request.getParameter("rpass"); String lsex = request.getParameter("lsex"); String larea = request.getParameter("larea"); String[] ah = request.getParameterValues("ah"); System.out.println(lname); System.out.println(lpass); System.out.println(rpass); System.out.println(lsex); System.out.println(larea); for(String item : ah) { System.out.println(item); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }