如何在viewpreparer类中获取HttpServletRequest

时间:2013-04-03 05:41:10

标签: spring spring-mvc tiles

使用Spring MVC框架并使用view preparer加载菜单。我需要在viewpreparer类中获取请求对象。为此,我在view preparer中使用以下代码

@Service
public class MenuViewPreparer implements ViewPreparer {


   HttpServletRequest request = ServletActionContext.getRequest();
  // HttpSession session = request.getSession();
 public void execute(TilesRequestContext tilesContext,
         AttributeContext attributeContext) throws PreparerException {

         // MenuList fetches the list of all the main menus by calling the getMenuList() method present in MenuServiceDAOImpl
         // which is of type MenuDTO
         String user=null;
         System.out.println("Menu :"+request.hashCode());
         UserDTO userDTO = UserName.getUserName(request);
         user=userDTO.getUserId();
}
}

我需要execute方法中的请求对象。但所有我都在null中获取请求对象。所以得到一个例外。谁能告诉我如何获得它?

提前感谢。

3 个答案:

答案 0 :(得分:1)

如果您将图块与spring security一起使用,请尝试以下代码:

    Object reqObj = tilesRequestContext.getRequestObjects()[0];
    ServletRequest reqq;
    if (SecurityContextHolderAwareRequestWrapper.class.isInstance(reqObj)) {
        SecurityContextHolderAwareRequestWrapper schaqw = (SecurityContextHolderAwareRequestWrapper) reqObj;
        reqq = schaqw.getRequest();
    } else if(PageContext.class.isInstance(reqObj)){
        PageContext context = (PageContext) reqObj;
        reqq = context.getRequest();
    } else {
        throw new ImpossibleException("tilesRequestContext.getRequestObjects[0] has unknow type: "+ reqObj.getClass().getName());
    }

这项工作对我而言。

P.S。 ImpossibleException是我不可能的情况下的自定义异常。我不知道它真的不可能,但无论如何都是异常所有需要的信息。而这种变体肯定比其他变种更好。

答案 1 :(得分:0)

你试过吗?

public class MenuPreparer implements ViewPreparer {


public void execute(TilesRequestContext tilesContext, 
                  AttributeContext attributeContext) throws PreparerException {

    HttpServletRequest request = (HttpServletRequest) tilesContext.getRequest();
}

答案 2 :(得分:0)

由于tilesContext.getRequest()似乎已被弃用,我不得不寻找替代品。以下对我有用:

Object[] requests = (Object[]) tilesContext.getRequestObjects();
PageContext pageContext = null;
HttpServletRequest request = null;
if(requests.length > 0){
     pageContext = (PageContext) requests[0];
     request = (HttpServletRequest) pageContext.getRequest();
}

让我知道它是否有效。