我已经使用SpringRoo生成了一些页面,我需要在应用程序主页上显示数据库中的一些项目。所以我如何将模型和数据传递到主页,Roo添加了以下几行,我已经评论掉了
<mvc:view-controller path="/" view-name="index"/>
我用Roo创建了一个新的控制器,名为Home,就像这个
@RequestMapping("/")
@Controller
public class Home {
@RequestMapping(method = RequestMethod.GET)
public String index() {
return "index";
}
}
现在,所有页面都显示Index视图,甚至/login。
致以问候和感谢。
试试这个:
不要映射到"/"url,它将匹配所有请求(如您所见)。编辑:根据评论,上一句突出显示的部分是错误的。解决方法似乎仍然有效。
- 在web.xml文件中,配置一个欢迎文件(可能是index.html)
- 使用索引文件名,即索引控制器的
@RequestMapping
(可能是"/index.html")
另一种选择,如果这还不够
- 在web.xml文件中,配置一个JSP欢迎文件(可能是index.JSP)
- 在JSP欢迎文件中,将请求转发到一个已知的URL(可能是/blammy)
- 将索引控制器映射到已知的URL(例如
@RequestMapping("/blammy")
)
要传递模型数据,请将model添加到方法签名中。
对于路由问题,请尝试在方法级别映射请求,并确保其他视图有匹配的映射。即:"/login"
@Controller
public class Home {
@RequestMapping(value="/", method = RequestMethod.GET)
public String index(Model model) {
String myData = "I want access to this";
model.addAttribute("myData", myData);
return "index";
}
}
由于我发现自己对上面的混杂评论感到困惑,我想我会写下我是如何做到这一点的。
-
在webmvc-config.xml 中注释掉
<mvc:view-controller path="/" view-name="index"/>
-
创建了一个新控制器。我用roo为我创建了它。然而,我意识到它添加了一些与控制器相关的JSP。由于我不需要它们,所以我删除了JSP。控制器样本低于
@RequestMapping("/") @Controller public class IndexController { @RequestMapping public String index() { return "redirect:/asas?page=1&size=10"; } }
您几乎可以调用任何现有的控制器方法。在我的情况下,我希望它显示从数据库中检索到的某些项目。
在我的研究中,通过添加@RequestMapping("/")
,它并不会强制每个请求都降落在该控制器中。只有当您命中应用程序的基本URI时才会发生这种情况。
For me的工作方式是将请求映射定义为默认的welcome-file
路径:
@Controller
public class Home {
@RequestMapping("/index.html")
public String index() {
return "index";
}
}
您可以采用这种方法。
在web.xml中,添加以下代码并将index_home.jsp
放到webapp目录中。
<welcome-file-list>
<welcome-file>index_home.jsp</welcome-file>
</welcome-file-list>
在index_home.jsp
中,添加以下代码:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:redirect url="/redirect"/>
</body>
</html>
最后在Controller
中,您可以添加以下代码:
@Controller
public class HomePageController {
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void runMethod(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException {
// add your logic to show some items from database on the homepage of the application
}
}