问题描述
我想创建一个在我的任何spring mvc控制器操作之前执行的过滤器。
我想检查是否存在cookie,然后存储只有当前请求的某个对象。
然后我需要在我的控制器操作中引用此对象(如果存在)。 / p>
有关如何执行此操作的建议?
创建过滤器只需创建一个实现javax.servlet.Filter的类,在你的情况下可以是这样的
public class CookieFilter实现Filter {
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)抛出IOException,ServletException {
HttpServletRequest request =(HttpServletRequest)req;
Cookie [] cookies = request.getCookies();
if(cookies!= null){
for(Cookie ck:cookies){
if(nameOfMyCookie.equals(ck.getName())){
//读取cookie等等
// .... ....
//在当前请求中设置一个对象
request.setAttribute(myCoolObject,myObject)
}
}
chain.doFilter(request,res);
}
public void init(FilterConfig config)抛出ServletException {
//加载过滤器时调用的一些初始化代码
}
public void destroy(){
//在卸载过滤器时执行
}
}
然后在web.xml中声明过滤器
< filter>
< filter-name> CookieFilter< / filter-name>
< filter-class>
my.package.CookieFilter
< / filter-class>
< / filter>
< filter-mapping>
< filter-name> CookieFilter< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>
此时您的控制器只需使用request.getAttribute检查请求中是否存在attibute( myCoolObject)
I want to create a filter that will execute before any of my spring mvc controller actions.
I want to check for the existence of a cookie, and then store an object somewhere for the current request only.
I then need to reference this object (if it exists) from within my controller action.
Suggestions on how to do this?
to create the filter just make a class that implements javax.servlet.Filter, in your case can be something like this
public class CookieFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
Cookie[] cookies = request.getCookies();
if (cookies != null){
for (Cookie ck : cookies) {
if ("nameOfMyCookie".equals(ck.getName())) {
// read the cookie etc, etc
// ....
// set an object in the current request
request.setAttribute("myCoolObject", myObject)
}
}
chain.doFilter(request, res);
}
public void init(FilterConfig config) throws ServletException {
// some initialization code called when the filter is loaded
}
public void destroy() {
// executed when the filter is unloaded
}
}
then declare the filter in your web.xml
<filter>
<filter-name>CookieFilter</filter-name>
<filter-class>
my.package.CookieFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>CookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
at this point in your controller just check if the attibute exists in the request using request.getAttribute("myCoolObject")
这篇关于想要创建一个过滤器来检查cookie,然后从控制器保存对象和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!