Spring mvc Controller 处理安卓post和get请求

来源:互联网 发布:java分布式 编辑:程序博客网 时间:2024/05/14 02:26

@Controller@RequestMapping ("/MyController")public class MyController {  @RequestMapping ("/test")  @ResponseBody     public String download (HttpServletRequest request)    {  String pathname = request.getParameter("a");          String filename = request.getParameter("b");          return pathname+";"+filename;    }      @RequestMapping (value = "/test1",method = RequestMethod.GET)  @ResponseBody     public Map<String, Object>  download1 (HttpServletRequest request)    { String pathname = request.getParameter("a");         String filename = request.getParameter("b");         HashMap hashMap = new HashMap();         hashMap.put("a", pathname);         hashMap.put("b", filename);         return hashMap;    }      @RequestMapping (value ="/test2",method = RequestMethod.POST)  @ResponseBody     public Map<String, Object>  download2 (HttpServletRequest request)    {  Map<String, Object> httpToMap = HttpToMap(request);  if(httpToMap== null) {  httpToMap = new HashMap<String,Object>();   httpToMap.put("error", "没有数据");  }  return httpToMap;            }    @RequestMapping (value ="/test3",method = RequestMethod.POST)  @ResponseBody     public Map<String, Object>  download3 (HttpServletRequest request)    {  try {request.setCharacterEncoding("utf-8");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}  String parameter = request.getParameter("a");  return null;            }         StudentDAO studentDAO = new StudentDAO();//调用登陆判断方法        @RequestMapping(value="/doLogin/{username}/{password}",method=RequestMethod.GET)    @ResponseBody    public Map<String, Object> getTeacher(@PathVariable("username") Integer username, @PathVariable("password") String password){            System.out.println("拦截了客户端json请求");        Map<String, Object> map = new HashMap<String, Object>();                System.out.println("密码错误");        map.put("result", "密码错误");        return map; //封装为json返回给客户端    }          //********************************************************************************    public Map <String, Object> HttpToMap (HttpServletRequest request)    {        Map <String, Object> map;        try        {            JSONObject jsonObject = HttpToJson (request);            map = getMap (jsonObject);        }        catch (Exception e)        {            map = null;        }        return map;            }        public JSONObject HttpToJson (HttpServletRequest request)    {        JSONObject jsonObject;        BufferedReader reader = null;        try        {            reader = new BufferedReader (new InputStreamReader (request.getInputStream (), "utf-8"));            String jsonStr = null;            StringBuilder result = new StringBuilder ();            while ((jsonStr = reader.readLine ()) != null)            {                result.append (jsonStr);            }            jsonObject = JSONObject.parseObject (result.toString ()); // 取一个json转换为对象        }        catch (Exception e)        {            jsonObject = null;        }        finally        {            if (null != reader)            {                try                {                    reader.close ();                }                catch (IOException e)                {                    //LOGGER.error ("Close reader error : ", e);                } // 关闭输入流            }        }        return jsonObject;    }        private Map <String, Object> getMap (JSONObject jsonObject)    {        Map <String, Object> map = new HashMap <String, Object> ();        for (Iterator <String> keyIter = jsonObject.keySet ().iterator (); keyIter.hasNext ();)        {            String key = (String) keyIter.next ();                        if (jsonObject.get (key).getClass ().equals (JSONObject.class))            {                Map <String, Object> map2;                map2 = getMap (jsonObject.getJSONObject (key));                map.put (key, map2);            }            else if (jsonObject.get (key).getClass ().equals (JSONArray.class))            {                List <Map <String, Object>> list;                list = getList (jsonObject.getJSONArray (key));                map.put (key, list);            }            else            {                map.put (key, jsonObject.get (key));            }        }                return map;    }        private List <Map <String, Object>> getList (JSONArray jsonArray)    {        List <Map <String, Object>> list = new ArrayList<> ();        for (int i = 0; i < jsonArray.size (); i++)        {            Map <String, Object> map2;            map2 = getMap (jsonArray.getJSONObject (i));            list.add (map2);        }        return list;    }}

以上代码:
MyController 类之前加入注解
@Controller 声明是controller层
@RequestMapping ("/MyController") 该controller层目录结构 访问路径   ip:端口号/工程名称/MyController/

1.get请求

  @RequestMapping ("/test")  @ResponseBody     public String download (HttpServletRequest request)    {  String pathname = request.getParameter("a");          String filename = request.getParameter("b");          return pathname+";"+filename;    }
访问路径为:
ip:端口号/工程名称/MyController/test?a=username&b=passworld
get请求内容在请求头上,拼接在url后面
如果不声明请求方式默认为get请求,所以 test和test1请求是等效的
 StudentDAO studentDAO = new StudentDAO();//调用登陆判断方法        @RequestMapping(value="/doLogin/{username}/{password}",method=RequestMethod.GET)    @ResponseBody    public Map<String, Object> getTeacher(@PathVariable("username") Integer username, @PathVariable("password") String password){            System.out.println("拦截了客户端json请求");        Map<String, Object> map = new HashMap<String, Object>();                System.out.println("密码错误");        map.put("result", "密码错误");        return map; //封装为json返回给客户端    }

这种方式自定义格式
访问路径为:
ip:端口号/工程名称/MyController/doLogin/username/passworld
就可以得到 username 和passworld字段

2.post请求
post请求请求的内容通过http body部分发送
  @RequestMapping (value ="/test2",method = RequestMethod.POST)  @ResponseBody     public Map<String, Object>  download2 (HttpServletRequest request)    {  Map<String, Object> httpToMap = HttpToMap(request);  if(httpToMap== null) {  httpToMap = new HashMap<String,Object>();   httpToMap.put("error", "没有数据");  }  return httpToMap;            }

这里通过request拿到流对象,再转换成String -->Json -->Map  参考工具方法:HttpToMap,HttpToJson,getMap,getList方法
以上方法亲测可用
test3,本来
 request.getParameter("key值"),可以拿到json的值,或者
request.getParameterMap可以拿到集合 这里一直拿到空(待研究)