servlet的两种编写方式

进行编写servlet前咱们要知道servlet是什么,servlet是sun公司制定的一种用来扩展web服务器功能的组件,主要是用来接收浏览器发送的请求,获取参数,而后返回响应数据给到浏览器。 1、 servlet的开发步骤:java

建立一个web项目
   建立一个类实现servlet接口或实现HttpServlet类
   重写doGet()和doPost()方法
   使用web.xml或使用注解进行配置

2、使用配置文件编写HelloServlet.java
[Java] 纯文本查看 复制代码
?web

public class HelloServlet extends HttpServlet {浏览器

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Web资源: 到达了Servlet中,调用了post方法");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Web资源: 到达了Servlet中,调用了get方法");
}

在web.xml文件中进行配置
[mw_shl_code=xml,true]<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"服务器

xmlns="http://java.sun.com/xml/ns/javaee"
     xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     [url]http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd[/url]"
     version="3.0">

<servlet>app

<servlet-name>hello</servlet-name>
<servlet-class>com.itheima.servlet.HelloServlet</servlet-class>

</servlet>
<servlet-mapping>ide

<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>

</servlet-mapping>
</web-app>post

}[/mw_shl_code]
3、使用注解的方式编写HelloServlet.java
[Java] 纯文本查看 复制代码
?url

@WebServlet(name = "HelloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {code

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("Web资源: 到达了Servlet中,调用了post方法");
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Web资源: 到达了Servlet中,调用了get方法");
}

}xml

相关文章
相关标签/搜索