- Dependencies
除了标准的Web Starter依赖项之外,你还需要包括标记为提供的tomcat嵌入式jasper(感谢@Fencer在此处发表评论)。否则,由于JSF取决于JSP处理器,你将在应用程序启动时遇到异常(另请参见答案末尾的第一个链接)。
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
- Servlet registration
注册JSF Servlet并将其配置为在启动时加载(不需要web.xml)。如果使用JSF 2.2,则最好是*.xhtml至少在使用facelet时使用映射:
@Beanpublic ServletRegistrationBean servletRegistrationBean() { ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean( new FacesServlet(), "*.xhtml"); servletRegistrationBean.setLoadonStartup(1); return servletRegistrationBean;}使你的配置类实现,ServletContextAware以便你可以设置init参数。在这里,你必须强制JSF加载配置:
@Overridepublic void setServletContext(ServletContext servletContext) { servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString()); servletContext.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", "true"); //More parameters...}- EL integration
在faces-config.xml中声明EL解析器。这将成为视图文件与托管Bean属性和方法之间的粘合剂:
<?xml version="1.0" encoding="UTF-8"?><faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2"> <application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application></faces-config>
- The View Scope
编写一个自定义的Spring范围来模拟JSF视图范围(请注意,你的bean将由Spring而不是JSF管理)。它看起来应该像这样:
public class ViewScope implements Scope { @Override public Object get(String name, ObjectFactory<?> objectFactory) { Map<String, Object> viewMap = FacesContext.getCurrentInstance() .getViewRoot().getViewMap(); if (viewMap.containsKey(name)) { return viewMap.get(name); } else { Object object = objectFactory.getObject(); viewMap.put(name, object); return object; } } @Override public String getConversationId() { return null; } @Override public void registerDestructionCallback(String name, Runnable callback) { } @Override public Object remove(String name) { return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name); } @Override public Object resolveContextualObject(String arg0) { return null; }}并将其注册到你的配置类中:
@Beanpublic static CustomScopeConfigurer viewScope() { CustomScopeConfigurer configurer = new CustomScopeConfigurer(); configurer.setScopes( new ImmutableMap.Builder<String, Object>().put("view", new ViewScope()).build()); return configurer;}- Ready to go!
现在,你可以按照以下方式声明托管bean。记住要使用@Autowired(最好在构造函数中)代替@ManagedProperty,因为你正在处理Spring Beans。
@Component@Scope("view")public class MyBean { //Ready to go!}Still pending to achieve
我无法在Spring Boot上下文中使用JSF特定的注释。所以@FacesValidator,@FacesConverter,@FacesComponent,等不能使用。仍然有机会在faces-config.xml中声明它们(参见xsd),这是一种老式的方法。



