创建project和module
这里的web文件夹里的部分内容可以通过右键->add Framwork Support->JAVAEE->WEB APPLICATION->create web.xml来创建(我的可能因为版本原因,只创建了web文件夹和index.jsp)
引入相关依赖
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
创建servlet的class文件
注意点:
- 创建一个类继承HttpServelet
- 复写doPost和doGet,并在doPost中调用doGet
- 在doGet中完成逻辑
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取参数
String method = req.getParameter("method");
if(method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if(method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
req.getRequestDispatcher("WEB-INF/jsp/hello.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
创建jsp
在WEB-INF/jsp下创建hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello jsp</title>
</head>
<body>
${msg}
</body>
</html>
创建web.xml
- 创建servlet(指定servlet的名字和servlet类的路径)
- 完成servlet的映射(指定可以通过什么url路径访问上面创建的某个servlet)
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.kuang.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
创建tomcat并启动
在Edit Configuration中进行相关配置。
访问
在地址栏中输入http://localhost:8080/hello?method=add访问