第一个Servlet项目
1.new -> project,选择以下,然后next
然后起项目名,再next:
2.增加maven框架,配置以下依赖:
<!-- servlet依赖的jar包start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- servlet依赖的jar包start --> <!-- jsp依赖jar包start --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <!-- jsp依赖jar包end --> <!--jstl标签依赖的jar包start --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--jstl标签依赖的jar包end -->
3.在java文件夹下新建Demo类:
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet(name = "Demo") public class Demo extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //设置网页相应类型 resp.setContentType("text/html"); //实现具体操作 PrintWriter out = resp.getWriter(); out.print("this is a new servlet page"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
4.在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_4_0.xsd" version="4.0"> <servlet> <servlet-name>Demo</servlet-name> <servlet-class>com.nenu.Demo</servlet-class> </servlet> <servlet-mapping> <servlet-name>Demo</servlet-name> <url-pattern>/Demo</url-pattern> </servlet-mapping> </web-app>5.启动,在网址栏输入网址:http://localhost:8080/Demo
成功
- 范例中继承了HttpServlet,并重新定义了doGet方法,当浏览器get方法发送请求时,会调用此方法。
- 在doGet方法可以看到HttpServletRequest与HttpServletResponse两个参数,容器中接收到客户端的HTTP请求后,会收集HTTP请求中的信息,并分别创建代表请求与响应的Java对象,而后在调用doGet时将这两个对象当做参数传入。可以从HttpServletRequest对象中取得有关HTTP请求参数名称,并取得用户发送的请求参数值。
@WebServlet("/hello.view")
这表示,如果请求的URL是/hello.view,就会由Demo来处理请求。