您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
11-Servlet简介&快速入门
发布时间:2024-11-25 20:20:12编辑:雪饮阅读()
-
创建一个空项目,创建一根maven的web项目module,基于archetpye为webapp的模板maven-archetype-webapp
增加servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
这里scope要是provided,也就是运行时是没有servlet的,因为运行时在tomcat中是有提供servlet的,如果运行时也有,就会冲突的。
这里尤其需要说明的是要等待webapp的archetype模板完全创建完成后再添加依赖,否则他创建过程中会将你写的依赖给覆盖了。
这里你可能会在编译过程中报错如
Cannot resolve javax.servlet:servlet-api:3.1.0
原因是坐标位置改变了。
原因:仓库没有这个jar包
去仓库查找发现servlet3后就移地方了,所以改为
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
同样也增加上之前的tomcat插件,所以最终的pom如
<?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>servlet01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
同样在当前module的main下面创建java和resources
然后在java下创建package及类并实现Servlet接口。
并用WebServlet注解当前Servlet实现类的访问入口url的path。
所以当前类的实现如
package com;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/demo01")
public class ServletTest implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello world!");
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
那么最后通过maven的tomcat插件运行项目后的提示url并补齐我们webServlet注解的路径,则访问路径如
http://localhost:8080/servlet01/demo01
此时在控制台中就会有了hello world!的输出。
关键字词:Servlet,快速入门
相关文章
- 16-编写Servlet-依赖范围配置(maven项目实现servlet)
- 11_Jedis_快速入门
- 16_Listener_ServletContextListener使用(servlet容器
- 6_Filter_细节_过滤器拦截路径配置(servlet拦截与目录
- 3_Filter_快速入门(类似php中常用的中间件)
- 17_会话技术_Session_快速入门(session设置及获取)
- 03_会话技术_Cookie_快速入门
- 19_ServletContext_功能_获取文件服务器路径(src,web,w
- 18_ServletContext_功能_域对象(全局)
- 17_ServletContext_功能_获取MIME类型