Java获取页面路径以及请求参数

2020-07-14  本文已影响0人  超音速6

功能需求

在开发项目的过程中,有一个需求。添加、修改、删除操作完成后,要跳回到原页面。我想到了保存列表页面的请求链接和参数。添加、修改、删除操作完成后重定向上次保存的链接。

实现过程

package com.demo.intercepter;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 后台列表记住查询条件拦截器
 */
public class ExtendFunctionIntercepterForAdmin extends HandlerInterceptorAdapter {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.preHandle(request, response, handler);
        Web.getReturnUrl(request,response);
        return true;
    }

}
<mvc:interceptors>
    <!--后台列表记住查询条件拦截器-->
    <mvc:interceptor>
        <!--用户列表-->
        <mvc:mapping path="/admin/user/list"/>
                <!--笔记列表-->
        <mvc:mapping path="/admin/note/list"/>
        <bean class="com.demo.intercepter.ExtendFunctionIntercepterForAdmin"></bean>
    </mvc:interceptor>
</mvc:interceptors>
/**
* 修改用户方法
*/
@RequestMapping("/admin/user/update")
public String userUpdate(User user, HttpServletRequest request) {
    return Web.returnUrl(request, "/admin/user/" + request.getParameter("type"));
}
//使用自动跳转
$.ajax({
    url: "/admin/user/update",
    data: {
        "id":"1",
        "name": "里斯"
    },
    type: "post",
    dataType: "json",
    success: function (result) {
        //自动跳转
        fanhui('/admin/user/cus');
    }
});
//使用弹框提示点击确定跳转
$.ajax({
    url: "/admin/user/update",
    data: {
        "id":"1",
        "name": "里斯"
    },
    type: "post",
    dataType: "json",
    success: function (result) {
        //弹窗点击确定后跳转
        fanhuiManual('/admin/user/cus');
    }
});

// 自动跳转
function fanhui(url){
    var reUrl = getCookieFromServer("reUrl")
    if (!isEmpty(reUrl)) {
        location.href=reUrl;
    }else{
        location.href=baselocation + url;
    }
}

// 手动跳转
function fanhuiManual(url){
    var reUrl = getCookieFromServer("reUrl")
    if (!isEmpty(reUrl)) {
        return reUrl;
    }else{
        return baselocation + url;
    }
}

//获取Cookies方法,解决中文乱码
function getCookieFromServer(cookieName) {
    var cookieString = document.cookie;
    var start = cookieString.indexOf(cookieName + '=');
    // 加上等号的原因是避免在某些 Cookie 的值里有
    // 与 cookieName 一样的字符串。
    if (start == -1) // 找不到
        return null;
    start += cookieName.length + 1;
    var end = cookieString.indexOf(';', start);
    if (end == -1) {
        return Url.decode(cookieString.substring(start));
    } else {
        return Url.decode(cookieString.substring(start, end));
    }
}
var Url = {
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12)
                    | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
        return string;
    }
};
package com.demo.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

public class Web {
    private static Logger logger = LoggerFactory.getLogger(Web.class);

    /**
     * 获取返回URL
     *
     * @param request
     * @param response
     */
    public static void getReturnUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            StringBuffer stringBuffer = new StringBuffer();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
                stringBuffer.append("&");
                stringBuffer.append(stringEntry.getKey());
                stringBuffer.append("=");
                stringBuffer.append(URLEncoder.encode(stringEntry.getValue()[0], "UTF-8"));
            }
            String url = "http://" + request.getServerName() + request.getRequestURI();
            if (parameterMap.size() > 0) {
                url = url + stringBuffer.replace(0, 1, "?");
            }
            WebUtils.setCookie(response, "reUrl", URLEncoder.encode(url,"utf-8"), 1);
        } catch (Exception e) {
            logger.error("returnUrl", e);
        }
    }

    /**
     * 保存Cookie
     *
     * @param response
     */
    public static void setCookie(HttpServletResponse response, String key, String value, int days) {
        if (key != null && value != null) {
            Cookie cookie = new Cookie(key, value);
            cookie.setMaxAge(days * 24 * 60 * 60);
            cookie.setPath("/");
            response.addCookie(cookie);
        }

    }

    /**
     * 获取Cookie中保存的返回地址
     *
     * @param request
     * @return
     */
    public static String returnUrl(HttpServletRequest request, String url) {
        try {
            // 返回原来的页面
            String reUrl = getCookie(request, "reUrl");
            if (StringUtils.isNotBlank(reUrl)) {
                return "redirect:" + URLDecoder.decode(reUrl,"utf-8");
            }
        } catch (Exception e) {
            logger.error("returnUrl", e);
        }
        return "redirect:http://" +request.getServerName() + url;
    }

     /**
     * 获取Cookie中保存的返回地址
     *
     * @param request
     * @return
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        String resValue = "";
        if (cookies != null && cookies.length > 0) {
            for(int i = 0; i < cookies.length; ++i) {
                if (key.equalsIgnoreCase(cookies[i].getName()) && StringUtils.isNotEmpty(cookies[i].getValue())) {
                    resValue = cookies[i].getValue();
                }
            }
        }

        return resValue;
    }
}

总结

  1. 编写用户保存链接和请求参数的拦截器
  2. 配置拦截,添加要拦截的路径
  3. 执行修改用户,成功后使用java跳转链接
  4. 使用Ajax修改用户,成功后使用js条件链接
上一篇下一篇

猜你喜欢

热点阅读