Servlet
一、Servlet简介
- 运行在Tomcat服务器中。本质是一个接口,定义动态资源规范。该接口由Tomcat内置
二、Servlet的运行流程
java
package com.zhe.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloWorldServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取请求参数值
String username = req.getParameter("username");
String info = "NO";
if("zhw".equals(username)) {
info = "YES";
}
// 响应给客户端info值
resp.getWriter().write(info);
}
}
web-inf->web.xml
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类的映射路径
1、servlet-name 用于关联的请求路径
2、servlet-class servlet类全路径
-->
<!-- 一个servlet标签可以对应多个servlet-mapping标签 -->
<servlet>
<servlet-name>userServlet</servlet-name>
<servlet-class>com.zhe.servlet.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<!-- 当前别名userServlet找到name对应的servlet标签 -->
<servlet-name>userServlet</servlet-name>
<!-- s1找到当前mapping的别名userServlet -->
<!-- 一个别名可以对应多个url-pattern -->
<!-- url-pattern的路径匹配: -->
<!-- 1、精确匹配: /s1 -->
<!-- 2、模糊匹配:
/s1/*
/*
*.xml
-->
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<!-- <servlet> -->
<!-- <servlet-name>userServlet</servlet-name> -->
<!-- <servlet-class>com.zhe.servlet.HelloWorldServlet</servlet-class> -->
<!-- </servlet> -->
<!-- <servlet-mapping> -->
<!-- <servlet-name>userServlet</servlet-name> -->
<!-- <url-pattern>/s1</url-pattern> -->
<!-- </servlet-mapping> -->
</web-app>
可以使用注解替代web.xml的配置