java代码:
1 package servlet_pack; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Enumeration; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class RequestHeaderServlet 15 */ 16 @WebServlet("/RequestHeaderServlet") 17 public class RequestHeaderServlet extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public RequestHeaderServlet() { 24 super(); 25 } 26 27 /** 28 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 29 */ 30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 31 Enumeration enu = request.getHeaderNames(); 32 response.setContentType("text/html"); 33 PrintWriter out = response.getWriter(); 34 out.print("<!DOCTYPE html>"); 35 out.print("<html>"); 36 out.print("<head>"); 37 out.print("<title>A Servlet</title>"); 38 out.print("</head>"); 39 out.print("<body>"); 40 out.print("<table>"); 41 42 out.print("<tr>"); 43 out.print("<th>"); 44 out.print("HeaderName"); 45 out.print("</th>"); 46 out.print("<th>"); 47 out.print("HeaderValue"); 48 out.print("</th>"); 49 out.print("</tr>"); 50 51 while(enu.hasMoreElements()){ 52 String headerName = (String)enu.nextElement(); 53 String headerValue = request.getHeader(headerName); 54 55 out.print("<tr>"); 56 out.print("<td>"); 57 out.print(headerName); 58 out.print("</td>"); 59 out.print("<td>"); 60 out.print(headerValue); 61 out.print("</td>"); 62 out.print("</tr>"); 63 } 64 65 out.print("</table>"); 66 out.print("</body>"); 67 out.print("</html>"); 68 } 69 70 /** 71 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 72 */ 73 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 74 doGet(request, response); 75 } 76 77 }
Test.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <form name="f1" action="/4_Servlet_Request_Header/RequestHeaderServlet" method="get"> 9 <table> 10 <tr> 11 <td>用户名:</td> 12 <td><input type="text" name="username"></td> 13 </tr> 14 15 <tr> 16 <td>密码:</td> 17 <td><input type="password" name="password"></td> 18 </tr> 19 <tr> 20 <td colspan="2" align="center"><input type="submit" value="注册"></td> 21 </tr> 22 </table> 23 </form> 24 </body> 25 </html>
运行结果:
原文地址:https://www.cnblogs.com/ACGame/p/8451506.html
时间: 2024-10-16 03:40:30