标签:
该示例采用doPost方法提交表单,该示例一共包含两个文件。
一个是用来提交用户信息的表单userForm2.jsp,另一个是用来接收参数的Servlet。
userForm2.jsp
1 <%@ page language="java" contentType="text/html;charset=gb2312"%> 2 3 <html> 4 <head><title>用户表单</title></head> 5 6 <body> 7 <form action="DoPostDemo" method="post"> 8 用户名:<input type="text" name="username"><br /> 9 密码:<input type="password" name="password"><br /> 10 <input type="submit" value="提交"> 11 <input type="reset" value="重置"> 12 </form> 13 </body> 14 </html>
接收参数的Servlet
1 package com.mhb; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class DoPostDemo extends HttpServlet { 12 public void init() throws ServletException { 13 } 14 public void doPost(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 response.setContentType("text/html;charset=gb2312"); 17 PrintWriter out = response.getWriter(); 18 19 //设置接收参数的编码格式 20 request.setCharacterEncoding("gb2312"); 21 //获取username,password参数 22 String username = request.getParameter("username"); 23 String password = request.getParameter("password"); 24 25 out.println("<HTML>"); 26 out.println("<BODY>"); 27 out.print("用户名:"+username+"<br />"); 28 out.print("密码:"+password+"<br />"); 29 out.println(" </BODY>"); 30 out.println("</HTML>"); 31 } 32 public void destroy() { 33 super.destroy(); 34 } 35 }
web.xml配置
<servlet> <servlet-name>DoPostDemo</servlet-name> <servlet-class>com.mhb.DoPostDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>DoPostDemo</servlet-name> <url-pattern>/DoPostDemo</url-pattern> </servlet-mapping>
浏览器显示:
Servlet小示例:jsp页面提交信息Servlet接收并打印输出
标签:
原文地址:http://www.cnblogs.com/tdcqma/p/4757307.html