使用说明
配置服务器并启动,代码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;
}
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;
}
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;
}
接口限定请求方法为post,如果用get来请求,则出现“The request method 'GET' does not sopport this mapping[/test/request].”错误提示:
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
完整的测试代码在src/test/java包下
(完)