当
Tomcat
通过
Socket API
读取
HTTP
请求
(
字符串
),
并且按照
HTTP
协议的格式把字符串解析成
HttpServletRequest
对象
.
主要方法:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//路径和servlet类一一对应
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
@Override
public void init() throws ServletException {
//在这里实现自己需要的初始化
System.out.println("init1");
}
@Override
public void destroy() {
System.out.println("destroy");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//这里是设置响应的content-type. 告诉浏览器,响应body 里的数据格式是啥样的。
resp. setContentType(" text/html");
//这里是设置响应的content-type. 告诉浏览器,响应body 里的数据格式是啥样的。
resp. setContentType(" text/html");
//搞个StringBuilder, 把这些api 的结果拼起来,统一 写回到响应中.
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(req.getProtocol());
stringBuilder.append("<br>");
stringBuilder.append(req.getMethod());
stringBuilder.append("<br>" );
stringBuilder.append(req.getRequestURI());
stringBuilder.append("<br>");
stringBuilder.append(req.getContextPath());
stringBuilder.append("<br>");
stringBuilder.append(req.getQueryString());
stringBuilder.append("<br>");
resp.getWriter().write(stringBuilder.toString());
}
}
由于没有输入所以后面的为空,若在地址栏输入?a=10&b=20,最后就不是null