Get方式是将数据通过URL附加数据显性向浏览器发送数据 如:http://localhost:8080/FirstDemo/sample?name=zhangsan
Post方式会将数据存放在”请求体”中隐性向服务器发送数据 如:http://localhost:8080/FirstDemo/sample 请求体:name=zhangsan 在地址中隐藏数据
所有请求用service()方法
Get请求 doGet()方法
Post请求 doPost()方法
用doGet()和doPost()的好处是,在同一个java文件中,可以根据HTML中method方法的不同而执行的代码不同。代码如下:
首先是java文件:
get请求,是名字为绿色,post请求 名字为红色,用以区分
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.io.PrintWriter;
public class RequestMethodServlet extends HttpServlet {
@Override
//专用于处理get请求
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String MethodName=req.getMethod();
String name=req.getParameter("name");
String mobile=req.getParameter("mobile");
String sex=req.getParameter("sex");
String[] specs=req.getParameterValues("spec");
PrintWriter out=resp.getWriter();//向浏览器输出的数据流,返回的是PrintWriter对象
out.println("<h1>Method:"+MethodName+"</h1>");
out.println("<h1 style='color:green'>name:"+name+"</h1>");
out.println("<h1>mobile:"+mobile+"</h1>");
out.println("<h1>sex:"+sex+"</h1>");
for(int i=0;i< specs.length;i++){
out.println("<h2>spec:"+specs[i]+"</h2>");
}
}
@Override
//专门用于处理post请求
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String MethodName=req.getMethod();
String name=req.getParameter("name");
String mobile=req.getParameter("mobile");
String sex=req.getParameter("sex");
String[] specs=req.getParameterValues("spec");
PrintWriter out=resp.getWriter();//向浏览器输出的数据流,返回的是PrintWriter对象
out.println("<h1>Method:"+MethodName+"</h1>");
out.println("<h1 style='color:red'>name:"+name+"</h1>");
out.println("<h1>mobile:"+mobile+"</h1>");
out.println("<h1>sex:"+sex+"</h1>");
for(int i=0;i< specs.length;i++){
out.println("<h2>spec:"+specs[i]+"</h2>");
}
}
}
下面是HTML代码 其中 method 默认为get方法
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>学生信息登记表</title>
</head>
<body>
<h1>学生信息登记表</h1>
<form action="/FirstDemo/method" method="get">
姓名:<input type="text" name="name"/><br/>
电话:<input type="text" name="mobile"> <br/>
性别:
<select name="sex" style="width: 100px;padding: 5px">
<option value="male" >男</option>
<option value="female" >女</option>
</select>
</br>
特长:<input type="checkbox" name="spec" value="English"> 英语
<input type="checkbox" name="spec" value="Program"> 编程
<input type="checkbox" name="spec" value="Speech"> 演讲
<input type="checkbox" name="spec" value="Swimming">游泳
</br>
<input type="submit" value="提交">
</form>
</body>
</html>
运行后,在HTML页面中输入以下信息后点提交
我们会发现,name那一行是绿色的。
而我们把xml文件中的method中的get改为post后点击全部部署按钮后
刷新页面 name那一行就是红色的(我mobile输的不是上一个)
而且可以使代码维护变得更加方便.而service方法就没有此类特性