gpt4 book ai didi

java - 寻找一种简洁的方法通过 Controller 的 Model 对象向 Spring MVC 中的每个页面添加标题信息

转载 作者:行者123 更新时间:2023-12-01 15:47:38 25 4
gpt4 key购买 nike

我有一个<TITLE>我的 JSP 中的标记是使用请求处理程序中的值设置的:

<title><c:out value="${title}"/></title>

我创建了一个方法来执行此操作,以避免使用这些额外信息给 Controller 逻辑添加困惑。

但我仍然对代码中的外观不满意(我的实际 Controller 方法比此处提供的示例长得多,因此我试图尽可能地最小化和简化它们)。

是否有更简洁的方法从 Controller 中添加此信息? (它不能添加到 JSP 中)。

@RequestMapping(value = "/foo", method = RequestMethod.GET)
public final String foo(final ModelMap model) {
addTitle(model, "Desolation Row is the title of this page");
return "foo";
}

@RequestMapping(value = "/goo", method = RequestMethod.GET)
public final String goo(final ModelMap model) {
addTitle(model, "Leopardskin Pillbox Hat is the title of this page");
return "goo";
}

public ModelMap addTitle(ModelMap model, String title) {
model.addAttribute("title", title);
return model;
}

最佳答案

如果您想从 Controller 中提取出 addTitle 方法,也许您可​​以将它们放入 HandlerInterceptor 实现中?

可能是这样的:

public class TitleInterceptor implements HandlerInterceptor {
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
String requestUrl = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String title = "";
if ("/url1.htm".equals(requestUrl)) {
title = "Title 1";
} else if ("/url2.htm".equals(requestUrl)) {
title = "Title 2";
}
modelAndView.getModel().put("title", title)
}

}

如果您需要一些处理来确定标题,也许拦截器可用的 modelAndView 将包含有助于确定给定 url 的标题的数据。如果不需要任何处理,只需简单地将标题映射到 url,您甚至可以在 applicationContext.xml 中的 bean 配置期间将其实现为可配置 Map

我发现对实现 HandlerInterceptor 有帮助的一些链接可以在这里找到: http://whitesboard.blogspot.com/2009/10/handlerinterceptors-in-spring-web-mvc.htmlhttp://static.springsource.org/spring/docs/2.0.x/api/org/springframework/web/servlet/HandlerInterceptor.html

关于java - 寻找一种简洁的方法通过 Controller 的 Model 对象向 Spring MVC 中的每个页面添加标题信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6837102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com