编写HTML表单提交并接受数据信息(获取用户通过表单提交的内容)

时间:2021-03-28 22:18:19

MyInfoForm.java

package com.fxl;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInfoForm extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("用户名:
");
out.println("密 码:
");
out.println("性 别:男 女
");
out.println("你的爱好:体育音乐旅游读书
");
out.println("所在城市:" +
"北京" +
"天津" +
"上海" +
"杭州" +
"
");
out.println("你的介绍:请输入介绍...
");
out.println("提交照片:
");
//什么时候使用hidden传数据。1 不愿意让用户看到数据 2 不希望影响界面,同时业务逻辑要使用该数据,到时把value做成变量即可
out.println("");
out.println("");
out.println("");

}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
接受表单提交信息
RegisterCl.java

package com.fxl;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterCl extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String u=request.getParameter("username");
String p=request.getParameter("pwd");
String sex=request.getParameter("sex");
//如果接受复选框的内容,则使用getparameterValues
String [] hobbies=request.getParameterValues("hobby");
String city=request.getParameter("city");
String intro=request.getParameter("intro");
String hidden1=request.getParameter("hidden1");
out.println("用户名="+u+"
");
out.println("密 码="+p+"
");
out.println("性 别="+sex+"
");
if(hobbies!=null){
for(int i=0;i所在城市:"+city);
out.println("
个人介绍:"+intro);
out.println("
隐藏控件传递的数据:"+hidden1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}