Servlet快速入门
概述
简介:Servlet简单的讲就是Java的一门动态Web资源开发的技术,是JavaWeb的核心,是Javaee的规范之一,本质上就是一个封装好了的接口。
快速入门
创建顺序
创建项目
详情看我这篇文章:IDEA2022如何创建web项目
文件结构
配置文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>web-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <!-- tomcat 插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> </plugin> </plugins> </build> </project>
Servlet部分
import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/login") public class ServletDemo implements Servlet { @Override public void init(ServletConfig servletConfig) throws ServletException { } @Override public ServletConfig getServletConfig() { return null; } @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // 获取参数username String username = request.getParameter("username"); // 设置字符集 response.setContentType("text/html;charset=utf-8"); // 设置打印在网页上 PrintWriter writer = response.getWriter(); if ("zhangsan".equals(username)){ writer.write("张三,欢迎你"); } else if ("lisi".equals(username)){ writer.write("李四,欢迎你"); } else { writer.write("没有这个人"); } } @Override public String getServletInfo() { return null; } @Override public void destroy() { } }
运行结果