创建一个JSF项目,推荐用Tomcat做服务器
导入依赖项
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>jsf-hibernate-01</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.0-alpha1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>8.0.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>
创建 faces-config.xml,配置SpringBeanFacesELResolver在faces,进行JSF与Spring框架集成
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" 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
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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 http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
创建实体类
package org.example.pojo;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* @Author: HAPPY
* @Project_name: JSF
* @Package_name: org.example.pojo
* @Date: 2021/9/27 21:53
*/
@Entity(name = "student")
@ManagedBean(name = "student")
@RequestScoped
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
创建service
package org.example.service;
import org.example.pojo.Student;
import java.util.List;
/**
* @Author: HAPPY
* @Project_name: JSF
* @Package_name: org.example.service
* @Date: 2021/9/28 20:28
*/
public interface StudentService {
boolean insertStudent(Student student);
Student selectStudentById(Integer id);
List<Student> selectAllStudents();
boolean deleteStudentById();
}
实现service
package org.example.service.impl;
import org.example.dao.StudentDAO;
import org.example.dao.impl.StudentDAOImpl;
import org.example.pojo.Student;
import org.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.util.List;
/**
* @Author: HAPPY
* @Project_name: JSF
* @Package_name: org.example.service.impl
* @Date: 2021/9/28 20:37
*/
@Service("studentService")
@ManagedBean(name = "studentService")
@SessionScoped
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDAO;
@Override
public boolean insertStudent(Student student) {
System.out.println(student);
return studentDAO.insertStudent(student);
}
@Override
public Student selectStudentById(Integer id) {
return studentDAO.selectStudentById(id);
}
@Override
@Transactional
public List<Student> selectAllStudents() {
return studentDAO.selectAllStudents();
}
@Override
public boolean deleteStudentById() {
return studentDAO.deleteStudentById();
}
public StudentDAO getStudentDAO() {
return studentDAO;
}
public void setStudentDAO(StudentDAO studentDAO) {
this.studentDAO = studentDAO;
}
}
创建dao
package org.example.dao;
import org.example.pojo.Student;
import java.util.List;
/**
* @Author: HAPPY
* @Project_name: JSF
* @Package_name: org.example.dao
* @Date: 2021/9/28 20:28
*/
public interface StudentDAO {
boolean insertStudent(Student student);
Student selectStudentById(Integer id);
List<Student> selectAllStudents();
boolean deleteStudentById();
}
实现dao
package org.example.dao.impl;
import org.example.dao.StudentDAO;
import org.example.pojo.Student;
import org.example.util.SessionFactoryUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @Author: HAPPY
* @Project_name: JSF
* @Package_name: org.example.dao.impl
* @Date: 2021/9/28 20:38
*/
@Repository
public class StudentDAOImpl implements StudentDAO {
@Override
public boolean insertStudent(Student student) {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
try {
session.save(student);
transaction.commit();
return true;
} catch (Exception a) {
return false;
}
}
@Override
public Student selectStudentById(Integer id) {
return null;
}
@Override
public List<Student> selectAllStudents() {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Query query = session.createQuery("FROM org.example.pojo.Student");
return query.list();
}
@Override
public boolean deleteStudentById() {
return false;
}
}
创建工具类
package org.example.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* 获取SessionFactory 的工具类
*/
public class SessionFactoryUtil {
static SessionFactory sessionFactory;
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
创建spring 配置文件, applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--加载驱动文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--数据库连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
</bean>
<!-- service 对象, 用的component-scan 好像没有用,报空指针 -->
<bean id="studentService" class="org.example.service.impl.StudentServiceImpl">
<property name="studentDAO" ref="studentDAOImpl"/>
</bean>
<!-- hibernate用来创建sessionFactory -->
<bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 受管bean -->
<property name="annotatedClasses">
<list>
<value>org.example.pojo.Student</value>
</list>
</property>
<!-- 配置属性 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- 事务注解扫描 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
</bean>
<!-- 组件扫描器,用于创建service对象,好像没用-->
<context:component-scan base-package="org.example"/>
<!--注解驱动-->
<mvc:annotation-driven/>
</beans>
配置文件 jdbc.properties
jdbc_url=jdbc:mysql://localhost:3306/esms
jdbc_username=root
jdbc_password=123456
创建页面 index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>JSF Spring Hibernate Integration</title>
<style type="text/css">
.tg {
border-collapse: collapse;
border-spacing: 0;
border-color: #ccc;
}
.tg td {
font-family: Arial, sans-serif;
font-size: 14px;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
border-color: #ccc;
color: #333;
background-color: #fff;
}
.tg th {
font-family: Arial, sans-serif;
font-size: 14px;
font-weight: normal;
padding: 10px 5px;
border-style: solid;
border-width: 1px;
overflow: hidden;
word-break: normal;
border-color: #ccc;
color: #333;
background-color: #f0f0f0;
}
.tg .tg-4eph {
background-color: #f9f9f9
}
</style>
</h:head>
<h:body>
<h1>Add a Person</h1>
<h:form>
<table>
<tr>
<td><label>Name</label></td>
<td><h:inputText id="name" value="#{student.name}"/></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><h:inputText id="address" value="#{student.address}"/></td>
</tr>
<tr>
<td colspan="2">
<h:commandButton action="#{studentService.insertStudent(student)}" value="添加学生" />
</td>
</tr>
</table>
</h:form>
<br/>
<h3>Persons List</h3>
<c:if test="${!empty studentService.selectAllStudents()}">
<table class="tg">
<tr>
<th width="80">Student ID</th>
<th width="120">Student Name</th>
<th width="120">Student Address</th>
</tr>
<ui:repeat value="${studentService.selectAllStudents()}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.address}</td>
</tr>
</ui:repeat>
</table>
</c:if>
</h:body>
</html>
建表
create table student
(
id int auto_increment,
name varchar(50) null,
address varchar(50) null,
constraint student_pk
primary key (id)
);