您的位置:首页 > 编程语言 > Java开发

——具体jsp聊天室项目体会Java反射

2016-11-16 19:10 239 查看
这是之前写的一篇博客,对java反射机制用法的基本介绍

http://blog.csdn.net/sinat_34803353/article/details/53150164

下面是聊天室项目的一个完整Baseservlet

反射写的一个基本servlet,以前就是,xie一个servlet需要继承HttpServlet,里面是doGet()或者doPost()方法,但它只能执行一个,一般情况下是一个模块对应一个servlet,这样比较清晰,或者像在struct2里面,一个模块的请求都会发到一个action里。这里,我们用反射模拟这种情况,一个servlet里面可以执行多个方法——怎么执行多个方法呢?就是在页面上,我们传了一个参数名,我们这里是叫method,值就是value值,假设value=”login”,然后我们就想让servlet执行login方法,那么这个是怎么做到的呢?——对,就是使用反射。

看这个Baseservlet,首先,我们会接收到一个method的value

package cn.utils;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {
/*
* 它会根据请求中的m,来决定调用本类的哪个方法
*/
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=utf-8");

// 例如:http://localhost:8080/demo1/xxx?method=login
String methodName = req.getParameter("method");// 它是一个方法名称

// 当没用指定要调用的方法时,那么默认请求的是execute()方法。
if(methodName == null || methodName.isEmpty()) {
methodName = "execute";
}

// ①得到字节码文件
Class c = this.getClass();
try {
// ②通过方法名称获取方法的反射对象
Method m = c.getMethod(methodName, HttpServletRequest.class,
HttpServletResponse.class);

//③ 反射方法目标方法,也就是说,如果methodName为login,那么就调用login方法。
String result = (String) m.invoke(this, req, res);

// ④通过返回值完成请求转发
if(result != null && !result.isEmpty()) {
req.getRequestDispatcher(result).forward(req, res);
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}


下面是项目地址,大家如果相残考,可以下载完整代码

https://github.com/Sunshine-lhy/ChatRoom
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: