Springboot实现重定向

导读:本篇文章讲解 Springboot实现重定向,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

概述

最近发现不太了解重定向如何实现,这里做下讲解。

如何重定向

@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

获取get请求或者post的form-data类型请求参数

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

获取post请求体类型参数(json类型请求)

// 利用下面的方法获取到body的json字符串,然后取值
// value是需要取得参数的值,key是参数名
public void getValue(HttpServletRequest request, String key){
    String jsonBody = getBodyData(request);
    JSONObject jsonObject = JSON.parseObject(jsonBody);
    String value = jsonObject.getString(key)
}
// 获取到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();
}

参考

java实现重定向(springboot)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99904.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!