Spring Boot 自定义 Servlet


       在 Spring Boot 之前自定义 Servlet 的配置,都是在 webapp/WEB-INF/web.xml 文件下来配置;或者说使用 @WebServlet 注解的方式来配置。在使用 Spring Boot 开发 Web 项目时,并没有 web.xml 配置文件的存在,所以 Spring Boot 为我们提供了两种方式来将我们自定义的 Servlet 注册到 Spring 容器中。

  1. 使用 @WebServlet 注解方式
  2. 通过 ServletRegistrationBean类的方式

1.使用 @WebServlet 注解方式

1.1 自定义 MyServlet 类

       自定义一个 MyServlet类,添加注解@WebServlet,通过 value/urlPattern属性来指定映射的 URL。

/**
 * TODO 自定义Servlet
 *
 * @author liuzebiao
 * @Date 2020-4-2 10:50
 */
//指定vlaue属性 和 urlPattern属性均可以
@WebServlet(value = "/myServlet",description = "自定义MyServlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req,resp);
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Enumeration enu=req.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            System.out.println(paraName+": "+req.getParameter(paraName));
        }
        //输出 Hello Servlet 到页面
        resp.getWriter().write("Hello Servlet");
        //重定向到 baidu
//        resp.sendRedirect("http://www.baidu.com");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }
}
1.2 添加 @ServletComponentScan 注解

       在Spring Boot 启动类上,添加一个 @ServletComponentScan 注解

@ServletComponentScan
@SpringBootApplication
public class BootApplication {

    public static void main(String[] args) {
        // Spring应用启动起来         
        SpringApplication.run(BootApplication.class,args);

    }
}

2.编写ServletRegistrationBean类的方式

2.1 同样先自定义一个 MyServlet (代码同1.1中 MyServlet,唯一区别是不需要加@WebServlet 注解)
/**
 * TODO 自定义Servlet
 *
 * @author liuzebiao
 * @Date 2020-4-2 10:50
 */
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req,resp);
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Enumeration enu=req.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            System.out.println(paraName+": "+req.getParameter(paraName));
        }
        //输出 Hello Servlet 到页面
        resp.getWriter().write("Hello Servlet");
        //重定向到 baidu
//        resp.sendRedirect("http://www.baidu.com");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
    }
}
2.2 添加 Spring Boot 配置类,将自定义的 MyServlet 注册到容器中
@Configuration
public class MyServerConfig {

    //注册 Servlet 到容器中
    @Bean
    public ServletRegistrationBean myServlet(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
        return servletRegistrationBean;
    }
}

       当我们访问 /myServlet 请求时,便会执行到我们自定义的 MyServlet 中。Servlet URL映射地址,接收可变参数,支持同时配置多个 URL 地址。如下所示:

@Bean
public ServletRegistrationBean myServlet(){
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet","/demo","/test");
    return servletRegistrationBean;
}
@WebServlet(value = {"/myServlet","/demo","/test"},description = "自定义MyServlet")
public class MyServlet extends HttpServlet {

}

博主写作不易,来个关注呗

求关注、求点赞,加个关注不迷路 ヾ(◍°∇°◍)ノ゙

博主不能保证写的所有知识点都正确,但是能保证纯手敲,错误也请指出,望轻喷 Thanks♪(・ω・)ノ

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以回答你关于 Spring Boot 自定义 Session 的问题。 在 Spring Boot 中,Session 的默认实现是基于 Servlet 的 HttpSession 接口。如果你想要自定义 Session 实现,可以通过实现 Spring Session 的 Session 接口,并在配置文件中指定该实现来实现。 下面是一个使用 Redis 存储的自定义 Session 实现的示例代码: 首先,创建一个 RedisSession 类,实现 Session 接口,并实现相应的方法,如下所示: ```java public class RedisSession implements Session { private final String id; private Map<String, Object> attributes = new HashMap<>(); private boolean isNew; public RedisSession(String id) { this.id = id; this.isNew = true; } @Override public String getId() { return this.id; } @Override public <T> T getAttribute(String name) { return (T) this.attributes.get(name); } @Override public void setAttribute(String name, Object value) { this.attributes.put(name, value); this.isNew = false; } @Override public void removeAttribute(String name) { this.attributes.remove(name); } @Override public Instant getCreationTime() { throw new UnsupportedOperationException(); } @Override public void setLastAccessedTime(Instant lastAccessedTime) { throw new UnsupportedOperationException(); } @Override public Instant getLastAccessedTime() { throw new UnsupportedOperationException(); } @Override public void setMaxInactiveInterval(Duration interval) { throw new UnsupportedOperationException(); } @Override public Duration getMaxInactiveInterval() { throw new UnsupportedOperationException(); } @Override public boolean isExpired() { throw new UnsupportedOperationException(); } public boolean isNew() { return this.isNew; } } ``` 然后,创建一个 RedisSessionRepository 类,实现 SessionRepository 接口,并实现相应的方法,如下所示: ```java public class RedisSessionRepository implements SessionRepository<RedisSession> { private final RedisTemplate<String, RedisSession> redisTemplate; public RedisSessionRepository(RedisTemplate<String, RedisSession> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public RedisSession createSession() { String id = UUID.randomUUID().toString(); RedisSession session = new RedisSession(id); this.redisTemplate.opsForValue().set(id, session); return session; } @Override public void save(RedisSession session) { this.redisTemplate.opsForValue().set(session.getId(), session); } @Override public RedisSession findById(String id) { return this.redisTemplate.opsForValue().get(id); } @Override public void deleteById(String id) { this.redisTemplate.delete(id); } } ``` 最后,在 Spring Boot 的配置文件中指定使用 RedisSessionRepository 实现 SessionRepository,如下所示: ```properties spring.session.store-type=redis spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=10000 spring.session.redis.flush-mode=on_save spring.session.redis.namespace=spring:session spring.session.repository-type=redis ``` 以上就是关于 Spring Boot 自定义 Session 的步骤,希望能帮到你。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扛麻袋的少年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值