一、HttpServlet使用demo(这种方式麻烦了)
复写doGet/doPost方法
Tomcat虚拟路径还是使用/
(类似上一篇博客)
httpservlet_test写:
package cn.it.web.servlet;
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;
/**
* @author QLBF
* @version 1.0
* @date 2020/11/21 21:20
*/
@WebServlet("/demo4")
public class httpservlet_test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doget...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("dopost...");
}
}
要测试dopost方法,我们建了test_dopost.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<form action="/demo4" method="post">
<input name="username"></input>
<input type="submit" value="提交">
</form>
</body>
</html>
注意test_dopost.html的action写的是/demo4是对应上面代码@WebServlet("/demo4")的
然后启动tomcat,先访问html:
提交后就访问
就会在控制台输出:
二、HTTP中Referer防盗链和统计
如果你页面来到http://localhost:8080/demo4
如果Referer:http://localhost:8080/test_dopost.html
代表
告诉服务器,我(当前请求)从哪里来?(是从test_dopost.html才来到demo4的)
作用:
- 防盗链:
- 统计工作:
三、HttpServlet使用demo(直接利用idea生成)
直接生成好了继承HttpServlet和重写了里面的方法了:
在包中直接不是新建一个Java class而是新建一个Servlet了
package cn.it.web.servlet;
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;
/**
* @author QLBF
* @version 1.0
* @date 2020/11/22 15:59
*/
@WebServlet("/demo5")
public class Servlet_demo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String contextPath = request.getContextPath();
System.out.println(contextPath);
String requestURI = request.getRequestURI();
System.out.println(requestURI);
StringBuffer requestURL = request.getRequestURL();
System.out.println(requestURL);
}
}