【问题标题】:Two different model attributes, with the same name, each passed to a different view, but in the same controller两个不同的模型属性,具有相同的名称,每个都传递给不同的视图,但在同一个控制器中
【发布时间】:2017-07-10 00:29:42
【问题描述】:

基本上,我有一个控制器和两种不同的帐户类型。我想将视图显示为“adminDashboard.jsp”或“userDashboard.jsp”,具体取决于用户的类型,并将名为“user”的模型属性传递给这些视图中的每一个,但不同的对象具有不同的类,具体取决于在哪个视图上显示。目前,即使它隐藏在开关盒中,我的代码也只会读取先发生的那个,而不是属于“激活”开关的那个。

家庭控制器:

@Controller
@RequestMapping(value = "/dashboard")
public ModelAndView showDashboard(String userGroup) {
  switch(userGroup) {
    case "admin": {
      ModelAndView("adminDashboard", "user", adminObject);
    }
    case "user": {
      ModelAndView("userDashboard", "user", userObject);
    }
  }
}

adminDashboard.jsp

<html>
<head>
  ...
</head>
<body>
  ${user.adminId} <!-- reads this correctly -->
  ${user.userId} <!-- does not read this, which is good. -->
</body>
</html>

userDashboard.jsp

<html>
<head>
  ...
</head>
<body>
  ${user.adminId} <!-- reads this, which it should not -->
  ${user.userId} <!-- does not read this, but it should -->
</body>
</html>

有人可以向我解释为什么 admin 用户模型属性仍在传递,即使从技术上讲,代码甚至不应该进入那个 switch case?我想要做的甚至可能吗?如果有,有什么例子?

【问题讨论】:

  • 假设你的 switch case 有问题。它不包含break;你可以用if else块尝试相同的逻辑。
  • 我已经按照您的建议进行了尝试,尽管它返回了 userDashboard 视图,但当我使用 ${user} EL 标记时它使用了管理员用户模型属性。很麻烦,因为模型属性只在与 OTHER 视图关联的 ModelAndView 对象中声明。

标签: java jsp spring-mvc tomcat el


【解决方案1】:

不要为user profile级别维护两个jsp页面,建议你看看JSTL If Else条件的使用

 <c:if test="${user.profileLevel=='admin'}">
    <c:out value="${user.adminId}" />
    </c:if>

如果你想在子用户级别上进行渲染,你可以使用

<c:choose>
    <c:when test="${user.profile=='partner'}">
      Partners with Us.
    </c:when>    
    <c:otherwise>
      Other Level.
    </c:otherwise>
</c:choose>

可以嵌套在条件中。

在这种情况下,您的 jsp 将负责被访问的参数。对我来说,这听起来是一种更好的方法,因为首先不应该在用户级别页面中访问 adminId。

【讨论】:

  • 不幸的是,我的例子就是这样,这个解决方案对我没有帮助。我需要按照我在 OP 中概述的方式进行操作的原因大约有 10 多个,其中大部分完全不在我的掌控之中。如果我提出的问题有解决方案,请告诉我。
【解决方案2】:

如下更改您的控制器:

@Controller
@RequestMapping(value = "/dashboard")
public ModelAndView showDashboard(String userGroup) {
  switch(userGroup) {
    case "admin": {
      ModelAndView("adminDashboard", "adminUser", adminObject);
      break;
    }
    case "user": {
      ModelAndView("userDashboard", "user", userObject);
      break;
    }
  }
}

并在您的 adminDashboard.jsp 中按如下方式访问它:

    <html>
    <head>
      ...
    </head>
    <body>
      ${adminUser.adminId} <!-- reads like this -->
    </body>
    </html>

【讨论】:

  • 这不满足问题的条件。我不需要 adminUser 和用户,而只是用户。我的菜单导航 1000000% 依赖于此,这不取决于我。如果有适合我要求的解决方案,请告诉我。
猜你喜欢
  • 2014-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
相关资源
最近更新 更多