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

本文详细介绍了Spring MVC中GET和POST请求的处理方法,包括如何通过URL参数获取数据、解析JSON请求体并转换为Map对象的过程。同时提供了实用的代码示例。

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

@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 block
			e.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可以拿到集合 这里一直拿到空(待研究)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值