Guice 学习(九) WEB AND SERVLET

2024-05-23 07:08
文章标签 学习 servlet web guice

本文主要是介绍Guice 学习(九) WEB AND SERVLET,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、新建web工程,导入JAR包

这里写图片描述

2、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><display-name>GuiceWeb</display-name><listener><listener-class>com.guice.web.listener.MyGuiceServletContextListener</listener-class></listener><filter><filter-name>guiceFilter</filter-name><filter-class>com.google.inject.servlet.GuiceFilter</filter-class></filter><filter-mapping><filter-name>guiceFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
3、自定义监听器
package com.guice.web.listener;import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.guice.web.servlet.HelloWorldServlet;public class MyGuiceServletContextListener extends GuiceServletContextListener {@Overrideprotected Injector getInjector() {return Guice.createInjector(new ServletModule() {protected void configureServlets() {serve("/helloworld").with(HelloWorldServlet.class);}});}
}
4、新建servlet
package com.guice.web.servlet;import java.io.IOException;
import java.util.Date;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.guice.web.service.HelloWorld;/*** TODO :每个servlet必须是单例的* * @author E468380*/
@Singleton
public class HelloWorldServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().append("Hello , Guice !" + new Date());}}
5、运行tomcat服务器

一个简单的Helloworld

6、注入服务

新建service接口

package com.guice.web.service;import java.io.IOException;import com.google.inject.ImplementedBy;@ImplementedBy(HelloWorldImpl.class)
public interface HelloWorld {void execute() throws IOException;
}

新建实现类

package com.guice.web.service;import java.io.IOException;
import java.util.Date;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.google.inject.Inject;public class HelloWorldImpl implements HelloWorld {private HttpServletRequest request;private HttpServletResponse response;@Injectpublic HelloWorldImpl(HttpServletRequest request, HttpServletResponse response) {super();this.request = request;this.response = response;}public void execute() throws IOException {String name = request.getParameter("user");if (name == null || name.length() < 1)name = "Guest";response.getWriter().append(String.format("Hello, %s. %s -> sessionId=%s,hashCode=%d ", name, new Date(), request.getSession().getId(), hashCode()));}
}

修改servlet

package com.guice.web.servlet;import java.io.IOException;
import java.util.Date;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.guice.web.service.HelloWorld;/*** TODO :每个servlet必须是单例的* * @author E468380*/
@Singleton
public class HelloWorldServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Injectprivate Injector inj;// 自动注入Injector对象,然后通过Inject对象获取我们的服务,@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.getWriter().append("Hello , Guice !" + new Date());inj.getInstance(HelloWorld.class).execute();inj.getInstance(HelloWorld.class).execute();}}

输出

Hello , Guice !Thu Jul 02 10:38:27 CST 2015
Hello, Guest. Thu Jul 02 10:38:27 CST 2015 -> sessionId=C038A844F4C2C8259E06479AA59F0CC7,hashCode=1240584990 
Hello, Guest. Thu Jul 02 10:38:27 CST 2015 -> sessionId=C038A844F4C2C8259E06479AA59F0CC7,hashCode=593198207 

由上可知:sessionId是一样的,但是hashcode值不同,与原例不符,那是因为在
原文示例中(参考这里)将HelloWorldImpl类上标明注解:@RequestScoped ,但是程序运行会出如下错误:

HTTP Status 500 - Filter execution threw an exceptiontype Exception reportmessage Filter execution threw an exceptiondescription The server encountered an internal error that prevented it from fulfilling this request.exceptionjavax.servlet.ServletException: Filter execution threw an exceptionroot causejava.lang.NoSuchMethodError: com.google.inject.Scopes.isCircularProxy(Ljava/lang/Object;)Zcom.google.inject.servlet.ServletScopes$2$1.get(ServletScopes.java:121)com.google.inject.internal.InternalFactoryToProviderAdapter.get(InternalFactoryToProviderAdapter.java:40)com.google.inject.internal.InjectorImpl$3.get(InjectorImpl.java:737)com.google.inject.internal.InjectorImpl$4$1.call(InjectorImpl.java:978)com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1024)com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:974)com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013)com.guice.web.servlet.HelloWorldServlet.doGet(HelloWorldServlet.java:34)javax.servlet.http.HttpServlet.service(HttpServlet.java:620)javax.servlet.http.HttpServlet.service(HttpServlet.java:727)com.google.inject.servlet.ServletDefinition.doServiceImpl(ServletDefinition.java:278)com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:268)com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:180)com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:93)com.google.inject.servlet.ManagedFilterPipeline.dispatch(ManagedFilterPipeline.java:120)com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:132)com.google.inject.servlet.GuiceFilter$1.call(GuiceFilter.java:129)com.google.inject.servlet.GuiceFilter$Context.call(GuiceFilter.java:206)com.google.inject.servlet.GuiceFilter.doFilter(GuiceFilter.java:129)

我也不清楚这是为什么,如果有人知道,烦请告知,谢谢!

这篇关于Guice 学习(九) WEB AND SERVLET的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/996166

相关文章

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

Python Web框架Flask、Streamlit、FastAPI示例详解

《PythonWeb框架Flask、Streamlit、FastAPI示例详解》本文对比分析了Flask、Streamlit和FastAPI三大PythonWeb框架:Flask轻量灵活适合传统应用... 目录概述Flask详解Flask简介安装和基础配置核心概念路由和视图模板系统数据库集成实际示例Stre

如何使用Maven创建web目录结构

《如何使用Maven创建web目录结构》:本文主要介绍如何使用Maven创建web目录结构的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录创建web工程第一步第二步第三步第四步第五步第六步第七步总结创建web工程第一步js通过Maven骨架创pytho

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

如何使用Haporxy搭建Web群集

《如何使用Haporxy搭建Web群集》Haproxy是目前比较流行的一种群集调度工具,同类群集调度工具有很多如LVS和Nginx,本案例介绍使用Haproxy及Nginx搭建一套Web群集,感兴趣的... 目录一、案例分析1.案例概述2.案例前置知识点2.1 HTTP请求2.2 负载均衡常用调度算法 2.

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio