在进行编写servlet前我们要知道servlet是什么,servlet是sun公司制定的一种用来扩展web服务器功能的组件,主要是用来接收浏览器发送的请求,获取参数,然后返回响应数据给到浏览器。 一、 servlet的开发步骤:
- 创建一个web项目
- 创建一个类实现servlet接口或实现HttpServlet类
- 重写doGet()和doPost()方法
- 使用web.xml或使用注解进行配置
二、使用配置文件编写HelloServlet.java
[Java] 纯文本查看 复制代码 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>
<servlet-name>hello</servlet-name>
<servlet-class>com.itheima.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
}[/mw_shl_code]
三、使用注解的方式编写HelloServlet.java
[Java] 纯文本查看 复制代码 @WebServlet(name = "HelloServlet", urlPatterns = "/hello")
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方法");
}
}
|