Demo_01.java
package study;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* 使用2.5的servlet: 1.继承HttpServlet(没有的话解决方法在博客)
* 2.重写父类的doGet()和doPost()方法
* 3.配置web.xml文件
*/
public class Demo_01 extends HttpServlet{
//重写父类的两个方法(可快速生成)
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");
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="Demo_01">doGet</a><!-- 超链接都是get方式 -->
<form action="Demo_01" method="post">
<input type="submit" value="dopost">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>1_2.5的servlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 使用2.5servlet要部署的东西 -->
<servlet>
<servlet-name>a</servlet-name>
<servlet-class>study.Demo_01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>a</servlet-name>
<url-pattern>/Demo_01</url-pattern><!-- 使用相对路径 -->
</servlet-mapping>
<!--
当用户请求一个超链接时,超链接会被<servlet-mapping>的<url-pattern>拦截
然后通过<servlet-name>去寻找<servlet>中对应的<servlet-name>
最后再通过<servlet-class>寻找对应的class
-->
</web-app>