Servlet 如何获取表单提交的数据呢?
获取表单数据是每一个Web应用都必须面对的事情,那么Servlet后台程序如何获取表单提交的数据呢?
下文将一一道来,如下所示:
下文将一一道来,如下所示:
实现思路: 1. getParameter():request.getParameter(控件name)获取指定表单控件的值 如: <input type="text" name="uuu" /> String t = request.getParameter("uuu"); 2.getParameterValues(): 当一个控件出现超过一次以上, 我们可以使用此方法,获取控件对应的多个值,如:checkbox控件 3.getParameterNames(): 此方法可以获取表单中所有参数列表信息例: Servlet Post请求示例分享
一、新建PostTest.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Java265.com -Post获取数据测试</title> </head> <body> <body> <form action="/servlet01/helloWorld" method="POST" target="_Self"> <input type="checkbox" name="program" checked="checked" value="java265" /> Java265 <input type="checkbox" name="program" value="donet" /> donet <input type="checkbox" name="program" value ="python" checked="checked" /> Python <br /> <input type="text" name="urlInfo" value="java265.com" /> <br /> <input type="submit" value="submit" /> </form> </body> </html> 二、修改ServletHelloWorld.java代码 package servlet01; import java.io.IOException; import java.io.PrintWriter; 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("/helloWorld") public class ServletHelloWorld extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); String program = ""; if (req.getParameter("program") != null) { String[] strlist = req.getParameterValues("program"); for (int t = 0; t < strList.length; t++) { program = program + "|" + strList[t]; } } String urlInfo = ""; if (req.getParameter("urlInfo") != null) { urlInfo = new String(req.getParameter("urlInfo").getBytes("ISO-8859-1"), "UTF-8"); } // 输出获取的值 PrintWriter o = resp.getWriter(); o.println("<h4>Java265.com -Post TestCase</h4>"); o.println("<h5>GetParameter-program:" + program + "</h5>"); o.println("<h5>GetParameter-urlInfo:" + urlInfo + "</h5>"); } /** * */ private static final long serialVersionUID = 888; private String msg; @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); msg = "java265.com is Java WebSite."; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub resp.setContentType("text/html"); String urlInfo = ""; if (req.getParameter("urlInfo") != null) { urlInfo = new String(req.getParameter("urlInfo").getBytes("ISO-8859-1"), "UTF-8"); } // 输出获取的值 PrintWriter o = resp.getWriter(); o.println("<h4>" + msg + "</h4>"); o.println("<h5>GetParameter:" + urlInfo + "</h5>"); } } 三、在Tomcat中进行测试
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。