Servlet是Java的重要组成部分,1.什么是Servlet:Sun公司制定拓展web服务器功能组件,可以生成动态页面,承担客户端和服务端的中间层;
1.生成动态web页面;
2.组件规范:组件/容器(提供组件的运行环境,如Tomcat就是一个servlet容器)
3.servlet容器是怎么运行的:浏览器向web服务器发送请求 web服务器接收数据 发送servlet容器 然后实例化servlet 调用init方法 初始化 然后调用service方法。servlet 将处理的结构返回给web服务器 然后发送给客户端;servlet的优点只创建一个实例只初始化一次单可被多次调用
如何在项目里新建servlet可以参考 https://www.php.cn/java-article-418804.html 这篇文章,我也是安装步骤一步步安装的;直接上代码,先看一下项目简单结构:
package com.tqh;
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 MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L; //这个貌似没毛用
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("
out.println("
");out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
//看一下web.xml配置,index.jsp, 访问 http://localhost:7070/MyServlet/test/hello?username=111&pwd=222
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//GET方式获取参数
String username = request.getParameter("username").trim(); // 111
String pwd = request.getParameter("pwd").trim(); // 222
username += ", username="+username;
username += ", pwd="+pwd; //用户名密码拼接 方便输出
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("
out.println("
");out.print(" This is ");
out.print(this.getClass());
out.println(username);
out.println(" ");
out.println("");
out.flush();
out.close();
}
}
web.xml : 注意这里一定要加
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">
index.jsp : JSP的知识点大家可自己去了解一下(PHP前后端早就分离很久了,早就用上了vue/bootstrap等,java还....)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$END$
配置servlet和安装tomcat上面的外链大家可以看一下,我们来看一下效果:
还有很多不足,还请大家多多指点,谢谢!