1.在webapp下建立a.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/demo-05/hello" method="get">
<input type="submit">
</form>
</body>
</html
然后再从com.atguigu.servlet类中进行相关的设置
package com.atguigu.servlet;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class helloServlet implements Servlet {
public helloServlet() {
System.out.println("1 构造器");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2.init方法");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
// HttpServletRequest为ServletRequest的子类
// HttpServletRequest中有获取“采用什么方法提交”的方法
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String method = httpServletRequest.getMethod();
if(method.equals("GET")){
// 有时候此区域通常有大量的逻辑代码,会显得很繁琐
// 所以会把大量的代码封装到一个方法中
getmethod();
}else {
postmethod();
}
}
public void getmethod(){
System.out.println("get 请求");
}
public void postmethod(){
System.out.println("post 请求");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4.销毁方法");
}
}
步骤:
1.在com.atguigu.servlet包下建立helloHttpServlet类并继承HttpServlet
2.重写doGet和doPost方法
3.在web.xml文件中配置访问路径
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.atguigu.servlet.helloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<!-------给“继承HttpServlet的类”配置访问路径------>
<servlet>
<servlet-name>helloHttpServlet</servlet-name>
<servlet-class>com.atguigu.servlet.helloHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloHttpServlet</servlet-name>
<url-pattern>/hello2</url-pattern>
</servlet-mapping>
</web-app>
4.修改a.html文件中的提交路径(/hello2)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/demo-05/hello2" method="post">
<input type="submit">
</form>
</body>
</html>
测试结果
补充配置即可