请求服务(RequestService)

一个module中的web组件,负责将Service的结果按照适当的规范输出给前端。
格式:http://server/moduleID/param0/param1/paramN/p.TYPE
格式上包含三部分:
moduleID:将请求分发到具体的模块,分发器参考下面具体介绍;
paramX:参数部分
TYPE:使用什么请求服务完成,对应到module中的一个具体的RequestService

从MVC的角度来看,这个相当于C,将服务提供的模型数据以适当的形式展现给前端;

一、请求分发器
framework中的web组件,一个标准的Http Filter或HttpServlet,下面是Filter版本的代码
public void doFilter(ServletRequest sreq, ServletResponse sresp,
  FilterChain chain) throws IOException, ServletException {
 HttpServletRequest req = (HttpServletRequest)sreq;
 HttpServletResponse resp = (HttpServletResponse)sresp;
 req.setAttribute(Constants.SERVLET_CONTEXT, servletContext);
 //
 String path = req.getRequestURI();
 if((path == null || path.length() <= 1) && !StringUtils.isEmpty(welcomePage))
  path = this.welcomePage;
 //
 LocalModule module = null;
 String[] uris = null;
 String reqType = null;
 if(path.indexOf(".") > 0) {
  path = path.replaceAll("/+", "/").substring(req.getContextPath().length());
  reqType = path.substring(path.lastIndexOf(".") + 1);
  final String pathEff = path.substring(0, path.lastIndexOf("."));
  
  uris = StringUtils.split(pathEff, "/");
  
  final String moduleId = uris[0];
  module = Application.getInstance().getModules().exists(moduleId)?Application.getInstance().getModules().getLocalModule(moduleId): null;
  Principal principal = (Principal)req.getSession().getAttribute(Principal.PRINCIPAL);
  if(principal == null && req.getUserPrincipal() != null) {
   principal = new SimpleUserPrincipal(req.getUserPrincipal().getName(), req.getUserPrincipal().getName(), req.getUserPrincipal());
  }
  if(module != null) {
   req.setAttribute(Constants.MODULE, module);
   Data request = DataUtils.convert(module, req);
   ThreadContext ctx = new ThreadContext(module, request, principal);
   ThreadContext.setContext(ctx);
  }
 }
 //
 if(module != null && !StringUtils.isEmpty(reqType) && module.canHandleRequest(reqType)) {
  final String[] pathItems = new String[uris.length - 1];
  System.arraycopy(uris, 1, pathItems, 0, uris.length - 1);
  processRequestInChain(module, reqType, req, resp, pathItems);
 } else {
  chain.doFilter(sreq, sresp);
 }
}
判断规则:
1、请求的模块存在:Application.getInstance().getModules().exists(moduleId)
2、请求的模块能够处理该类型请求:module.canHandleRequest(reqType)

二、开发RequestService
需要实现接口RequestService:
public interface RequestService {
 public void service(LocalModule module, String[] pathItems, HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException;
}

一个典型的把服务的处理结果输出为Json的RequestService:
public class JsonRequestService extends AbstractRequestService implements RequestService {

 private final static Logger logger = Logger.getLogger(JsonRequestService.class);

 public void service(LocalModule module, String[] uris, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

  Data request = DataUtils.convert(module, req);
  request.put(Constants.ACTION_TYPE, Constants.ACTION_TYPE_ACTION);
  resp.setContentType("application/json");

  JSONResult result = new JSONResult();
  result.setRequest(request);

  String serviceId = uris[0];
  if (!module.getModuleConfig().getServiceConfigs().containsKey(serviceId))
   serviceId += "Action";
  String method = uris[1];
  String serviceModuleId = uris.length == 3 ? uris[2] : module.getId();
  try {
   final Data data = ServiceInvoker.invoke(module.getId(), serviceModuleId, serviceId + ":" + method, request);
   String results = (String) data.get("result");
   result.setResult(results);
   result.setData(data);
  } catch (ObjectNotFoundException e) {
   resp.sendError(404);
   return;
  } catch (AppException e) {
   logger.error(this.getClass().getName(), e);
   result.setResult(e.getErrorCode());
   result.setMessage(e.getMessage());
  } catch (Exception e) {
   logger.error(this.getClass().getName(), e);
   result.setResult("1");
   result.setMessage(e.getMessage());
  }
  String jsonString = result.toJSONString();
  logger.debug(jsonString);
  resp.getWriter().append(jsonString);
  resp.flushBuffer();
 }

}

三、注册
注册为服务,如下:
<service id="com.flyingwords.framework.request.impl.ShtmlRequestService" type="class" target="com.flyingwords.framework.request.impl.ShtmlRequestService">
 <desc></desc>
 <configs>
  <config name="content-type">text/html; charset=UTF-8</config>
  <config name="encoding">UTF-8</config>
 </configs>
</service>
注册为RequestService,如下:
<requests>
 <request type="json" service="com.flying.framework.request.impl.JsonRequestService"/>
</requests>

四、访问
http://server:port/pas/UserService/findByUserNameAndPassword.json
即可访问该接口了。

flying框架中,RequestService定义为服务的外延,是WEB访问服务的桥梁。

原文地址:https://www.cnblogs.com/hifong/p/5456651.html