一、如何重定向

最近有业务需要用到重定向,摸索了很久,下面是代码:

@RestController
public class FirstController {

    @PostMapping("/test")
    public void login(HttpServletRequest req,HttpServletResponse resp) throws IOException {

        // 构造重定向的路径:
        String username = req.getParameter("username");
        String password = req.getParameter("password ");           
        url.append("http://192.168.xx.xx/login?").append("username=").append(username).append("&")
                .append("password=").append(password);
        String redirectToUrl = url.toString();
        // 发送重定向响应:
        resp.sendRedirect(redirectToUrl);
    }
}

实现的功能:访问/test接口,将参数username和password拼接在需要重定向的url上一起重定向到指定的地址。

二、对于参数的获取

在接口参数里添加HttpServletRequest request

1、如果是get请求或者post的form-data类型使用如下方法:

//values是参数的值,可以是参数的名称
String value = request.getParameter(key);

2、如果是post请求的body类型:

//获取到body的json字符串
private String getBodyData(HttpServletRequest request){
    LOG.info("get request body");
    StringBuffer data = new StringBuffer();
    String line;
    BufferedReader reader = null;
    try {
        reader = request.getReader();
        while (null != (line = reader.readLine()))
            data.append(line);
    } catch (IOException e) {
        LOG.warn("get request body error: ", e);
        throw new CustomSsoException("获取body异常");
    } finally {
        if (reader != null){
            try {
                reader.close();
            } catch (IOException e) {
                LOG.error("reader close error:",e);
            }
        }
    }
    return data.toString();
}
//利用上面的方法获取到body的json字符串,然后取值
//value是需要取得参数的值,key是参数名
public void getValue(HttpServletRequest request){
    String jsonBody = getBodyData(request);
    JSONObject jsonObject = JSON.parseObject(jsonBody);
    String value = jsonObject.getString(key)
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐