springMVC框架下如何实现移动端接口调用2

本文介绍了一种移动端调用PC端接口的实现方案,包括拦截器验证、反射调用控制器方法等关键技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇博客中已经简单的整理了移动端调用PC端接口的实现流程,这其中涉及到springMVC拦截器的使用。下面通代码对应上篇博客中的流程简介看一下具体是如何实现的。首先定义一个拦截器,需要实现HandlerInterceptor接口,这个接口有三个方法,在这里的作用是验证用户是否登录,所用只用preHandle这个方法就可以完成。首先需要建立两个类,InDto和OutDto分别是信息接收实体和信息反馈实体。


InDto:主要是用来接收移动端URL请求的参数包括请求的controller、方法、参数。

[java]  view plain  copy
  1. <span style="font-size:18px;">/**  
  2.  * <p>Title:InDto</p> 
  3.  * Description:参数接收实体类  
  4.  */  
  5. public class InDto {  
  6.     /** 
  7.      * 版本号 
  8.      *一般为固定的,主要是为了和Action进行凭借识别对应的controller 
  9.      */  
  10.     private String version;  
  11.     /** 
  12.      * 方法包名 
  13.      */  
  14.     private String action;  
  15.     /** 
  16.      * 方法名 
  17.      */  
  18.     private String method;    
  19.     /** 
  20.      * 时间戳 
  21.      */  
  22.     private String timeStamp;     
  23.     /** 
  24.      * 请求参数 
  25.      */  
  26.     private String req;  
  27.     /** 
  28.      * 接口请求request 
  29.      */  
  30.     private HttpServletRequest request;  
  31.     /** 
  32.      * 接口请求response 
  33.      */  
  34.     private HttpServletResponse response;  
  35.     /** 
  36.      * 注入 
  37.      */  
  38.     private Object dao;  
  39.   
  40.     public String getVersion() {  
  41.         return version;  
  42.     }  
  43.     public void setVersion(String version) {  
  44.         this.version = version;  
  45.     }  
  46.     public String getAction() {  
  47.         return action;  
  48.     }  
  49.     public void setAction(String action) {  
  50.         this.action = action;  
  51.     }  
  52.     public String getMethod() {  
  53.         return method;  
  54.     }  
  55.     public void setMethod(String method) {  
  56.         this.method = method;  
  57.     }  
  58.     public String getTimeStamp() {  
  59.         return timeStamp;  
  60.     }  
  61.     public void setTimeStamp(String timeStamp) {  
  62.         this.timeStamp = timeStamp;  
  63.     }  
  64.       
  65.     public String getReq() {  
  66.         return req;  
  67.     }  
  68.     public void setReq(String req) {  
  69.         this.req = req;  
  70.     }  
  71.     public Object getDao() {  
  72.         return dao;  
  73.     }  
  74.     public void setDao(Object dao) {  
  75.         this.dao = dao;  
  76.     }  
  77.     public HttpServletRequest getRequest() {  
  78.         return request;  
  79.     }  
  80.     public void setRequest(HttpServletRequest request) {  
  81.         this.request = request;  
  82.     }     
  83.     public HttpServletResponse getResponse() {  
  84.         return response;  
  85.     }  
  86.     public void setResponse(HttpServletResponse response) {  
  87.         this.response = response;  
  88.     }  
  89.   
  90.     //构造函数  
  91.     public InDto(Map<String,String[]> map) throws IOException{  
  92.         this.version=map.get("Version")!=null?map.get("Version")[0]:"";  
  93.         this.action=map.get("Action")!=null?map.get("Action")[0]:"";          
  94.         this.method=map.get("Method")!=null?map.get("Method")[0]:"";                  
  95.         this.timeStamp=map.get("TimeStamp")!=null?map.get("TimeStamp")[0]:"";  
  96.         this.req=map.get("Req")!=null?map.get("Req")[0]:"";  
  97.   
  98.     }  
  99. }  
  100. </span>  


OutDto:主要用来返回约定的编码,方便移动端确定请求成功、失败、或者服务器请求失败。

[java]  view plain  copy
  1. <span style="font-size:18px;">/** 
  2.  * <p>Title:OutDto</p> 
  3.  * Description: 信息反馈实体类 
  4. */  
  5. public class OutDto {  
  6.     /** 
  7.      * 成功 
  8.      */  
  9.     public static final String STATUS_SUCCESS="100";    
  10.     /** 
  11.      * 失败 
  12.      */  
  13.     public static final String STATUS_FAIL="200";    
  14.     /** 
  15.      * 服务端异常 
  16.      */  
  17.     public static final String STATUS_EXCEPTION="300";    
  18.       
  19.     /** 
  20.      * 代码标识 
  21.      */  
  22.     private String status;  
  23.     /** 
  24.      * 信息 
  25.      */  
  26.     private String msg;  
  27.     /** 
  28.      * 返回数据 
  29.      */  
  30.     private Object data;  
  31.       
  32.       
  33.     public String getStatus() {  
  34.         return status;  
  35.     }  
  36.     public void setStatus(String status) {  
  37.         this.status = status;  
  38.     }  
  39.     public String getMsg() {  
  40.         return msg;  
  41.     }  
  42.     public void setMsg(String msg) {  
  43.         this.msg = msg;  
  44.     }  
  45.     public Object getData() {  
  46.         return data;  
  47.     }  
  48.     public void setData(Object data) {  
  49.         this.data = data;  
  50.     }  
  51.     /** 
  52.      * @描述 设置失败状态 
  53.      */  
  54.     public void setStatusFail() {  
  55.         this.status = STATUS_FAIL;  
  56.     }  
  57.     /** 
  58.      * @描述 设置失败状态和消息 
  59.      */  
  60.     public void setStatusFail(String msg) {  
  61.         this.status = STATUS_FAIL;  
  62.         this.msg=msg;  
  63.     }  
  64.       
  65.       
  66.     /** 
  67.      * @描述 设置成功状态 
  68.      */  
  69.     public void setStatusSuccess() {  
  70.         this.status = STATUS_SUCCESS;  
  71.     }  
  72.     /** 
  73.      * @描述 设置成功状态并插入data数据 
  74.      * @author quzf 
  75.      */  
  76.     public void setStatusSuccess(Object data,String msg) {  
  77.         this.status = STATUS_SUCCESS;  
  78.         this.data=data;  
  79.         this.msg=msg;  
  80.     }  
  81.     /** 
  82.      * @描述 设置成功状态并插入data数据 
  83.      */  
  84.     public void setStatusSuccess(String msg) {  
  85.         this.status = STATUS_SUCCESS;  
  86.         this.msg=msg;  
  87.         this.data="";  
  88.     }     
  89. }  
  90. </span>  


移动端约定的请求接口的URL:

[html]  view plain  copy
  1. http://localhost:8080/test/Service/dataSync.do?&Version=1.0&Action=login&Method=Login &TimeStamp=10000&Req={"params":{  
  2.     "userName": "admin",  
  3.     "userPwd ": "123456"  
  4.    }  
  5. }  


编写一个拦截器实现接口HandlerInterceptor

[java]  view plain  copy
  1. <span style="font-size:18px;">/** 
  2. * 
  3. *拦截器 
  4. */  
  5. public class DataSyncInterceptor   implements HandlerInterceptor {  
  6.       
  7.     @Autowired  
  8.     private OrganService organService;  
  9.       
  10.     /** 
  11.      * @描述 验证用户名密码是否正确 
  12.      */  
  13.     public OutDto testLegal(HttpServletRequest request) throws Exception {  
  14.         //实例化一个InDto,同时获得了客户端传来的信息  
  15. InDto inDto=new InDto(request.getParameterMap());  
  16.         JSONObject reqJSON = JSON.parseObject(inDto.getReq());  
  17.         String action = inDto.getAction();//获取到请求的Action  
  18.         OutDto outDto=new OutDto();  
  19.     if(action.equals("login")){//如果是登录进行验证    
  20. String userName = reqJSON.getString("userName");  
  21.             String userPwd = reqJSON.getString("userPwd");  
  22.             User user = organService.login(userName, userPwd);  
  23.               
  24.             if(user==null){  
  25.                 outDto.setStatusFail();  
  26.                 outDto.setMsg("用户名或密码不正确!");  
  27.             }else{  
  28.                 outDto.setStatusSuccess();  
  29.             }  
  30.             return outDto;  
  31.         }  
  32.     }  
  33.       
  34.         @Override  
  35.     public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
  36.             Object o) throws Exception {  
  37.         //请求参数注入InDto  
  38.         OutDto outDto=new OutDto();  
  39.         try {  
  40.             InDto inDto=new InDto(request.getParameterMap());  
  41.             //设置验证结果,先不走验证非法,直接返回成功  
  42.             outDto = testLegal(request);  
  43.             //参数验证结果成功后,执行下面的拦截器  
  44.             if(OutDto.STATUS_SUCCESS.equals(outDto.getStatus())){  
  45.                 return true;  
  46.             }else{  
  47.                 response.setCharacterEncoding("UTF-8");  
  48.                 PrintWriter out = response.getWriter();   
  49.                 out.print(JsonUtil.object2json(outDto));  
  50.                 out.close();    
  51.               return false;  
  52.             }  
  53.         } catch (Exception e) {  
  54.              response.setCharacterEncoding("UTF-8");  
  55.              outDto.setStatus(OutDto.STATUS_EXCEPTION);//异常时  
  56.              PrintWriter out = response.getWriter();   
  57.              out.print(JsonUtil.object2json(outDto));    
  58.              e.printStackTrace();  
  59.              out.close();    
  60.             return false;  
  61.         }  
  62.     }  
  63.   
  64.     @Override  
  65.     public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,  
  66.             Object arg2, ModelAndView arg3) throws Exception {  
  67.         // TODO Auto-generated method stub  
  68.           
  69.     }  
  70.   
  71.     @Override  
  72.     public void afterCompletion(HttpServletRequest arg0,  
  73.             HttpServletResponse arg1, Object arg2, Exception arg3)  
  74.             throws Exception {  
  75.         // TODO Auto-generated method stub  
  76.           
  77.     }  
  78. }  
  79. </span>  


          拦截器配置到mvc的配置文件中:

[html]  view plain  copy
  1. <mvc:interceptors>  
  2.         <mvc:interceptor>  
  3.             <!-- //映射路径后缀名 -->  
  4.             <mvc:mapping path="/Service/*"/>  
  5.             <!--//自定义拦截器 -->  
  6.             <bean class="interceptor.DataSyncInterceptor"/>  
  7.         </mvc:interceptor>  
  8. </mvc:interceptors>  

        拦截器走完如果用户验证通过后preHandle方法返回true,由于没有配置其他的拦截器就会根据请求的URL开始调用对应的controller。请求的URL中有“http://localhost:1080/test/Service/dataSync.do”   所以会根据URL找到Service这个controller中的dataSync方法。

[java]  view plain  copy
  1. <span style="font-size:18px;">/** 
  2.  * <p>Title:ServiceController</p> 
  3.  * Description: 移动端接口入口 
  4.  */  
  5. @Controller  
  6. @RequestMapping("Service")  
  7. public class ServiceController{  
  8.       
  9.      @RequestMapping({"/dataSync"})  
  10.      @ResponseBody  
  11.     public void dataSync(HttpServletRequest request, HttpServletResponse response) {  
  12.          OutDto outDto = new OutDto();  
  13.         try {  
  14.              InDto inDto=new InDto(request.getParameterMap());  
  15.              inDto.setRequest(request);  
  16.              inDto.setResponse(response);             
  17.              String method = inDto.getMethod();            
  18.             if(StringUtils.isBlank(method)){  
  19.                 method=AtcConstant.getAtcClassMethod();  
  20.             }             
  21.             //依据action和method,然后读取配置中的类反射执行该class  
  22.             Object bean = SpringHelper.getBean(inDto.getAction()+inDto.getVersion());         
  23.             outDto=(OutDto) ReflectUtil.invoke(bean,method, inDto,outDto);  
  24.         } catch (Exception e) {  
  25.             outDto.setStatus(OutDto.STATUS_EXCEPTION);  
  26.             e.printStackTrace();  
  27.         }  
  28.         try {  
  29.             //返回的结构为字节流是调用,为移动端做附件下载时使用  
  30.             if ("返回流".equals(outDto.getMsg())) {   
  31.                 OutputStream outputStream=response.getOutputStream();  
  32.                 InputStream is=new FileInputStream(outDto.getData().toString());  
  33.                 byte b[] = new byte[1024];  
  34.                 int len = -1;  
  35.                 while ((len = is.read(b)) != -1)  
  36.                     outputStream.write(b, 0, len);  
  37.                   
  38.                 is.close();  
  39.                 outputStream.close();  
  40.             }else {     //非字节流结果返回时调用  
  41.                 response.setCharacterEncoding("UTF-8");  
  42.                 PrintWriter out = response.getWriter();  
  43.                 out.print(JsonUtil.object2json(outDto));  
  44.                 out.close();    
  45.             }             
  46.         } catch (IOException e) {  
  47.             e.printStackTrace();  
  48.         }         
  49.     }  
  50. }  
  51. </span>  

        这个方法中的核心代码是:

String method = inDto.getMethod();

Object bean =SpringHelper.getBean(inDto.getAction()+inDto.getVersion());      

outDto=(OutDto)ReflectUtil.invoke(bean,method, inDto,outDto);


         根据请求的Action+Version 可以确定要调用的Controller,用ReflectUtil中的invoke方法,将得到的实体bean和要调用的方法名称作为参数传递就可以调用相应controller中的方法。以这次的登录为例Action=login;Version =1.0就会请求名为login1.0的Controller中的Login方法。在这个controller的方法中就可以写系统的业务逻辑代码。

 

小结:

         移动端调用接口的代码实现就是这样的,通过拦截器进行登录验证,使用invoke调用请求的controller中的方法。




版权声明:本文为博主原创文章,未经博主允许不得转载。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值