使用servlet实现远程调用的修改
我们提供的服务有:做网站、成都网站制作、微信公众号开发、网站优化、网站认证、常山ssl等。为上1000+企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的常山网站制作公司
全部代码:
[@more@]package com.witframework.remote;
/**
* 对远程调用请求的封装
* @author wuxinyang
*/
public class HttpInvokeRequest implements java.io.Serializable,Cloneable{
private static final long serialVersionUID = 1L;
//目标地址,如果为localhost则为本地方法调用。
private String serverAddress;
private String serviceType="spring";
//spring bean的配置名称,如果配置了该值则通过spring配置装载service。
//服务的接口class名称,必须带包名
private String serviceName;
//要调用的方法名称
private String methodName;
//传入的参数列表
private Object[] arguments;
private boolean resultAsXml;
/**
* serverAddress=localhost:8080
* serviceAddress=spring:service/getAll
* serviceAddress=class:service/getAll
*/
public HttpInvokeRequest(String serviceAddress) {
int typeIndex=serviceAddress.indexOf(":");
if(typeIndex>0){
serviceType=serviceAddress.substring(0,serviceAddress.indexOf(":"));
this.serviceName=serviceAddress.substring(serviceAddress.lastIndexOf(":")+1,serviceAddress.lastIndexOf("/"));
}else{
this.serviceName=serviceAddress.substring(0,serviceAddress.indexOf("/"));
}
this.methodName=serviceAddress.substring(serviceAddress.lastIndexOf("/")+1);
}
public HttpInvokeRequest(String serverAddress,String serviceAddress) {
this(serviceAddress);
this.serverAddress=serverAddress;
}
/**
* 清除参数列表
*/
public void clearArguments(){
arguments=null;
}
public void setArgument(Object... args){
arguments=args;
}
public Object[] getArguments() {
return arguments;
}
public String getMethodName() {
return methodName;
}
public String getServerAddress() {
return serverAddress;
}
public String getServiceName() {
return serviceName;
}
public String getServiceType(){
return serviceType;
}
@Override
public Object clone() throws CloneNotSupportedException{
return super.clone();
}
public void setServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public boolean isResultAsXml() {
return resultAsXml;
}
public void setResultAsXml(boolean resultAsXml) {
this.resultAsXml = resultAsXml;
}
}
package com.witframework.remote;
import org.apache.commons.beanutils.MethodUtils;
/**
* 简单远程调用请求解析执行类
* @author wuxinyang
*
*/
class LocalRequestProcessor {
public static Object processorLocalhost(HttpInvokeRequest request){
String serviceName = request.getServiceName();
try {
Object service;
if(request.getServiceType().equalsIgnoreCase("spring")){
service=com.witframework.core.BeanFactory.getBean(serviceName);
}
else{
service = Class.forName(serviceName).newInstance();
}
Object object= MethodUtils.invokeExactMethod(service, request.getMethodName(),request.getArguments());
if(request.isResultAsXml())
object=Java2Xml.toXml(object);
return object;
} catch (Exception e) {
return new HttpInvokerException("处理远程调用时发生错误.",e);
}
}
}
package com.witframework.remote;
import java.io.Closeable;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import org.apache.log4j.Logger;
/**
* 简单远程调用请求解析执行类
* @author wuxinyang
*
*/
public class RemoteExecutor {
static Logger logger = Logger.getLogger ( RemoteExecutor.class) ;
/**
* 执行远程调用
* @return 返回值对象
* @throws HttpInvokerException 在授权验证失败或调用参数错误时 */
public static Object invoke(HttpInvokeRequest httpInvokeRequest) throws HttpInvokerException {
return invoke(httpInvokeRequest,false);
}
public static Object invoke(HttpInvokeRequest httpInvokeRequest,boolean resultAsXml) throws HttpInvokerException {
Object result;
long startTime=System.currentTimeMillis();
if(null==httpInvokeRequest)
throw new HttpInvokerException("not set HttpInvokerRequest.");
if(httpInvokeRequest.getServerAddress().equals("localhost")){
result= LocalRequestProcessor.processorLocalhost(httpInvokeRequest);
if(resultAsXml)
result=Java2Xml.toXml(result);
return result;
}
try {
HttpInvokeRequest request=(HttpInvokeRequest)httpInvokeRequest.clone();
request.setResultAsXml(resultAsXml);
result= processorRemote(request);
} catch (CloneNotSupportedException e) {
throw new HttpInvokerException(e);
}
long usetime=System.currentTimeMillis()-startTime;
logger.debug("call remote service completed. used time:"+usetime);
return result;
}
private static Object processorRemote(HttpInvokeRequest httpInvokeRequest) throws HttpInvokerException {
java.net.URLConnection con;
ObjectOutputStream dataout=null;
InputStream conis=null;
OutputStream conos=null;
ObjectInputStream in=null;
try {
URL url = new URL("http://"+httpInvokeRequest.getServerAddress()+"/httpinvoker");
con = url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-type", "application/octest-stream");
conos=con.getOutputStream();
dataout = new ObjectOutputStream(conos);
dataout.writeObject(httpInvokeRequest);
conis=con.getInputStream();
in = new ObjectInputStream(conis);
Object obj = in.readObject();
if(obj instanceof RuntimeException){
throw (RuntimeException)obj;
}
return obj;
}catch (Exception e) {
throw new HttpInvokerException(e);
}finally{
close(in);
close(conos);
close(conis);
close(dataout);
}
}
private static void close(Closeable object){
try {
object.close();
} catch (Exception e) {
}
}
}
package com.witframework.remote;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.log4j.Logger;
/**
* 远程调用的
服务器处理类,要是有remote包,需要在提供远程服务的应用上配置
* WitRemoteServlet,如下:
*
*
* WitRemoteServlet
* com.witframework.remote.WitRemoteServlet
*
*
* WitRemoteServlet
* /httpinvoker
*
*
*
* @author wuxinyang
*/
public class WitRemoteServlet extends GenericServlet {
static Logger logger = Logger.getLogger ( WitRemoteServlet.class) ;
@Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
ObjectInputStream in = new ObjectInputStream(req.getInputStream());
resp.setContentType("application/octest-stream");
HttpInvokeRequest request = null;
try {
request = (HttpInvokeRequest)in.readObject();
logger.debug("invoke request:"+request.toString());
} catch (ClassNotFoundException e) {
outObject(resp,new HttpInvokerException(e));
}
outObject(resp,LocalRequestProcessor.processorLocalhost(request));
}
private void outObject(ServletResponse resp,Object o) {
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
ObjectOutputStream out=null;
ServletOutputStream servletout=null;
try {
out = new ObjectOutputStream(byteout);
out.writeObject(o);
byte buf[] = byteout.toByteArray();
resp.setContentLength(buf.length);
servletout = resp.getOutputStream();
servletout.write(buf);
} catch (Exception e) {
e.printStackTrace();
}finally{
close(servletout);
close(out);
}
}
private static void close(Closeable object){
try {
object.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.witframework.remote;
/**
* 简单远程调用异常类型定义类
* @author wuxinyang
*
*/
public class HttpInvokerException extends RuntimeException{
private static final long serialVersionUID = 20080804L;
public HttpInvokerException(String msg) {
super(msg);
}
public HttpInvokerException(Throwable cause) {
super(cause);
}
public HttpInvokerException(String msg,Throwable cause){
super(msg,cause);
}
}
本文名称:使用servlet实现远程调用(2)
网址分享:
http://bjjierui.cn/article/gpehhs.html