如何在Spring Boot 2.5+中集成JSF(Mojarra),不使用JoinFaces
Mojarra 与 Spring Boot 2.5+ 原生集成方案
以下是无需第三方封装工具的手动集成步骤,可直接复用原有XML配置逻辑:
1. 核心依赖引入
首先在pom.xml中添加Mojarra及相关依赖,注意Spring Boot 2.5基于javax.servlet API,需使用JSF 2.3版本的Mojarra,不要选用适配Jakarta EE的3.x+版本:
<dependencies> <!-- Spring Boot Web Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Mojarra JSF 2.3 --> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.3.17</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.3.17</version> </dependency> <!-- JSP API 适配Tomcat --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies>
2. 替换web.xml配置
原有web.xml中的配置可通过Spring Boot配置类直接注册,无需保留web.xml文件:
- 注册FacesServlet:通过
ServletRegistrationBean实现和原有web.xml完全一致的映射规则
@Configuration public class JsfConfig { @Bean public ServletRegistrationBean<FacesServlet> facesServletRegistration() { ServletRegistrationBean<FacesServlet> registration = new ServletRegistrationBean<>(new FacesServlet(), "*.xhtml"); registration.setLoadOnStartup(1); return registration; } // 注入原有web.xml中的上下文参数 @Bean public ServletContextInitializer servletContextInitializer() { return servletContext -> { // JSF项目阶段配置 servletContext.setInitParameter("javax.faces.PROJECT_STAGE", "Development"); // Facelets页面刷新间隔 servletContext.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1"); // 其余原有web.xml的context-param都可在此处添加 }; } }
3. faces-config.xml兼容处理
无需改造原有faces-config.xml,直接将文件移动到src/main/resources/META-INF路径下,Mojarra启动时会自动扫描加载该配置。
如果希望逐步替换XML配置,可将原有XML中声明的托管Bean改为使用@Named+@RequestScoped/@ViewScoped等注解实现,效果完全一致。
4. 打通Spring与JSF的EL表达式上下文
要在JSF页面中访问Spring容器管理的Bean,只需在原有faces-config.xml中添加EL解析器配置即可:
<application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver> </application>
5. 资源路径与打包配置
- 若打可执行JAR包运行:将所有.xhtml页面、静态资源放到
src/main/resources/META-INF/resources路径下,内嵌Tomcat会自动识别该目录为web资源根目录 - 若打WAR包部署:页面资源可保留原有webapp目录结构,启动类继承
SpringBootServletInitializer即可适配外部容器部署
内容的提问来源于stack exchange,提问作者csyperski
相关产品推荐
相关产品推荐

