写一个简单的代码,获取html页面表单的值,打印在后台。
大家一定一定要注意,导入的包一定要放在web.xml目录下,否则会报500错误
ParamterServlet.html代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="http://localhost:8080/draft_war_exploded/ParamterServlet" method="get"> 用户名: <input type="text" name="username"><br> 密 码: <input type="password" name="password"><br> 兴趣爱好: <input type="checkbox" name="hobby" value="cpp">C++ <input type="checkbox" name="hobby" value="java">Java <input type="checkbox" name="hobby" value="js">JavaScript <br> <input type="submit"> </form> </body> </html>
效果:
ParamterServlet.java代码:
package demo01; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; public class ParamterServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); //获取多个值使用getParameterValues() String[] hobby = request.getParameterValues("hobby"); System.out.println(username+'\n'+password+'\n'+ Arrays.asList(hobby)+'\n'); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); //获取多个值使用getParameterValues() String[] hobby = req.getParameterValues("hobby"); System.out.println(username+'\n'+password+'\n'+ Arrays.asList(hobby)+'\n'); } }
运行起来试一下:
可以看到,后台获取到了值
这样就实现了简单的前后端交互。