需求
制作一个表单,获取用户名、密码和兴趣爱好 然后把这个表单丢给servlet处理,让servlet获取其中的属性值
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Complete A Form</title>
</head>
<body>
<form action="/ServletTest_war_exploded/Servlet05" method="POST">
用户名: <input type="text" name="username"><br/>
密码: <input type="password" name="password"><br/>
爱好:
<input type="checkbox" name="hobby" value="sing">唱歌
<input type="checkbox" name="hobby" value="dance">跳舞
<input type="checkbox" name="hobby" value="game">玩游戏<br/>
<input type="submit" value="提交">
</form>
</body>
</html>
注意,这里的action写的是servlet所处的地址,/ServletTest_war_exploded/Servlet05,前面的是项目地址,后面的是自定义地址
Servlet05.java
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;
@WebServlet(name = "Servlet05", value = "/Servlet05")
public class Servlet05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
out.println("username:" + name);
out.println("password:" + password);
String[] hobbys = request.getParameterValues("hobby");
out.println("hobby:");
for (int i = 0; i < hobbys.length; i++) {
out.print(hobbys[i] + ",");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
在doGet那里获取用户Post的表单,并打印出来
结果展示
form.html /Servlet05
总结
Servlet这个动作,实现一个跳转 + 处理post信息的综合功能
|