springbootAPI接收参数的方式

背景:
  1.接口类使用注解 @RestController 这是个组合注解 包含@Controller @ResponseBody 所以呢  返回客户端的是json格式的字符串,不能跳转到页面
  2.@RequestMapping(value="/getDownloadMd5",method=RequestMethod.POST) post请求
请求方式:
第一种 入参中 使用注解@RequestParam
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value="username", required=false)

点击查看代码

  /* * 
     * @Description: 使用@RequestParm 可以处理入参字段比较少的请求
     * @Param: [username, password]
     * @Author: ZhaoJs
     * @Date: 2021/9/24 
     * @Version: 1.0
    **/
    @RequestMapping(value="/login",method=RequestMethod.GET)
    public ApiResponse<Map<String,Object>> addUser(@RequestParam("username") String username, @RequestParam("password") String password) {
        ApiResponse<Map<String,Object>> api = new ApiResponse<Map<String,Object>>();
        return api;
    }

第二种 请求参数比较多用bean来封装接受参数

点击查看代码
  /* * 
     * @Description: 通过bean来封装接口参数
     * @Param: [user] bean对象
     * @Author: ZhaoJs
     * @Date: 2021/9/24 
     * @Version: 1.0
    **/
    @RequestMapping("/addUser3")
    public String addUser2(UserModel user) {
        System.out.println("username is:"+user.getUsername());
        System.out.println("password is:"+user.getPassword());
        ApiResponse<Map<String,Object>> api = new ApiResponse<Map<String,Object>>();
        return api;
    }
  @RequestMapping(value = "/updateMemberBase" ,method = RequestMethod.POST)
    public ApiResponse<MesMemberVo> updateMember( @RequestBody MesMemberVo mesMemberVo){
 @RequestBody post请求中使用

第三种 通HttpServletRequest 来获取参数,get post都可以 可以获取多个参数 也可以获取json字符串

点击查看代码

  /* * 
     * @Description: 使用@RequestParm 可以处理入参字段比较少的请求
     * @Param: [username, password]
     * @Author: ZhaoJs
     * @Date: 2021/9/24 
     * @Version: 1.0
    **/
	@RequestMapping(value = "api/thbmember/thblogin" ,method = RequestMethod.GET)
	public ApiResponse<String> thblogin(HttpServletRequest request,HttpServletResponse response,@RequestParam("memberAccount") String memberAccount,@RequestParam("memberPassword") String memberPassword,
			@RequestParam("captchaCode") String captchaCode){
		ApiResponse<String> apiResponse = new ApiResponse<>();
		try {
			String memberCode = thbMemberService.login(request,response,memberAccount, memberPassword,captchaCode);
			apiResponse.setData(memberCode);
			apiResponse.setStatus(0);
		} catch (Exception e) {
			apiResponse.setStatus(1);
			apiResponse.setStatusText(e.getMessage());
		}
		return apiResponse;
	}

        ------requestSession 验证码逻辑 第一步获取验证码的时候 同时把这个值 放到了session中
                HttpSession session = request.getSession();
                session.setAttribute("captchaCode", captchaCode.toLowerCase());
	        String captchaCodesseion = (String) request.getSession().getAttribute("captchaCode");
		if(!captchaCode.equals(captchaCodesseion)){
			throw new RuntimeException("图形码输入错误");
		}

第四种 获取 json对象  通过@RequestBody 可以将请求体中的JSON字符串绑定到相应的bean上
          也可以将其分别绑定到对应的字符串上
          也可以  net.sf.json上 阿里巴巴

点击查看代码
  @RequestMapping(value="/getDownloadMd5",method=RequestMethod.POST)
    public ApiResponse<Map<String,Object>> getDownloadMd5(@RequestBody JSONObject jsonParam){
        ApiResponse<Map<String,Object>> api = new ApiResponse<Map<String,Object>>();
        // 直接将json信息打印出来
        //System.out.println(jsonParam.toString());
        String cardNo = jsonParam.getString("cardNo");
        String policyNo = jsonParam.getString("policyNo");

        return api
    }
	String insuredAllStr = request.getParameter("insuredAllStr");
	System.out.println("insuredAllStr:"+insuredAllStr); //这种是获取不到json对象的

4.2 HttpServletRequest request 解析requset

点击查看代码
	@RequestMapping(value="/underWirteBYZT",method=RequestMethod.POST)
	public void underWirteBYZT(HttpServletRequest request, HttpServletResponse response) {
		String requestStr = "";
		String message = "";
		PrintWriter pw = null;
		Map<String, Object> retMap = new HashMap<String, Object> ();
		try {
			pw = response.getWriter();
			requestStr = HttpContextUtils.getStrFromRequest(request);
			message = intefCarInsService.underWirteInform(requestStr);
			System.err.println(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
		retMap.put("ResponseCode", "0");
		retMap.put("ErrorMessage", "");
		pw.write(JSONObject.fromObject(retMap).toString());
	}



public class HttpContextUtils {
	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
	/**
	 * 从输入流里获取请求字符串
	 * @param req
	 * @return
	 * @throws IOException
	 */
	public static String getStrFromRequest(HttpServletRequest req) throws Exception {
		//拿到字节流
		ServletInputStream servletInputStream = req.getInputStream();
		
		//以  UTF-8  的编码格式 拿到字符流
		InputStreamReader inputStreamReader = new InputStreamReader(servletInputStream,"UTF-8");
		
		//把字符流加到缓冲流,以便提高读取效率
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		
		String readStr = null;
		StringBuffer str = new StringBuffer();
		while((readStr = bufferedReader.readLine()) != null){
			str.append(readStr);
		}

		bufferedReader.close();
		inputStreamReader.close();
		servletInputStream.close();
		
//		System.err.println(JSONObject.fromObject(str.toString()));
		return str.toString();
	}
}

第五种@PathVariable获取路径中的参数
posted @ 2021-09-24 15:22  BBS_自律  阅读(281)  评论(0编辑  收藏  举报