Servlet的两种创建方法


Servlet的两种创建方法


我们所说servlet是一种运行在服务器端的扩展程序,继承自javax.servlet.http.HttpServlet。HttpServlet继承GenericServlet,GenericServlet实现了

Servlet, ServletConfig, Serializable这三个接口。它的作用是处理客户端发送的请求。

访问方法:http://主机名:端口号/servlet名称  这里说servlet名称是不准确的,应该说是servlet名称的映射名称或者是urlPatterns

例如:http://localhost:8080/hehe 即可访问该servlet


1.常规方法

(1)创建一个类,继承javax.servlet.http.HttpServlet,重写doPost,doGet等方法


package com.test.hehe;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class Haha extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("hahaha");
    }
}



(2)在项目的/web/WEB-INF/目录下,打开web.xml,在<web-app> 这里是内部 </web-app>的内部加入如下几行:

    <servlet>
        <display-name>Haha</display-name>
        <servlet-name>Haha</servlet-name>
        <servlet-class>com.test.hehe.Haha</servlet-class>
    </servlet>


    <servlet-mapping>
        <servlet-name>Haha</servlet-name>
        <url-pattern>/hahaha</url-pattern>
    </servlet-mapping>

在浏览器中输入http://localhost:8080/hahaha就可以看见结果了(前提是,你已经启动了服务器,并且该项目已经在服务器中跑了,端口号是8080,主机名是localhost)。


2.注解

这个创建sevrlet很简单,但是在较低的版本中不支持,废话不多说,看代码:


package com.test.hehe;

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;

@WebServlet(name="hehe",urlPatterns="/hehe")
public class SayHehe extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().println("hehe");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {    
        resp.getWriter().println("hehe");
}}



一定要 importjavax.servlet.annotation.WebServlet;

并在顶部写:@WebServlet(name="hehe",urlPatterns="/hehe")

http://localhost:8080/hehe 就可以看到效果了


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值