针对用RequestMappingHandlerAdapter问题替换AnnotationMethodHandlerAdapter问题这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展3.1Di
针对用RequestMappingHandlerAdapter问题替换AnnotationMethodHandlerAdapter问题这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展3.1 DispatcherServlet 初始化-initHandlerMappings/initHandlerAdapters、HandlerMapping和HandlerAdapter配置须知、io.netty.channel.ChannelInboundHandlerAdapter的实例源码、java – RequestMappingHandlerMapping.getHandlerInternal:230 – 没有找到处理程序方法等相关知识,希望可以帮助到你。
本文目录一览:- 用RequestMappingHandlerAdapter问题替换AnnotationMethodHandlerAdapter问题
- 3.1 DispatcherServlet 初始化-initHandlerMappings/initHandlerAdapters
- HandlerMapping和HandlerAdapter配置须知
- io.netty.channel.ChannelInboundHandlerAdapter的实例源码
- java – RequestMappingHandlerMapping.getHandlerInternal:230 – 没有找到处理程序方法
用RequestMappingHandlerAdapter问题替换AnnotationMethodHandlerAdapter问题
我最近升级到3.2spring,并注意到它AnnotationMethodHandlerAdapter
已被赞成弃用RequestMappingHandlerAdapter
。因此,我重新配置为使用新类,并带有所需的自定义MessageConverter
。一切都很好。
但是,当尝试访问带注释的URL时Controller
,出现错误:
[java] javax.servlet.ServletException: No adapter for handler [my.company.TagController@1c2e7808]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler [java] at org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:1128) [java] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:903) [java] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
在调试调度程序(尤其是Dispatcher.getHandlerAdapter()
方法)时,它会找到myHandlerAdapter
,但是AbstractHandlerMethodAdapter.supports()
被调用的则需要一个MethodHandler
:
public final boolean supports(Object handler) { return handler instanceof HandlerMethod && supportsInternal((HandlerMethod) handler);}
并且控制器不是HandlerMethod
。该AnnotatedMethodHandlerAdapter
的支持方法..好,不同的(作品仍然!)
public boolean supports(Object handler) { return getMethodResolver(handler).hasHandlerMethods();}
因此,我显然不能简单地升级到新类……我缺少一些额外的配置,但是文档并没有真正帮助我。有任何想法吗?
谢谢。
答案1
小编典典<mvc:annotation-driven/>
在spring配置文件中使用“ ”,而不是编写自己的WebMvcConfigurationSupport实现
例
<mvc:annotation-driven/><context:component-scan base-package="com.springapp.mvc"/> <bean> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <bean> <property name="messageConverters"> <list> <bean/> <bean/> <bean/> <bean/> <bean/> </list> </property> </bean>
3.1 DispatcherServlet 初始化-initHandlerMappings/initHandlerAdapters
initHandlerMappings
private void initHandlerMappings(ApplicationContext context) {
this.handlerMappings = null;
if (this.detectAllHandlerMappings) {
Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerMappings = new ArrayList(matchingBeans.values());
AnnotationAwareOrderComparator.sort(this.handlerMappings);
}
} else {
try {
HandlerMapping hm = (HandlerMapping)context.getBean("handlerMapping", HandlerMapping.class);
this.handlerMappings = Collections.singletonList(hm);
} catch (NoSuchBeanDefinitionException var3) {
;
}
}
if (this.handlerMappings == null) {
this.handlerMappings = this.getDefaultStrategies(context, HandlerMapping.class);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No HandlerMappings declared for servlet ''" + this.getServletName() + "'': using default strategies from DispatcherServlet.properties");
}
}
}
就是这么简单 从spring容器中获取HandlerMapping的bean 如果没有就创建一个默认的(默认文件就在mvc的jar包里 DispatcherServlet.properties) 完活 然而springboot中HandlerMapping这些是怎么注入的呢 默认的hanlerMapping实体有
- 0 = {PropertySourcedRequestMappingHandlerMapping@14317}
- 1 = {WebMvcEndpointHandlerMapping@14345}
- 2 = {ControllerEndpointHandlerMapping@14372}
- 3 = {RequestMappingHandlerMapping@14396}
- 4 = {BeanNameUrlHandlerMapping@15448}
initHandlerAdapters
与initHandlerMappings类似,从bean工程中获取HandlerAdapter的实现
private void initHandlerAdapters(ApplicationContext context) {
this.handlerAdapters = null;
if (this.detectAllHandlerAdapters) {
Map<String, HandlerAdapter> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerAdapter.class, true, false);
if (!matchingBeans.isEmpty()) {
this.handlerAdapters = new ArrayList(matchingBeans.values());
AnnotationAwareOrderComparator.sort(this.handlerAdapters);
}
} else {
try {
HandlerAdapter ha = (HandlerAdapter)context.getBean("handlerAdapter", HandlerAdapter.class);
this.handlerAdapters = Collections.singletonList(ha);
} catch (NoSuchBeanDefinitionException var3) {
;
}
}
if (this.handlerAdapters == null) {
this.handlerAdapters = this.getDefaultStrategies(context, HandlerAdapter.class);
if (this.logger.isTraceEnabled()) {
this.logger.trace("No HandlerAdapters declared for servlet ''" + this.getServletName() + "'': using default strategies from DispatcherServlet.properties");
}
}
}
默认的hanlerMapping实体有
- 0 = {RequestMappingHandlerAdapter@6397} WebMvcAutoConfiguration
- 1 = {HttpRequestHandlerAdapter@6398} WebMvcConfigurationSupport
- 2 = {SimpleControllerHandlerAdapter@6399} WebMvcConfigurationSupport
HandlerMapping和HandlerAdapter配置须知
---------------------siwuxie095
HandlerMapping 和 HandlerAdapter 配置须知
在 SpringMVC 的核心配置文件 dispatcher-servlet.xml 中,
HandlerMapping 和 HandlerAdapter 的配置一共有 5 种方
式,具体如下:
方式一:什么都不配置
SpringMVC 针对这两者均已有默认配置,详见 spring-webmvc 的 jar
包中第一个包 org.springframework.web.servlet 中最后一个配置文件
DispatcherServlet.properties
方式二:仅限 XML 方式实现的 SpringMVC,配置如下:
BeanNameUrlHandlerMapping 和 SimpleControllerHandlerAdapter
<!-- 配置 HandlerMapping(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- 配置 HandlerAdapter(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
方式三:仅限注解方式实现的 SpringMVC,配置如下:
DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter
<!-- 配置 HandlerMapping(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<!-- 配置 HandlerAdapter(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
「这两个类都已过期(废弃),所以不推荐此法」
方式四:仅限注解方式实现的 SpringMVC,配置如下:
RequestMappingHandlerMapping 和 RequestMappingHandlerAdapter
<!-- 配置 HandlerMapping(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 配置 HandlerAdapter(可选,即 可以省略不配置) -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
方式五:使用 MVC 的注解驱动(此法通用),配置如下:
<!-- 启用注解驱动 -->
<mvc:annotation-driven/>
原理:详见 spring-webmvc 的 jar 包中第二个包 org.springframework.web.
servlet.config 中第一个类 AnnotationDrivenBeanDefinitionParser
【made by siwuxie095】
io.netty.channel.ChannelInboundHandlerAdapter的实例源码
MockClient(EventLoopGroup elg,FrameCodec<ByteBuf> frameCodec) { // Set up so written Frames are encoded into bytes,received bytes are encoded into Frames put // on queue. cb.group(elg) .channel(LocalChannel.class) .handler( new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) throws Exception { ch.pipeline() .addLast(new FrameEncoder(frameCodec)) .addLast(new TestFrameDecoder(frameCodec)) .addLast( new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { responses.offer((Frame) msg); } }); } }); }
@Test public void shouldFireOutboundChannelClosedEvent() throws InterruptedException { inboundChannel.pipeline().addLast(handler); List<Object> events = new ArrayList<>(1); outboundChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void userEventTriggered(ChannelHandlerContext ctx,Object evt) throws Exception { events.add(evt); } }); inboundChannel.close().sync(); assertFalse(events.isEmpty()); assertEquals(1,events.size()); assertTrue(events.get(0) instanceof OutboundChannelClosedEvent); }
@Test public void serverBootStrapWithOptionstest() throws InstantiationException,illegalaccessexception,ClassNotFoundException { LinkedHashMap<String,Object> channelHandlerOptions = new LinkedHashMap<String,Object>(); channelHandlerOptions.put("lineFrame",new LineBasedFrameDecoder(2000)); channelHandlerOptions.put("decoder",new StringDecoder()); channelHandlerOptions.put("encoder",new StringEncoder()); channelHandlerOptions.put("handler",new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { log.info("Message Received and forward to ConsumerProcessor. Msg -> {}",msg); } }); Server server = BootStrap.builder() .port(5252) .options(channelHandlerOptions) .messageConsumer(msg -> log.info(msg)) .build(); assertNotNull(server); }
@Override protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) { return new ChannelInboundHandlerAdapter() { private HttpResponseEncoder encoder = new HttpResponseEncoder(); @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { LOG.trace("Received non-SSL request,returning redirect"); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.MOVED_PERMANENTLY,Unpooled.EMPTY_BUFFER); response.headers().set(Names.LOCATION,redirectAddress); LOG.trace(Constants.LOG_RETURNING_RESPONSE,response); encoder.write(ctx,response,ctx.voidPromise()); ctx.flush(); } }; }
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try{ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class) .remoteAddress(new InetSocketAddress(host,port)) .handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("Hello discardServer.",CharsetUtil.UTF_8)); } }); } }) .option(ChannelOption.so_KEEPALIVE,true); ChannelFuture f = b.connect().sync(); // f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
@Override protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) { return new ChannelInboundHandlerAdapter() { private HttpResponseEncoder encoder = new HttpResponseEncoder(); @Override public void channelRead(ChannelHandlerContext ctx,ctx.voidPromise()); ctx.flush(); } }; }
private void disconnect(ClientSecureChannel secureChannel,CompletableFuture<Unit> disconnected) { RequestHeader requestHeader = new RequestHeader( NodeId.NULL_VALUE,DateTime.Now(),uint(0),null,null); secureChannel.getChannel().pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.debug("channelInactive(),disconnect complete"); disconnected.complete(Unit.VALUE); super.channelInactive(ctx); } }); logger.debug("Sending CloseSecureChannelRequest..."); CloseSecureChannelRequest request = new CloseSecureChannelRequest(requestHeader); secureChannel.getChannel().pipeline().fireUserEventTriggered(request); client.getConfig().getWheelTimer().newTimeout( timeout -> disconnected.completeExceptionally(new UaException(StatusCodes.Bad_Timeout)),5,TimeUnit.SECONDS ); }
public static void main(String[] args) throws Exception { ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new PurchaseDataDecoder()); p.addLast(new PurchaseDataEncoder()); p.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object data) throws Exception { System.out.println("processed Purchase " + data); PurchaseData processed = new PurchaseData(data,true); ctx.writeAndFlush(processed); } }); } }; BootstrapTemplate.newServerBootstrap(HOST,PORT,initializer); }
public static void main(String[] args) throws Exception { ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new StringEncoder()); p.addLast(new StringDecoder()); p.addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { System.out.println(msg); ctx.close(); } }); } }; BootstrapTemplate.newServerBootstrap(HOST,initializer); }
public TestConstantStringServer(int port,final String constant) throws InterruptedException { channel = new ServerBootstrap() .group(bossGroup,workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(TestConstantStringServer.class,LogLevel.DEBUG)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new LoggingHandler(TestConstantStringServer.class,LogLevel.DEBUG)); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { ctx.write(msg); ctx.writeAndFlush(Unpooled.copiedBuffer(constant,CharsetUtil.UTF_8)) .addListener(ChannelFutureListener.CLOSE); } }); } }) .bind(LOCALHOST,port) .sync() .channel(); }
@BeforeClass public static void init() { // Configure a test server group = new LocalEventLoopGroup(); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) { // discard ReferenceCountUtil.release(msg); } }); } }); localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress(); }
@BeforeClass public static void init() { // Configure a test server group = new LocalEventLoopGroup(); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) { // discard ReferenceCountUtil.release(msg); } }); } }); localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress(); }
@Test public void testTooManyAcceptedChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Socket s = new Socket(NetUtil.LOCALHOST,((InetSocketAddress) f1.channel().localAddress()).getPort()); assertthat(s.getInputStream().read(),is(-1)); s.close(); g.shutdownGracefully(); }
@Test public void testTcpInfo() throws Exception { EventLoopGroup group = new EpollEventLoopGroup(1); try { Bootstrap bootstrap = new Bootstrap(); EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group) .channel(EpollSocketChannel.class) .handler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); EpollTcpInfo info = ch.tcpInfo(); assertTcpInfo0(info); ch.close().syncUninterruptibly(); } finally { group.shutdownGracefully(); } }
@Test public void testTcpInfoReuse() throws Exception { EventLoopGroup group = new EpollEventLoopGroup(1); try { Bootstrap bootstrap = new Bootstrap(); EpollSocketChannel ch = (EpollSocketChannel) bootstrap.group(group) .channel(EpollSocketChannel.class) .handler(new ChannelInboundHandlerAdapter()) .bind(new InetSocketAddress(0)).syncUninterruptibly().channel(); EpollTcpInfo info = new EpollTcpInfo(); ch.tcpInfo(info); assertTcpInfo0(info); ch.close().syncUninterruptibly(); } finally { group.shutdownGracefully(); } }
@Override public void buildBungeeServer(Channel channel,Connection connection) { ChannelPipeline pipeline = channel.pipeline(); pipeline.addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(EncapsulatedProtocolUtils.createHandshake(null,false)); super.channelActive(ctx); } }); NetworkDataCache cache = NetworkDataCache.getFrom(connection); pipeline.replace(PipelineUtils.PACKET_DECODER,PipelineUtils.PACKET_DECODER,new FromServerPacketDecoder(connection,cache)); pipeline.replace(PipelineUtils.PACKET_ENCODER,PipelineUtils.PACKET_ENCODER,new ToServerPacketEncoder(connection,cache)); pipeline.get(CustomHandlerBoss.class).setPacketHandlerchangelistener(listener -> { try { return (listener instanceof DownstreamBridge) ? new EntityRewriteDownstreamBridge(ProxyServer.getInstance(),ReflectionUtils.getFieldValue(listener,"con")) : listener; } catch (IllegalArgumentException | illegalaccessexception e) { throw new RuntimeException(e); } }); }
@Override protected void initChannel(SocketChannel ch) throws Exception { channel = ch; responseEventBus = new ResponseEventBus(); responseEventBus.getEventBus().register(this); ch.pipeline().addLast(new ModbusMasterCodec(transectionId -> { Entry entry = requestRecorder.get(transectionId); if (null == entry || entry.trieved == true) { return null; } entry.trieved = true; return entry.request; }),responseEventBus,new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); } }); }
@Test(expected = java.net.BindException.class) public void portAlreadyInUsetest() { final MessageRegistry messageRegistry = new MessageRegistry(); final NioEventLoopGroup bossGroup = new NioEventLoopGroup(); final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); NodeServer serverA = new NodeServer(); NodeServer serverB = new NodeServer(); try { serverA.initialize("127.0.0.1",8042,bossGroup,workerGroup,messageRegistry,new ChannelInboundHandlerAdapter() ); serverB.initialize("127.0.0.1",new ChannelInboundHandlerAdapter() ); } finally { serverA.shutdown(); serverB.shutdown(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
@BeforeClass public static void init() { // Configure a test server group = new LocalEventLoopGroup(); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) { // discard ReferenceCountUtil.release(msg); } }); } }); localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress(); }
@BeforeClass public static void init() { // Configure a test server group = new LocalEventLoopGroup(); ServerBootstrap sb = new ServerBootstrap(); sb.group(group) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override public void initChannel(LocalChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) { // discard ReferenceCountUtil.release(msg); } }); } }); localAddr = (LocalAddress) sb.bind(LocalAddress.ANY).syncUninterruptibly().channel().localAddress(); }
@Test public void testTooManyAcceptedChannels() throws Exception { EventLoopGroup g = new OioEventLoopGroup(1); ServerBootstrap sb = new ServerBootstrap(); sb.channel(OioServerSocketChannel.class); sb.group(g); sb.childHandler(new ChannelInboundHandlerAdapter()); ChannelFuture f1 = sb.bind(0); f1.sync(); Socket s = new Socket(NetUtil.LOCALHOST,is(-1)); s.close(); g.shutdownGracefully(); }
@Test(expected = java.net.BindException.class) public void portAlreadyInUsetest() { final MessageRegistry messageRegistry = new MessageRegistry(); final NioEventLoopGroup bossGroup = new NioEventLoopGroup(); final NioEventLoopGroup workerGroup = new NioEventLoopGroup(); NodeServer serverA = new NodeServer(); NodeServer serverB = new NodeServer(); try { serverA.initialize("127.0.0.1",new ChannelInboundHandlerAdapter() ); } finally { serverA.shutdown(); serverB.shutdown(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
private void disconnect(ClientSecureChannel secureChannel,CompletableFuture<Void> disconnected) { RequestHeader requestHeader = new RequestHeader( NodeId.NULL_VALUE,null); secureChannel.getChannel().pipeline().addFirst(new ChannelInboundHandlerAdapter() { @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { logger.debug("channelInactive(),disconnect complete"); disconnected.complete(null); } }); logger.debug("Sending CloseSecureChannelRequest..."); CloseSecureChannelRequest request = new CloseSecureChannelRequest(requestHeader); secureChannel.getChannel().pipeline().fireUserEventTriggered(request); }
/** * First let's just exercise the PipelineTester a bit. */ @Test public void testPipelineTester() { final ByteBuf buf = Unpooled.copiedBuffer("Hello,world",UTF_8); final PipelineTester pipelineTester = new PipelineTester(new ChannelInboundHandlerAdapter() { @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { super.channelActive(ctx); ctx.channel().writeAndFlush(buf); } }); assertthat(pipelineTester.readClient(),is(buf)); final ByteBuf foo = Unpooled.copiedBuffer("foo",UTF_8); pipelineTester.writeClient(foo.retain()); assertthat(foo,is(pipelineTester.readServer())); final ByteBuf bar = Unpooled.copiedBuffer("bar",UTF_8); pipelineTester.writeServer(bar.retain()); assertthat(bar,is(pipelineTester.readClient())); }
@Scope("prototype") @Bean(name = "channelInitializer") public ChannelInboundHandlerAdapter channelInitializer() throws Exception { // return new ChannelInitializer<SocketChannel>() { // @Override // public void initChannel(SocketChannel ch) throws Exception { // ChannelPipeline pipeline = ch.pipeline(); // // boolean loggingHadler = java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().indexOf("-agentlib:jdwp") > 0 || isDebug; // // if (loggingHadler) { // pipeline.addLast("logger",new LoggingHandler()); // } // // ProtocolUnificationHandler protocolUnificationHandler = new ProtocolUnificationHandler(isUnificationMode,opcodeMap(),sslContext(),maxFrameLength,charset); // protocolUnificationHandler.setRedisService(redisService); // pipeline.addLast(protocolUnificationHandler); // } // }; ChannelServerInitializer channelServerInitializer = new ChannelServerInitializer(); channelServerInitializer.setopcodeMap(opcodeMap()); channelServerInitializer.setRedisService(redisService); channelServerInitializer.setCharset(charset); channelServerInitializer.setSslCtx(sslContext()); channelServerInitializer.setMaxFrameLength(8192); return channelServerInitializer; }
public NettyWebSocketServer(String host,int port,String uri,ChannelInboundHandlerAdapter handler) { super(new InetSocketAddress(host,port),handler); if(uri==null || uri.isEmpty()) { this.uri="/"; }else { this.uri=uri; } }
public NettyWebSocketServer(NettyServerConfig config,String host,ChannelInboundHandlerAdapter handler) { super(config,new InetSocketAddress(host,handler); if(uri==null || uri.isEmpty()) { this.uri="/"; }else { this.uri=uri; } }
public void server(int port) throws Exception { final ByteBuf buf = Unpooled.unreleasableBuffer( Unpooled.copiedBuffer("Hi!\r\n",Charset.forName("UTF-8"))); EventLoopGroup group = new OioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(OioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(buf.duplicate()).addListener(ChannelFutureListener.CLOSE); } }); } }); ChannelFuture f = b.bind().sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully().sync(); } }
/** * Initializes this socket and binds its internal udp socket to a free port. * If the socket is already initialized any invocation of this method will * result in an IllegalStateException. * * @throws SocketException Thrown in case the socket Could not be initialized */ public void initialize() throws SocketException { if ( this.isInitialized() ) { throw new IllegalStateException( "Cannot re-initialized ClientSocket" ); } this.udpSocket = new Bootstrap(); this.udpSocket.group( Epoll.isAvailable() ? new EpollEventLoopGroup() : new NioEventLoopGroup() ); this.udpSocket.channel( Epoll.isAvailable() ? EpollDatagramChannel.class : NioDatagramChannel.class ); this.udpSocket.handler( new ChannelInboundHandlerAdapter() { @Override public void channelRead( ChannelHandlerContext ctx,Object msg ) throws Exception { io.netty.channel.socket.DatagramPacket packet = (io.netty.channel.socket.DatagramPacket) msg; PacketBuffer content = new PacketBuffer( packet.content() ); InetSocketAddress sender = packet.sender(); if ( !receiveDatagram( sender,content ) ) { // Push datagram to update queue: handleDatagram( sender,content,System.currentTimeMillis() ); } } } ); try { this.channel = this.udpSocket.bind( ThreadLocalRandom.current().nextInt( 45000,65000 ) ).sync().channel(); } catch ( InterruptedException e ) { SocketException exception = new SocketException( "Could not bind to socket" ); exception.initCause( e ); throw exception; } this.afterInitialize(); }
@Test public void afterNettyContextinit() { AtomicInteger readCount = new AtomicInteger(); ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { readCount.incrementAndGet(); super.channelRead(ctx,msg); } }; String handlerName = "test"; NettyContext nettyContext = HttpServer.create(opt -> opt.afterNettyContextinit(c -> c.addHandlerFirst(handlerName,handler))) .start((req,resp) -> resp.sendNotFound()) .getContext(); HttpClientResponse response1 = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address())) .get("/",req -> req.failOnClientError(false).send()) .block(); assertthat(response1.status().code()).isEqualTo(404); response1.dispose(); //the "main" context doesn't get enriched with handlers from options... assertthat(nettyContext.channel().pipeline().names()).doesNotContain(handlerName); //...but the child channels that are created for requests are assertthat(readCount.get()).isEqualTo(1); HttpClientResponse response2 = HttpClient.create(opt -> opt.connectAddress(() -> nettyContext.address())) .get("/",req -> req.failOnClientError(false).send()) .block(); assertthat(response2.status().code()).isEqualTo(404); //reactor handler was applied and produced a response response2.dispose(); assertthat(readCount.get()).isEqualTo(1); //BUT channelHandler wasn't applied a second time since not Shareable nettyContext.dispose(); }
private void createServerChannelHandler() { endInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { try { synchronized (networkManagers) { if (!closed) injectChannelInternal(channel); } } catch (Exception e) { plugin.getLogger().log(Level.SEVERE,"Cannot inject incomming channel " + channel,e); } } }; beginInitProtocol = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline().addLast(endInitProtocol); } }; serverChannelHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { Channel channel = (Channel) msg; channel.pipeline().addFirst(beginInitProtocol); ctx.fireChannelRead(msg); } }; }
@Override public void prepare() throws Exception { eventHandleAdaptor = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) { // System.out.println("_________________"+msg); // ctx.write(msg); addCount(1); } }; Bootstrap b = new Bootstrap(); b.group(group); b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,false); b.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("frameDecoder",new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,4,4)); pipeline.addLast("frameEncoder",new LengthFieldPrepender(4)); pipeline.addLast("decoder",new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast("encoder",new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast("handler",eventHandleAdaptor); } }); f = b.connect("localhost",5656).sync(); }
public void start(TcpChannelHandler handler) { channelHandler = new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { handler.process(ctx,msg); } }; start(); }
public static void main(String[] args) { // new SimpleTcpserver(8007).start( (ChannelHandlerContext ctx,Object msg) -> { // System.out.println(msg); // ctx.writeAndFlush("ok"); // }); new SimpleTcpserver(8007).start(new ChannelInboundHandlerAdapter(){ @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { ctx.writeAndFlush("ok"); } }); }
@Override public final ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { final ChannelInboundHandlerAdapter exceptionHandler = new ChannelInboundHandlerAdapter() { @Override public void exceptionCaught( final ChannelHandlerContext ctx,final Throwable cause ) throws Exception { if (cause instanceof HttpException) { final HttpException e = (HttpException) cause; sendResponse(ctx,e.getStatus()); return; } if (cause instanceof DecoderException) { exceptionCaught(ctx,cause.getCause()); return; } log.error("error in pipeline: ",cause); sendResponse(ctx,HttpResponseStatus.INTERNAL_SERVER_ERROR); } }; ch .pipeline() .addLast(new HttpRequestDecoder(),new HttpContentDecompressor(),new HttpObjectAggregator(Integer.MAX_VALUE),decoder,exceptionHandler,handler); ch.pipeline().addLast(new HttpResponseEncoder()); } }; }
static ChannelHandler forbiddenHttpRequestResponder() { return new ChannelInboundHandlerAdapter() { @Override public void channelRead(ChannelHandlerContext ctx,Object msg) throws Exception { if (msg instanceof FullHttpRequest) { ((FullHttpRequest) msg).release(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,HttpResponseStatus.FORBIDDEN); ctx.channel().writeAndFlush(response); } else { ctx.fireChannelRead(msg); } } }; }
java – RequestMappingHandlerMapping.getHandlerInternal:230 – 没有找到处理程序方法
试图制作一些弹簧示例程序 – 不断得到错误 – 发生我的控制器无法处理/你好请求.这是来自log4j的调试信息.
13:50:58,502 {TRACE} dispatcherServlet.initContextHolders:1018 - Bound request context to thread: org.apache.catalina.connector.RequestFacade@636f2067
13:50:58,503 {DEBUG} dispatcherServlet.doService:823 - dispatcherServlet with name 'springtest' processing GET request for [/springtest_2/hello]
13:50:58,504 {TRACE} dispatcherServlet.getHandler:1088 - Testing handler map
[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@7bab2c3] in dispatcherServlet with name 'springtest'
13:50:58,504 {DEBUG} RequestMappingHandlerMapping.getHandlerInternal:220 - Looking
up handler method for path /hello
13:50:58,504 {DEBUG} RequestMappingHandlerMapping.getHandlerInternal:230 - Did not find handler method for [/hello]
13:50:58,504 {TRACE} dispatcherServlet.getHandler:1088 - Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping@722e242b] in dispatcherServlet with name 'springtest'
13:50:58,505 {TRACE} BeanNameUrlHandlerMapping.getHandlerInternal:127 - No handler mapping found for [/hello]
13:50:58,505 {WARN} PageNotFound.noHandlerFound:1108 - No mapping found for HTTP request with URI [/springtest_2/hello] in dispatcherServlet with name 'springtest'
13:50:58,505 {TRACE} dispatcherServlet.resetContextHolders:1028 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@636f2067
13:50:58,505 {DEBUG} dispatcherServlet.processRequest:966 - Successfully completed request
13:50:58,506 {TRACE} XmlWebApplicationContext.publishEvent:332 - Publishing event in WebApplicationContext for namespace 'springtest-servlet': ServletRequestHandledEvent: url=[/springtest_2/hello]; client=[0:0:0:0:0:0:0:1]; method=[GET]; servlet=[springtest]; session=[null]; user=[null]; time=[9ms]; status=[OK]
我项目中的web.xml.
display-name>Spring3-Hibernate DEMOdisplay-name>
figListeneraram>
figLocationaram-name>
aram-value>/WEB-INF/log4j.properties
aram-value>
aram>
总结
以上是小编为你收集整理的java – RequestMappingHandlerMapping.getHandlerInternal:230 – 没有找到处理程序方法全部内容。
如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。
关于用RequestMappingHandlerAdapter问题替换AnnotationMethodHandlerAdapter问题的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于3.1 DispatcherServlet 初始化-initHandlerMappings/initHandlerAdapters、HandlerMapping和HandlerAdapter配置须知、io.netty.channel.ChannelInboundHandlerAdapter的实例源码、java – RequestMappingHandlerMapping.getHandlerInternal:230 – 没有找到处理程序方法的相关知识,请在本站寻找。
本文标签: