文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

使用servlet实现远程调用(2)

2023-06-03 02:23

关注

使用servlet实现远程调用的修改

全部代码:

[@more@]package com.witframework.remote;


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;

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;


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;




public class RemoteExecutor {
static Logger logger = Logger.getLogger ( RemoteExecutor.class) ;

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;





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;



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);
}

}
阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯