在我的 header HTML 中,我显示了一个 UL/LI 菜单,其中一个 LI 项目的可见性取决于服务方法调用。
我试过这个:
家庭 Controller
@Controller
public class HomeController {
private static final Logger log = LogManager.getLogger(HomeController.class);
@Autowired
private EtdService etdService;
@GetMapping("/home")
public String home(Model model) throws EtdException {
model.addAttribute("tierTemplate", etdService.getTierTemplate());
// Also tried this explicitly
model.addAttribute("etdService", etdService);
return "home";
}
}
服务接口(interface)(EtdService)
public interface EtdService {
boolean isChangeUserAllowed();
}
服务实现 (EtdServiceImpl)
@Component
public class EtdServiceImpl implements EtdService {
@Override
public boolean isChangeUserAllowed() {
System.out.println("Got here");
return false;
}
}
HTML:
<li th:if="${@etdService.isChangeUserAllowed()}" class="nav-item dropdown" id="changeUserPanel" role="presentation">
<!-- ... Definition of this LI -- note can't put a new DIV in a UL list ... -->
</li>
错误:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'etdService' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:772) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
最佳答案
除了bphilipnyc的回答(将直接值设置到模型中),
model.addAttribute("isChangeUserAllowed", etdService.isChangeUserAllowed());
如果您需要全局化通用模型属性而不是每次都重新添加,一个解决方案是一个带有@ModelAttribute
的@ControllerAdvice
类,例如
/**
* This class is used to globalize common Model Attributes without re-adding every time
* The approach is to mark it as @ControllerAdvice to make it apply to every Controller method,
* and implement a @ModelAttribute Model-Adder to append to the model on every Controller method.
*/
// Makes the methods of this class apply to all Controller Request methods
@ControllerAdvice
public class GlobalController {
@Autowired
MyService myService;
@ModelAttribute // A Model Attribute Adder method
public void setGlobalModelAttributes(HttpServletRequest request, Model model) {
model.addAttribute("isChangeUserAllowed", myService.isChangeUserAllowed());
model.addAttribute("currentUserFullName", myService.getCurrentUserFullName());
}
}
更多例子
https://stackoverflow.com/a/33879102/1005607
https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation
关于Spring Thymeleaf - 用于显示 HTML 项目的调用服务方法 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783825/