# ws-web **Repository Path**: lengmianshi2/ws-web ## Basic Information - **Project Name**: ws-web - **Description**: 基于Netty的web项目,实现了SpringMVC中如@RequestParam、@Value、@Controller等注解的功能,使得我们在Netty框架中编写接口大为便利。 - **Primary Language**: Java - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 2 - **Created**: 2018-04-02 - **Last Updated**: 2021-10-13 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### 使用说明 #### 配置服务器并启动,代码`ClassPathApplicationContext.getInstance().start("web.properties")`十分关键 ``` public final class TestWebSocketServer { private static Logger logger = Logger.getLogger(TestWebSocketServer.class); private static final int PORT = 9090; public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.ERROR)).childHandler(new ChannelInitializer() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addFirst(new IdleStateHandler(0L, 0L, 64L, TimeUnit.SECONDS)); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerCompressionHandler()); pipeline.addLast(new ChunkedWriteHandler()); pipeline.addLast(new DispatcherServlet()); } }); /** * 指定服务器启动需要使用的属性文件,属性文件放在classpath目录下,多个文件以英文逗号隔开 * 属性文件可以配置controller扫描包的包路径以及,统一的异常处理器 */ ClassPathApplicationContext.getInstance().start("web.properties"); Channel ch = b.bind(PORT).sync().channel(); ch.closeFuture().sync(); } catch (Exception e) { logger.error("WebSocketServer启动失败...", e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` web.properties文件中配置: ``` #包含所有controller的包,必须配置 web.package=com.leng.test.controller #统一的异常处理器,可配可不配,不配的话需要在每个controller中处理异常 web.exceptionResolver=com.leng.test.resolver.MyHandlerExcetionResolver ``` #### 1.测试get请求方法 ``` @RequestMapping(value="hello",method=RequestMethod.GET) @ResponseBody public Object test(){ Map map = new HashMap(); map.put("code", "200"); map.put("msg", "get hello world"); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/175256_c3331912_1213036.png "微信截图_20180406174501.png") #### 2.测试post请求方法 ``` @RequestMapping(value="hello",method=RequestMethod.POST) @ResponseBody public Object test2(){ Map map = new HashMap(); map.put("code", "200"); map.put("msg", "post hello world"); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/175146_053e1510_1213036.png "微信截图_20180406174501.png") #### 3.测试HttpServletRequeset ``` @RequestMapping(value="request",method=RequestMethod.POST) @ResponseBody public Object test3(HttpServletRequest request){ String name = request.getParameter("name"); String age = request.getParameter("age"); Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/180342_ef168504_1213036.png "微信截图_20180406174501.png") 接口限定请求方法为post,如果用get来请求,则出现“The request method 'GET' does not sopport this mapping[/test/request].”错误提示: ![输入图片说明](https://gitee.com/uploads/images/2018/0406/180709_c4bf0ff1_1213036.png "微信截图_20180406174501.png") #### 4.测试@RequestParam ``` @RequestMapping(value="request",method=RequestMethod.POST) @ResponseBody public Object test3(@RequestParam("name")String name,@RequestParam("age")int age){ Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/183305_478a8998_1213036.png "微信截图_20180406174501.png") #### 5.测试@RequestParam默认值 ``` @RequestMapping(value = "param/default", method = RequestMethod.GET) @ResponseBody public Object test4(@RequestParam(value = "name", defaultValue = "lisi") String name, @RequestParam(value = "age", defaultValue = "20") Integer age) { Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/183211_e4c3cc84_1213036.png "微信截图_20180406174501.png") #### 6.测试直接入参 ``` @RequestMapping(value = "param", method = RequestMethod.POST) @ResponseBody public Object test5(String name, int age) { Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/183628_888bbdae_1213036.png "微信截图_20180406174501.png") #### 7.测试@CookieValue ``` @RequestMapping(value = "cookie", method = RequestMethod.POST) @ResponseBody public Object test6(@CookieValue(value = "name") String name, @CookieValue(value = "age") int age) { Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/184951_92f3b117_1213036.png "微信截图_20180406174501.png") #### 8.测试@RequestHeader ``` @RequestMapping(value = "header", method = RequestMethod.POST) @ResponseBody public Object test7(@RequestHeader(value = "name") String name, @RequestHeader(value = "age") int age) { Map map = new HashMap(); map.put("name", name); map.put("age", age); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/185204_e2aea999_1213036.png "微信截图_20180406174501.png") #### 9.测试@Value ``` @RequestMapping(value = "value", method = RequestMethod.POST) @ResponseBody public Object test8(@Value(value = "web.package") String pack) { Map map = new HashMap(); map.put("package", pack); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/185356_0f3c0bb5_1213036.png "微信截图_20180406174501.png") #### 10.测试@Shakehands ``` @RequestMapping(value = "ws", method = RequestMethod.GET) @Shakehands public void test9(HttpServletRequest req, final ChannelHandlerContext ctx) { // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req.getNativeRequest()); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { ChannelFuture future = handshaker.handshake(ctx.channel(), req.getNativeRequest()); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { ctx.fireExceptionCaught(future.cause()); } else { System.out.println("握手成功"); } } }); } } private static String getWebSocketLocation(HttpServletRequest req) { String location = req.getHeader(HOST.toString()) + req.getRequestURI(); return "ws://" + location; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/191050_638386a2_1213036.png "微信截图_20180406174501.png") #### 11.测试统一的异常处理器 异常处理器代码: ``` public class MyHandlerExcetionResolver implements HandlerExceptionResolver { @Override public void resolveException(WebRequest request, Handler handler, ChannelHandlerContext ctx, Exception e) { System.err.println("异常处理器捕获到异常了"); e.printStackTrace(); Map map = new HashMap(); map.put("error", "程序发生异常,被统一的异常处理器捕获了"); String message = JSONObject.toJSONString(map); HttpResponseUtils.sendHttpResponse(ctx, HttpResponseStatus.OK, message, "application/json"); } } ``` 测试接口: ``` @RequestMapping(value = "except", method = RequestMethod.POST) @ResponseBody public Object test9() throws Exception{ Map map = new HashMap(); map.put("code","200"); map.get("age").toString(); return map; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0406/192107_f8675ae8_1213036.png "微信截图_20180406174501.png") #### 12.测试绑定Bean User类: ``` public class User { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 接口: ``` @RequestMapping(value = "bean", method = RequestMethod.POST) @ResponseBody public Object test10(User user) throws Exception { return user; } ``` ![输入图片说明](https://gitee.com/uploads/images/2018/0407/105903_70dae851_1213036.png "微信截图_20180407105626.png") 完整的测试代码在src/test/java包下 (完)