概述:
Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
但是使Servlet能够处理以上请求的前提条件是Servlet对象要被布置在Servlet容器当中,Tomcat服务器就是一种Servlet容器。Servlet的使用和JSP不同,它需要web.xml文件的配置。当一个客户端发出HTTP请求时,服务器会根据配置文件中的配置信息将该请求的信息发送给相对应的Servlet进行处理。
Servlet就是一段由java编写的程序,由服务器来维护。为了方便服务器的处理,Servlet需要遵循一定的结构规范。通常我们所说的Servlet就是一个实现了HttpServlet抽象类的类的实例。
下面写个建单的servlet试一下:
servlet运行环境:servlet服务器tomcat9,jdk8,编辑器。
servlet程序在web服务器中运行需要指定的目录结构(要遵循一定的规范):
在tomcat的webapps目录下新建目录结构SimpleServlet/WEB-INF/classes,展开如下:
SimpleServlet
|-WEB-INF
| |-classes
| | |-ServTest.class
| |-web.xml
|-index.jsp
|-ServTest.java
index.jsp
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>Servlet</title>
</head>
<body>
<center>
<form action="MyServlet" name="form" method="post">
Your Name:<input type="text" name="USERNAME"><br>
<input type="submit" value="SUBMIT"></form>
</center>
</body>
</html>
ServTest
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class ServTest extends HttpServlet {
//handle post request
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out = response.getWriter();
String name = request.getParameter("USERNAME");
out.println("<html lang='en'>");
out.println("");
out.println("<head>");
out.println("<meta charset='UTF-8' />");
out.println("<title>Servlet</title>");
out.println("<title><%=request.getServletContext().getServerInfo() %></title>");
out.println("<link href='/SimpleServlet/favicon.png' rel='shortcut icon' type='image/x-icon' />");
out.println("</head>");
out.println("<body>");
out.println("Your Name : <b><font color='red'>" + name + "</font></b>");
out.println("</body>");
out.println("<html>");
}
//destroy
public void destroy() {}
}
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_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>ServletHandle</servlet-name>
<servlet-class>ServTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletHandle</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
在web容器中java源文件是没有用的,需要变异成class文件
命令:javac -classpath D:\工具软件\apache-tomcat-9.0.8\lib\servlet-api.jar -d WEB-INF/classes ServTest.java
-classpath:指明编译需要的库(就是jar)
-d:指明编译后生成的class文件存放的地址
最后是需要编译的java源文件。
这样就可以tomcat启动起来,体验一下servlet。
参考文件:https://blog.youkuaiyun.com/a153375250/article/details/50916428
https://blog.youkuaiyun.com/tiger925/article/details/8615406