Servlet
HelloWorld
package org.westos.demo;
import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;
/**
* @author lwj
* @date 2020/8/15 9:29
*/
public class MyServlet implements Servlet {
private ServletConfig servletConfig;
public MyServlet() {
System.out.println("构造方法执行了");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
//servletConfig 配置对象,是个接口,服务器创建子类对象传递给init方法
System.out.println(servletConfig);
//org.apache.catalina.core.StandardWrapperFacade@51faaa70
//用途:获取该Servlet的配置信息
Enumeration<String> initNames = servletConfig.getInitParameterNames();
while (initNames.hasMoreElements()) {
String s = initNames.nextElement();
String initParameter = servletConfig.getInitParameter(s);
System.out.println(s + ":" + initParameter);
//name:John
}
String servletName = servletConfig.getServletName();
System.out.println(servletName);
//MyServlet
ServletContext servletContext = servletConfig.getServletContext();
System.out.println(servletContext);
//org.apache.catalina.core.ApplicationContextFacade@6a4b14b7
//ServletContext,全局上下文对象,代表你整个Web应用
//ServletContext对象包含在ServletConfig中,ServletConfig对象在初始化Servlet时由Web容器提供给Servlet
//该Servlet使用ServletContext接口中定义的方法与其Servlet容器进行通信
//init()方法只调用一次,默认情况下第一次访问Servlet时,才会创建,执行初始化init
System.out.println("init方法调用了");
this.servletConfig = servletConfig;
}
@Override
public ServletConfig getServletConfig() {
return servletConfig;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("请求到达,开始处理请求...");
ServletConfig servletConfig = getServletConfig();
servletResponse.getWriter().write("Hello Welcome.");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("destroy方法调用过了,正常关闭服务器时,在销毁servlet之前执行destroy方法");
}
}
配置Servlet
<?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>MyServlet</servlet-name>
<servlet-class>org.westos.demo.MyServlet</servlet-class>
<!--配置Servlet的初始化参数-->
<init-param>
<param-name>name</param-name>
<param-value>John</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--默认值-1,在第一次访问Servlet时调用-->
<!--只需要给一个非负数,启动服务器就创建Servlet,该数越小,优先级越高,0最高,当多个Servlet的启动优先级别相等时,默认按顺序启动-->
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlet是单例多线程。
GenericServlet
Defines a generic, protocol-independent servlet。
定义一般的,与协议无关的Servlet。
package javax.servlet;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
private static final long serialVersionUID = 1L;
private transient ServletConfig config;
public GenericServlet() {
}
public void destroy() {
}
public String getInitParameter(String name) {
return this.getServletConfig().getInitParameter(name);
}
public Enumeration<String> getInitParameterNames() {
return this.getServletConfig().getInitParameterNames();
}
public ServletConfig getServletConfig() {
return this.config;
}
public ServletContext getServletContext() {
return this.getServletConfig().getServletContext();
}
public String getServletInfo() {
return "";
}
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
public void log(String message) {
this.getServletContext().log(this.getServletName() + ": " + message);
}
public void log(String message, Throwable t) {
this.getServletContext().log(this.getServletName() + ": " + message, t);
}
public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
public String getServletName() {
return this.config.getServletName();
}
}
只保留service()作为抽象方法。
package org.westos.demo;
import javax.servlet.*;
import java.io.IOException;
/**
* @author lwj
* @date 2020/8/15 11:05
*/
public class MyGenericServlet extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
ServletConfig servletConfig = getServletConfig();
}
}
HttpServlet
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
} catch (ClassCastException var6) {
throw new ServletException(lStrings.getString("http.non_http"));
}
this.service(request, response);
//调用service
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
long lastModified;
if (method.equals("GET")) {
lastModified = this.getLastModified(req);
if (lastModified == -1L) {
this.doGet(req, resp);
} else {
long ifModifiedSince;
try {
ifModifiedSince = req.getDateHeader("If-Modified-Since");
} catch (IllegalArgumentException var9) {
ifModifiedSince = -1L;
}
if (ifModifiedSince < lastModified / 1000L * 1000L) {
this.maybeSetLastModified(resp, lastModified);
this.doGet(req, resp);
} else {
resp.setStatus(304);
}
}
} else if (method.equals("HEAD")) {
lastModified = this.getLastModified(req);
this.maybeSetLastModified(resp, lastModified);
this.doHead(req, resp);
} else if (method.equals("POST")) {
this.doPost(req, resp);
} else if (method.equals("PUT")) {
this.doPut(req, resp);
} else if (method.equals("DELETE")) {
this.doDelete(req, resp);
} else if (method.equals("OPTIONS")) {
this.doOptions(req, resp);
} else if (method.equals("TRACE")) {
this.doTrace(req, resp);
} else {
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[]{method};
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
关键:doGet()和doPost(),所以我们只要重写doGet()和doPost()方法。
当请求到来执行service()方法时,会执行到我们重写的方法。多态访问成员方法:编译看左,运行看右。
package org.westos.demo;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author lwj
* @date 2020/8/15 11:10
*/
public class MyHttpServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get请求来了");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post请求来了");
}
}
<?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>MyHttpServlet</servlet-name>
<servlet-class>org.westos.demo.MyHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServlet</servlet-name>
<url-pattern>/httpServlet</url-pattern>
</servlet-mapping>
</web-app>
表单的action选项 ※
在发布项目时,当你配置了上下文路径,/20200815-servlet这种,那么在表单的action选项中就需要加上上下文路径,/20200815-servlet/httpServlet,以后会使用动态代码来拿上下文路径。
如果你的上下文路径是/,那么在表单的action选项中就不需要加上下文路径,只需要/httpServlet即可。
测试HttpServlet的Get请求和POST请求。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<form action="/httpServlet" method="get">
姓名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"> <br>
<input type="submit" value="提交">
</form>
<hr>
<form action="/httpServlet" method="post">
姓名:<input type="text" name="username"> <br>
密码:<input type="password" name="password"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
get请求来了
post请求来了
表单action选项是正确的。
项目目录结构: