Java Servlet 教程-02-hello world
2018年9月28日大约 2 分钟
快速开始
我们来写一个最简单的 hello world 项目,来对 servlet 有个最直观的认识。
项目结构
.
├── java
│ └── com
│ └── github
│ └── houbb
│ └── servlet
│ └── learn
│ └── base
│ └── hello
│ ├── Hello.java
└── webapp
├── WEB-INF
│ └── web.xml
└── index.html
pom.xml 设置
使用 maven 做项目 jar 管理。
- servlet-api
javax.servlet
servlet-api
2.5
provided
- 指定打包方式为 war 包
war
- tomcat7 插件
你可以将项目打包为 *.war 然后放到 tomcat 下启动,此处为了方便使用了 tomcat7-maven-plugin。
整体如下:
- pom.xml
servlet
com.ryo
1.0-SNAPSHOT
4.0.0
war
servlet-base
UTF-8
2.2
javax.servlet
servlet-api
2.5
provided
org.apache.tomcat
tomcat-servlet-api
9.0.0.M8
provided
servlet
org.apache.tomcat.maven
tomcat7-maven-plugin
${plugin.tomcat.version}
8081
/
${project.build.sourceEncoding}
servlet
org.apache.tomcat.maven
tomcat7-maven-plugin
${plugin.tomcat.version}
8081
/
${project.build.sourceEncoding}
web.xml
hello
com.github.houbb.servlet.learn.base.hello.Hello
hello
/hello
/index.html
指定了 url 与 Servlet 类之间的映射。
当我们访问 /hello
的时候,会调用对应的 Hello
Servlet 类进行处理。
代码
- Hello.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 入门测试
*/
public class Hello extends HttpServlet {
private static final long serialVersionUID = -6775862788735743674L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
// 实际的逻辑是在这里
PrintWriter out = resp.getWriter();
out.println("hello");
}
}
- index.html
Hello Servlet!
启动
直接启动 tomcat7:run 运行当前 war。
打开浏览器 http://localhost:8081/,默认显示的是:
Hello Servlet!
访问 url
打开浏览器 http://localhost:8081/hello,显示的是:
hello
也就是我们在 Hello
类中返回的 html 内容。
基于注解实现
如果你使用过 springmvc 一定会发现,web.xml
中的配置太麻烦了。
当然,Servlet 中我们也可以使用注解来简化这一配置。
- HelloAnnotation.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 入门注解测试
*/
@WebServlet("/hello/annotation")
public class HelloAnnotation extends HttpServlet {
private static final long serialVersionUID = 491287664925808862L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
// 实际的逻辑是在这里
PrintWriter out = resp.getWriter();
out.println("hello annotation");
}
}
访问
和上面一样,打开浏览器 http://localhost:8081/hello/annotation,显示的是:
hello annotation
源码地址
源码参见servlet 入门案例
贡献者
binbin.hou