Java 在 Spring MVC/Security 中设置和读取 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20351554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:17:01  来源:igfitidea点击:

Set and read cookies in Spring MVC/Security

javaspringspring-mvccookiesspring-security

提问by TurtleFrog

I am new to Spring and I need to set a custom cookie when "Login" button is clicked, and then that cookie will be red inside the webapp. What is the best practice to do exactly that? Also, this brings question how to read it later on every page in webapp?

我是 Spring 的新手,我需要在单击“登录”按钮时设置一个自定义 cookie,然后该 cookie 在 webapp 中将变为红色。做到这一点的最佳做法是什么?此外,这带来了如何稍后在 webapp 中的每个页面上阅读它的问题?

I thought I can set cookies with JavaScript, and read it later via custom filter (which would read the cookie from request, set it to the attribute and send it to controller.

我以为我可以用 JavaScript 设置 cookie,然后通过自定义过滤器读取它(它将从请求中读取 cookie,将其设置为属性并将其发送到控制器。

Is this thought correct? Or should I set the cookie somewhere else (if so where and why?)

这个想法正确吗?或者我应该在其他地方设置 cookie(如果是这样,为什么?)

UPDATE 1:

更新1:

What I want to achieve: I have dropdown box (which is language selector) on login page that has some values (language code, e.g. "en"), and selected value needs to be set as cookie (e.g. "lang") and that "lang" cookie will be red for i18n later on the pages. I have made i18n to work, but I need to read "lang" cookie to set the selected language.

我想要实现的目标:我在登录页面上有下拉框(即语言选择器),它有一些值(语言代码,例如“en”),并且选定的值需要设置为 cookie(例如“lang”),并且“lang”cookie 稍后会在页面上为 i18n 显示为红色。我已经让 i18n 工作了,但我需要阅读“lang”cookie 来设置选定的语言。

UPDATE 2:

更新 2:

I have done what I wanted to do, but it is not exactly clean:

我已经完成了我想做的事情,但它并不完全干净:

I am setting cookie via Javascript, or jQuery to be exact, and when user selects or changes the selection in <select/>then Javascript injects language value as cookie (e.g. en):

我正在通过Javascript或jQuery设置cookie,准确地说,当用户选择或更改选择时,<select/>Javascript将语言值作为cookie注入(例如en):

HTML:

HTML:

<select name="language" id="selectLanguage" class="form-control">
   <option val="en">English</option>
</select>

JS:

JS:

var cookie = {

    set: function($this) {
        var now = new Date();
        var time = now.getTime();
        var expireTime = time + 1000*36000;
        now.setTime(expireTime);
        document.cookie = 'lang=' + $this.val() +';expires='+now.toGMTString()+';path=/';
    }

}

$('#selectLanguage').change(function(event) {
    cookie.set($(this));
});

Then I created new Filerthat I called CookieFilter.java:

然后我创建了新的Filer,我称之为CookieFilter.java

public class CookieFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        Cookie[] cookies = ((HttpServletRequest) req).getCookies();
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if(ck.getName().toString().equals("lang")){
                    req.setAttribute("languageCookie", ck.getValue());
                } else {
                    req.setAttribute("languageCookie", "en");
                };
            }
            chain.doFilter(req, res);
        }
    }

    public void init(FilterConfig config) throws ServletException {
        // TODO Auto-generated method stub
    }
    public void destroy() {
        // TODO Auto-generated method stub
    }
}

Added new filterin web.xml:

web.xml 中添加了新过滤器

<filter>
    <filter-name>CookieFilter</filter-name>
    <filter-class>
        package.path.to.CookieFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>CookieFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

And to finish everything, I got the request from CookieFilterin my controller and red the attribute I sent:

为了完成所有操作,我在控制器中收到了来自CookieFilter的请求,并将我发送的属性设为红色:

String cookie = request.getAttribute("languageCookie").toString();
model.addAttribute("languageCookie",cookie);

Now I can read attribute from modeland set it inside .JSP or do everything I want with it.

现在我可以从model.JSP 中读取属性并将其设置在里面,或者用它做我想做的一切。

That is my solution, but there must be other way ... :)

那是我的解决方案,但必须有其他方式...... :)

回答by bh5k

So, is it a requirement to use a cookie or is that just the approach that you are taking? You can very cleanly handle i18n in Spring MVC using Interceptors. I cover that here. Basically you need to register an interceptor and have that determine your browser requests.

那么,使用 cookie 是必需的还是您正在采用的方法?您可以使用拦截器在 Spring MVC 中非常干净地处理 i18n。我在这里介绍。基本上,您需要注册一个拦截器并确定您的浏览器请求。