springboot整合servlet的使用经历

最近这段时间一直想看下原来自己是如何使用servlet方式进行项目开发的,现在看来是不是servlet离我们很久远了。

是的,现在企业开发都是框架先行的原则,不过自己还是想给自己在自己公众号里面写上一篇如何使用原生servlet方式进行一个示例程序的编写。

好了,我们看下如何使用springboot方式进行使用原生的servlet使用,按以往的文章风格,我们开始下面的示例程序编写了。

package com.wpw.springbootservlet;

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 = "myservlet",urlPatterns ="/myservlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("hello servlet");
    }
}

首先,我们通过@WebServlet注解标注这个类是一个servlet,然后里面标注一下url拦截的路径,在doGet方法里面进行一句话的输出。

我们接下来看下,我们在启动类需要做些什么。

package com.wpw.springbootservlet;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import javax.servlet.Servlet;

@SpringBootApplication
@ServletComponentScan(basePackages = "com.wpw")
public class SpringbootServletApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootServletApplication.class, args);
    }
}

通过上面的@ServletComponentScan注解进行扫描上面我们使用注解方式注入的自定义servlet,实现容器的装载。

接下来,我们只需要通过下面的地址进行访问即可,可以在页面输出我们返回的信息。

http://localhost:8080/myservlet

好了,这篇文章就到这里结束了,其实文章主要还是很容易理解的,之所以会写这篇文章,主要还是自己内心的一点想法吧。

更多教程请访问码农之家

posted @ 2022-07-23 09:02  small_123  阅读(168)  评论(0编辑  收藏  举报