java中spring的web支持nio,ws-web: 基于Netty的web项目,实现了SpringMVC中如@RequestParam、@Value、@Controller等注解的功能,使得我们...

使用说明

配置服务器并启动,代码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;

}

dda8228755e43940b99d9c646b5a9544.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;

}

e10cb0215ba5262ead41aa308cdfaefe.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;

}

26f73651598d4fb6c2a50997bf8a96a6.png

接口限定请求方法为post,如果用get来请求,则出现“The request method 'GET' does not sopport this mapping[/test/request].”错误提示:

d6d6432aefd32fd47726371b3cbf3a4a.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;

}

d1f69f071166cfc01197b876d88f1bd4.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;

}

e62175d7ab2a76f2323f4e3646be9d28.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;

}

c451a5830691305207a70e90cd019e47.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;

}

c64c88b76c20ba52981b353c83bafac7.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;

}

d65e5747c04e788ab8106551e700a7e8.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;

}

83ba48380eac1b4c5c9c0917967a717b.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;

}

01eb9ab9e5bdb1024606dbea1c548667.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;

}

5a173ed98249e1df8ccf64ea34e2541e.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;

}

f51b93d4ff201a7fa483777562a302da.png

完整的测试代码在src/test/java包下

(完)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值