• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

使用 Servlet、Hibernate、MySQL 和 Thymeleaf 开发CRUD WEB应用程序

武飞扬头像
allway2
帮助1

  在本教程中,您将学习使用 Servlet、Hibernate、MySQL 和 Thymeleaf 开发CRUD WEB应用程序。

学新通

pom.xml

  1.  
    <?xml version="1.0" encoding="UTF-8"?>
  2.  
    <project xmlns="http://maven.apache.org/POM/4.0.0"
  3.  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.  
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.  
     
  6.  
    <modelVersion>4.0.0</modelVersion>
  7.  
    <groupId>tigratius</groupId>
  8.  
    <artifactId>Servlet-Thymeleaf-Hibernate-Crud</artifactId>
  9.  
    <version>1.0</version>
  10.  
    <packaging>war</packaging>
  11.  
     
  12.  
    <properties>
  13.  
    <project.build.sourceEncoding>US-ASCII</project.build.sourceEncoding>
  14.  
    <maven.compiler.source>1.8</maven.compiler.source>
  15.  
    <maven.compiler.target>1.8</maven.compiler.target>
  16.  
    </properties>
  17.  
     
  18.  
    <build>
  19.  
    <resources>
  20.  
    <resource>
  21.  
    <directory>src/main/resources</directory>
  22.  
    </resource>
  23.  
    <resource>
  24.  
    <directory>src/main/java</directory>
  25.  
    <includes>
  26.  
    <include>**/*.properties</include>
  27.  
    <include>**/*.xml</include>
  28.  
    <include>**/*.html</include>
  29.  
    </includes>
  30.  
    </resource>
  31.  
    </resources>
  32.  
     
  33.  
    <plugins>
  34.  
    <plugin>
  35.  
    <groupId>org.apache.maven.plugins</groupId>
  36.  
    <artifactId>maven-dependency-plugin</artifactId>
  37.  
    <version>3.0.1</version>
  38.  
    <executions>
  39.  
    <execution>
  40.  
    <phase>package</phase>
  41.  
    <goals>
  42.  
    <goal>copy</goal>
  43.  
    </goals>
  44.  
    <configuration>
  45.  
    <artifactItems>
  46.  
    <artifactItem>
  47.  
    <groupId>com.github.jsimone</groupId>
  48.  
    <artifactId>webapp-runner</artifactId>
  49.  
    <version>9.0.24.0</version>
  50.  
    <destFileName>webapp-runner.jar</destFileName>
  51.  
    </artifactItem>
  52.  
    </artifactItems>
  53.  
    </configuration>
  54.  
    </execution>
  55.  
    </executions>
  56.  
    </plugin>
  57.  
    <plugin>
  58.  
    <groupId>org.apache.maven.plugins</groupId>
  59.  
    <artifactId>maven-compiler-plugin</artifactId>
  60.  
    <version>3.8.0</version>
  61.  
    <configuration>
  62.  
    <source>${maven.compiler.source}</source>
  63.  
    <target>${maven.compiler.target}</target>
  64.  
    <encoding>${project.build.sourceEncoding}</encoding>
  65.  
    </configuration>
  66.  
    </plugin>
  67.  
    <plugin>
  68.  
    <groupId>org.apache.maven.plugins</groupId>
  69.  
    <artifactId>maven-resources-plugin</artifactId>
  70.  
    <version>3.1.0</version>
  71.  
    <configuration>
  72.  
    <encoding>${project.build.sourceEncoding}</encoding>
  73.  
    </configuration>
  74.  
    </plugin>
  75.  
    <plugin>
  76.  
    <groupId>org.apache.maven.plugins</groupId>
  77.  
    <artifactId>maven-war-plugin</artifactId>
  78.  
    <version>3.2.2</version>
  79.  
    <configuration>
  80.  
    <failOnMissingWebXml>false</failOnMissingWebXml>
  81.  
    </configuration>
  82.  
    </plugin>
  83.  
    <plugin>
  84.  
    <groupId>org.apache.tomcat.maven</groupId>
  85.  
    <artifactId>tomcat7-maven-plugin</artifactId>
  86.  
    <version>2.2</version>
  87.  
    </plugin>
  88.  
     
  89.  
    </plugins>
  90.  
     
  91.  
    </build>
  92.  
     
  93.  
    <dependencies>
  94.  
    <dependency>
  95.  
    <groupId>org.thymeleaf</groupId>
  96.  
    <artifactId>thymeleaf</artifactId>
  97.  
    <version>3.0.15.RELEASE</version>
  98.  
    </dependency>
  99.  
    <dependency>
  100.  
    <groupId>javax.servlet</groupId>
  101.  
    <artifactId>javax.servlet-api</artifactId>
  102.  
    <version>4.0.1</version>
  103.  
    </dependency>
  104.  
    <dependency>
  105.  
    <groupId>org.slf4j</groupId>
  106.  
    <artifactId>slf4j-api</artifactId>
  107.  
    <version>2.0.3</version>
  108.  
    <scope>compile</scope>
  109.  
    </dependency>
  110.  
     
  111.  
    <dependency>
  112.  
    <groupId>org.slf4j</groupId>
  113.  
    <artifactId>slf4j-log4j12</artifactId>
  114.  
    <version>2.0.3</version>
  115.  
    <scope>compile</scope>
  116.  
    </dependency>
  117.  
     
  118.  
    <dependency>
  119.  
    <groupId>log4j</groupId>
  120.  
    <artifactId>log4j</artifactId>
  121.  
    <version>1.2.17</version>
  122.  
    <scope>compile</scope>
  123.  
    <exclusions>
  124.  
    <exclusion>
  125.  
    <groupId>com.sun.jdmk</groupId>
  126.  
    <artifactId>jmxtools</artifactId>
  127.  
    </exclusion>
  128.  
    <exclusion>
  129.  
    <groupId>com.sun.jmx</groupId>
  130.  
    <artifactId>jmxri</artifactId>
  131.  
    </exclusion>
  132.  
    <exclusion>
  133.  
    <groupId>javax.jms</groupId>
  134.  
    <artifactId>jms</artifactId>
  135.  
    </exclusion>
  136.  
    </exclusions>
  137.  
    </dependency>
  138.  
    <!--https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
  139.  
    <dependency>
  140.  
    <groupId>mysql</groupId>
  141.  
    <artifactId>mysql-connector-java</artifactId>
  142.  
    <!--<version>5.1.6</version>-->
  143.  
    <version>8.0.22</version>
  144.  
    </dependency>
  145.  
    <!--https://mvnrepository.com/artifact/org.hibernate/hibernate-core-->
  146.  
    <dependency>
  147.  
    <groupId>org.hibernate</groupId>
  148.  
    <artifactId>hibernate-core</artifactId>
  149.  
    <version>5.6.12.Final</version>
  150.  
    </dependency>
  151.  
    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 добавил сломалось-->
  152.  
    <dependency>
  153.  
    <groupId>org.hibernate</groupId>
  154.  
    <artifactId>hibernate-c3p0</artifactId>
  155.  
    <version>5.6.12.Final</version>
  156.  
    </dependency>
  157.  
    <!-- https://mvnrepository.com/artifact/javax.persistence/javax.persistence-api -->
  158.  
    <dependency>
  159.  
    <groupId>javax.persistence</groupId>
  160.  
    <artifactId>javax.persistence-api</artifactId>
  161.  
    <version>2.2</version>
  162.  
    </dependency>
  163.  
     
  164.  
    </dependencies>
  165.  
     
  166.  
     
  167.  
    </project>
学新通

MySQL建表脚本

  1.  
    CREATE TABLE `users` (
  2.  
    `id` INT(10) NOT NULL AUTO_INCREMENT,
  3.  
    `first_name` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
  4.  
    `last_name` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
  5.  
    `specialty` VARCHAR(100) NOT NULL COLLATE 'utf8mb4_unicode_ci',
  6.  
    PRIMARY KEY (`id`) USING BTREE
  7.  
    )

User.java

  1.  
    package com.example.crudweb.entity;
  2.  
     
  3.  
    import javax.persistence.*;
  4.  
    import java.util.Set;
  5.  
     
  6.  
    @Entity
  7.  
    @Table(name = "users")
  8.  
    public class User {
  9.  
     
  10.  
    @Id
  11.  
    @GeneratedValue(strategy = GenerationType.IDENTITY)
  12.  
    private Long id;
  13.  
    @Column(name = "first_name")
  14.  
    private String firstName;
  15.  
    @Column(name = "last_name")
  16.  
    private String lastName;
  17.  
    private String specialty;
  18.  
     
  19.  
    public User() {
  20.  
    }
  21.  
     
  22.  
    public User(Long id, String firstName, String lastName, String specialty) {
  23.  
    this.id = id;
  24.  
    this.firstName = firstName;
  25.  
    this.lastName = lastName;
  26.  
    this.specialty = specialty;
  27.  
    }
  28.  
     
  29.  
    public Long getId() {
  30.  
    return id;
  31.  
    }
  32.  
     
  33.  
    public void setId(Long id) {
  34.  
    this.id = id;
  35.  
    }
  36.  
     
  37.  
    public String getFirstName() {
  38.  
    return firstName;
  39.  
    }
  40.  
     
  41.  
    public void setFirstName(String firstName) {
  42.  
    this.firstName = firstName;
  43.  
    }
  44.  
     
  45.  
    public String getLastName() {
  46.  
    return lastName;
  47.  
    }
  48.  
     
  49.  
    public void setLastName(String lastName) {
  50.  
    this.lastName = lastName;
  51.  
    }
  52.  
     
  53.  
    public String getSpecialty() {
  54.  
    return specialty;
  55.  
    }
  56.  
     
  57.  
    public void setSpecialty(String specialty) {
  58.  
    this.specialty = specialty;
  59.  
    }
  60.  
     
  61.  
    }
学新通

UserRepository.java

  1.  
    package com.example.crudweb.repository;
  2.  
     
  3.  
    import com.sun.xml.bind.v2.model.core.ID;
  4.  
    import com.example.crudweb.entity.User;
  5.  
    import java.util.List;
  6.  
     
  7.  
    public interface UserRepository {
  8.  
     
  9.  
    void delete(Long id);
  10.  
     
  11.  
    void update(User item);
  12.  
     
  13.  
    void add(User item);
  14.  
     
  15.  
    User getById(Long id);
  16.  
     
  17.  
    List<User> getAll();
  18.  
    }
学新通

UserRepositoryImpl.java

  1.  
    package com.example.crudweb.repository.impl;
  2.  
     
  3.  
    import com.example.crudweb.entity.User;
  4.  
    import com.example.crudweb.repository.UserRepository;
  5.  
    import org.hibernate.Session;
  6.  
    import org.hibernate.SessionFactory;
  7.  
    import org.hibernate.Transaction;
  8.  
     
  9.  
    import java.util.ArrayList;
  10.  
    import java.util.List;
  11.  
     
  12.  
    public class UserRepositoryImpl implements UserRepository {
  13.  
     
  14.  
    SessionFactory sessionFactory;
  15.  
     
  16.  
    public UserRepositoryImpl(SessionFactory sessionFactory) {
  17.  
     
  18.  
    this.sessionFactory = sessionFactory;
  19.  
    }
  20.  
     
  21.  
    public void update(User item) {
  22.  
    Session session = null;
  23.  
    Transaction tx = null;
  24.  
    try {
  25.  
    session = sessionFactory.openSession();
  26.  
    tx = session.beginTransaction();
  27.  
    session.update(item);
  28.  
    tx.commit();
  29.  
    } catch (Exception e) {
  30.  
    if (tx != null) {
  31.  
    tx.rollback();
  32.  
    }
  33.  
    e.printStackTrace();
  34.  
    } finally {
  35.  
    if (session != null && session.isOpen()) {
  36.  
    session.close();
  37.  
    }
  38.  
    }
  39.  
    }
  40.  
     
  41.  
    public void add(User item) {
  42.  
    Session session = null;
  43.  
    Transaction tx = null;
  44.  
    try {
  45.  
    session = sessionFactory.openSession();
  46.  
    tx = session.beginTransaction();
  47.  
    session.save(item);
  48.  
    tx.commit();
  49.  
    } catch (Exception e) {
  50.  
    if (tx != null) {
  51.  
    tx.rollback();
  52.  
    }
  53.  
    e.printStackTrace();
  54.  
    } finally {
  55.  
    if (session != null && session.isOpen()) {
  56.  
    session.close();
  57.  
    }
  58.  
    }
  59.  
    }
  60.  
     
  61.  
    public void delete(Long id) {
  62.  
    Session session = null;
  63.  
    Transaction tx = null;
  64.  
    try {
  65.  
    session = sessionFactory.openSession();
  66.  
    tx = session.beginTransaction();
  67.  
    User user = session.get(User.class, id);
  68.  
    session.delete(user);
  69.  
    tx.commit();
  70.  
    } catch (Exception e) {
  71.  
    if (tx != null) {
  72.  
    tx.rollback();
  73.  
    }
  74.  
    e.printStackTrace();
  75.  
    } finally {
  76.  
    if (session != null && session.isOpen()) {
  77.  
    session.close();
  78.  
    }
  79.  
    }
  80.  
    }
  81.  
     
  82.  
    public User getById(Long id) {
  83.  
    Session session = null;
  84.  
    User skill = null;
  85.  
    try {
  86.  
    session = sessionFactory.openSession();
  87.  
    skill = session.get(User.class, id);
  88.  
    } catch (Exception e) {
  89.  
    e.printStackTrace();
  90.  
    } finally {
  91.  
    if (session != null && session.isOpen()) {
  92.  
    session.close();
  93.  
    }
  94.  
    }
  95.  
    return skill;
  96.  
    }
  97.  
     
  98.  
    public List<User> getAll() {
  99.  
    Session session = null;
  100.  
    List<User> users = new ArrayList<>();
  101.  
    try {
  102.  
    session = sessionFactory.openSession();
  103.  
    users = session.createQuery("from User", User.class).list();
  104.  
    } catch (Exception e) {
  105.  
    e.printStackTrace();
  106.  
    } finally {
  107.  
    if (session != null && session.isOpen()) {
  108.  
    session.close();
  109.  
    }
  110.  
    }
  111.  
    return users;
  112.  
    }
  113.  
     
  114.  
    }
学新通

UserService.java

  1.  
    package com.example.crudweb.service;
  2.  
     
  3.  
    import com.example.crudweb.entity.User;
  4.  
     
  5.  
    import com.example.crudweb.repository.UserRepository;
  6.  
     
  7.  
    import java.util.HashSet;
  8.  
    import java.util.List;
  9.  
    import java.util.Set;
  10.  
     
  11.  
    public class UserService {
  12.  
     
  13.  
    private UserRepository userRepository;
  14.  
     
  15.  
    public UserService(UserRepository userRepository) {
  16.  
     
  17.  
    this.userRepository = userRepository;
  18.  
     
  19.  
    }
  20.  
     
  21.  
    public User getById(Long id) {
  22.  
    try {
  23.  
    return userRepository.getById(id);
  24.  
    } catch (Exception ex) {
  25.  
    ex.printStackTrace();
  26.  
    }
  27.  
     
  28.  
    return null;
  29.  
    }
  30.  
     
  31.  
    public List<User> getAll() {
  32.  
    return userRepository.getAll();
  33.  
    }
  34.  
     
  35.  
    public void delete(Long id) {
  36.  
    userRepository.delete(id);
  37.  
    }
  38.  
     
  39.  
    public void create(String firstName, String lastName, String specialty) {
  40.  
    User user = getNewUser(firstName, lastName, specialty);
  41.  
    userRepository.add(user);
  42.  
    }
  43.  
     
  44.  
    public void update(Long id, String firstName, String lastName, String specialty) {
  45.  
    User user = getNewUser(firstName, lastName, specialty);
  46.  
    user.setId(id);
  47.  
    userRepository.update(user);
  48.  
    }
  49.  
     
  50.  
    private User getNewUser(String firstName, String lastName, String specialty) {
  51.  
    User user = new User();
  52.  
    user.setFirstName(firstName);
  53.  
    user.setLastName(lastName);
  54.  
    user.setSpecialty(specialty);
  55.  
    return user;
  56.  
    }
  57.  
    }
学新通

UserController.java

  1.  
    package com.example.crudweb.controller;
  2.  
     
  3.  
    import com.example.crudweb.config.ThymeleafConfig;
  4.  
    import com.example.crudweb.entity.User;
  5.  
    import com.example.crudweb.repository.impl.UserRepositoryImpl;
  6.  
    import com.example.crudweb.service.UserService;
  7.  
    import com.example.crudweb.util.HibernateUtil;
  8.  
    import org.hibernate.SessionFactory;
  9.  
    import org.thymeleaf.TemplateEngine;
  10.  
    import org.thymeleaf.context.WebContext;
  11.  
     
  12.  
    import javax.servlet.ServletConfig;
  13.  
    import javax.servlet.ServletContext;
  14.  
    import javax.servlet.annotation.WebServlet;
  15.  
    import javax.servlet.http.HttpServlet;
  16.  
    import javax.servlet.http.HttpServletRequest;
  17.  
    import javax.servlet.http.HttpServletResponse;
  18.  
    import java.io.IOException;
  19.  
    import java.util.Arrays;
  20.  
    import java.util.List;
  21.  
    import java.util.stream.Collectors;
  22.  
     
  23.  
    @WebServlet({"/user", "/user/new", "/user/insert", "/user/edit", "/user/delete", "/user/update"})
  24.  
    public class UserController extends HttpServlet {
  25.  
     
  26.  
    private ThymeleafConfig thymeleafConfig;
  27.  
    private ServletContext servletContext;
  28.  
    private UserService userService;
  29.  
     
  30.  
    @Override
  31.  
    public void init(ServletConfig config) {
  32.  
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
  33.  
    System.out.println(" HibernateUtil.getSessionFactory() was called!");
  34.  
    servletContext = config.getServletContext();
  35.  
    thymeleafConfig = new ThymeleafConfig(servletContext);
  36.  
    userService = new UserService(new UserRepositoryImpl(sessionFactory));
  37.  
    }
  38.  
     
  39.  
    @Override
  40.  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  41.  
    doGet(req, resp);
  42.  
    }
  43.  
     
  44.  
    @Override
  45.  
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
  46.  
    throws IOException {
  47.  
     
  48.  
    String action = request.getServletPath();
  49.  
     
  50.  
    switch (action) {
  51.  
    case "/user/new":
  52.  
    showNewForm(request, response);
  53.  
    break;
  54.  
    case "/user/insert":
  55.  
    insert(request, response);
  56.  
    break;
  57.  
    case "/user/delete":
  58.  
    delete(request, response);
  59.  
    break;
  60.  
    case "/user/edit":
  61.  
    showEditForm(request, response);
  62.  
    break;
  63.  
    case "/user/update":
  64.  
    update(request, response);
  65.  
    break;
  66.  
    default:
  67.  
    list(request, response);
  68.  
    break;
  69.  
    }
  70.  
    }
  71.  
     
  72.  
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
  73.  
    Long id = Long.parseLong(request.getParameter("id"));
  74.  
    String firstName = request.getParameter("firstName");
  75.  
    String lastName = request.getParameter("lastName");
  76.  
    String specialty = request.getParameter("specialty");
  77.  
     
  78.  
    userService.update(id, firstName, lastName, specialty);
  79.  
    response.sendRedirect("/user");
  80.  
    }
  81.  
     
  82.  
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
  83.  
    Long id = Long.parseLong(request.getParameter("id"));
  84.  
    User user = userService.getById(id);
  85.  
     
  86.  
    WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
  87.  
    ctx.setVariable("user", user);
  88.  
     
  89.  
    TemplateEngine engine = thymeleafConfig.getTemplateEngine();
  90.  
    engine.process("user/edit", ctx, response.getWriter());
  91.  
    }
  92.  
     
  93.  
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
  94.  
    Long id = Long.parseLong(request.getParameter("id"));
  95.  
    userService.delete(id);
  96.  
    response.sendRedirect("/user");
  97.  
    }
  98.  
     
  99.  
    private void insert(HttpServletRequest request, HttpServletResponse response) throws IOException {
  100.  
    String firstName = request.getParameter("firstName");
  101.  
    String lastName = request.getParameter("lastName");
  102.  
    String specialty = request.getParameter("specialty");
  103.  
     
  104.  
    userService.create(firstName, lastName, specialty);
  105.  
    response.sendRedirect("/user");
  106.  
    }
  107.  
     
  108.  
    private void showNewForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
  109.  
     
  110.  
    WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
  111.  
     
  112.  
    TemplateEngine engine = thymeleafConfig.getTemplateEngine();
  113.  
    engine.process("user/new", ctx, response.getWriter());
  114.  
    }
  115.  
     
  116.  
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
  117.  
    List<User> users = userService.getAll();
  118.  
     
  119.  
    WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
  120.  
    ctx.setVariable("users", users);
  121.  
     
  122.  
    TemplateEngine engine = thymeleafConfig.getTemplateEngine();
  123.  
    engine.process("user/list", ctx, response.getWriter());
  124.  
    }
  125.  
    }
学新通

ThymeleafConfig.java

  1.  
     
  2.  
    package com.example.crudweb.config;
  3.  
     
  4.  
    import org.thymeleaf.TemplateEngine;
  5.  
    import org.thymeleaf.templatemode.TemplateMode;
  6.  
    import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
  7.  
     
  8.  
    import javax.servlet.ServletContext;
  9.  
     
  10.  
     
  11.  
    /**
  12.  
    * Thymeleaf configuration.
  13.  
    */
  14.  
     
  15.  
     
  16.  
    public class ThymeleafConfig {
  17.  
     
  18.  
    private final String prefix = "/WEB-INF/templates/";
  19.  
    private final String suffix = ".html";
  20.  
    private final Long cacheTTLMs = 3600000L;
  21.  
    private final TemplateEngine templateEngine;
  22.  
     
  23.  
    public ThymeleafConfig(final ServletContext ctx) {
  24.  
     
  25.  
    ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(ctx);
  26.  
    templateResolver.setTemplateMode(TemplateMode.HTML);
  27.  
    templateResolver.setPrefix(prefix);
  28.  
    templateResolver.setSuffix(suffix);
  29.  
    templateResolver.setCacheTTLMs(cacheTTLMs);
  30.  
    templateResolver.setCacheable(true);
  31.  
     
  32.  
    templateEngine = new TemplateEngine();
  33.  
    templateEngine.setTemplateResolver(templateResolver);
  34.  
    }
  35.  
     
  36.  
    public TemplateEngine getTemplateEngine() {
  37.  
    return templateEngine;
  38.  
    }
  39.  
    }
  40.  
     
  41.  
     
  42.  
     
学新通

HibernateUtil.java

  1.  
    package com.example.crudweb.util;
  2.  
     
  3.  
    import com.example.crudweb.entity.User;
  4.  
    import org.hibernate.SessionFactory;
  5.  
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
  6.  
    import org.hibernate.cfg.Configuration;
  7.  
    import org.hibernate.service.ServiceRegistry;
  8.  
     
  9.  
    public class HibernateUtil {
  10.  
     
  11.  
    private static SessionFactory sessionFactory = null;
  12.  
     
  13.  
    public static SessionFactory getSessionFactory() {
  14.  
     
  15.  
    if (sessionFactory != null) {
  16.  
    return sessionFactory;
  17.  
    } else {
  18.  
    try {
  19.  
    Configuration configuration = new Configuration().configure();
  20.  
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
  21.  
    .applySettings(configuration.getProperties()).build();
  22.  
    configuration.addAnnotatedClass(User.class);
  23.  
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  24.  
    } catch (Throwable ex) {
  25.  
    System.err.println("Initial SessionFactory creation failed." ex);
  26.  
    throw new ExceptionInInitializerError(ex);
  27.  
    }
  28.  
    return sessionFactory;
  29.  
    }
  30.  
    }
  31.  
    }
学新通

hibernate.cfg.xml

  1.  
    <?xml version='1.0' encoding='utf-8'?>
  2.  
    <!DOCTYPE hibernate-configuration PUBLIC
  3.  
    "-//Hibernate/Hibernate Configuration DTD//EN"
  4.  
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
    <hibernate-configuration>
  6.  
    <session-factory>
  7.  
    <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
  8.  
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/demodb?autoReconnect=true&amp;useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=Asia/Shanghai</property>
  9.  
    <property name="hibernate.connection.username">root</property>
  10.  
    <property name="hibernate.connection.password">root</property>
  11.  
     
  12.  
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  13.  
    <property name="show_sql">false</property>
  14.  
     
  15.  
    <!-- hibernate c3p0 connection pooling configuration -->
  16.  
    <property name="hibernate.c3p0.acquire_increment">1</property>
  17.  
    <property name="hibernate.c3p0.idle_test_period">60</property> <!-- seconds -->
  18.  
    <property name="hibernate.c3p0.min_size">5</property>
  19.  
    <property name="hibernate.c3p0.max_size">10</property>
  20.  
    <property name="hibernate.c3p0.max_statements">50</property>
  21.  
    <property name="hibernate.c3p0.timeout">0</property> <!-- seconds -->
  22.  
    <property name="hibernate.c3p0.acquireRetryAttempts">1</property>
  23.  
    <property name="hibernate.c3p0.acquireRetryDelay">250</property>
  24.  
     
  25.  
    <mapping class="com.tigratius.crudweb.entity.User"/>
  26.  
     
  27.  
    </session-factory>
  28.  
    </hibernate-configuration>
学新通

list.html

  1.  
    <!DOCTYPE html>
  2.  
     
  3.  
    <html xmlns:th="http://www.thymeleaf.org">
  4.  
     
  5.  
    <head>
  6.  
    <title>User List</title>
  7.  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  8.  
    <link rel="stylesheet" type="text/css" media="all" href="../../../css/style.css" th:href="@{/css/style.css}" />
  9.  
    </head>
  10.  
     
  11.  
    <body>
  12.  
     
  13.  
    <h1>User List</h1>
  14.  
     
  15.  
    <div style="margin-bottom: 20px">
  16.  
    <a class="add" th:href="@{/user/new}">Add New User</a>
  17.  
    </div>
  18.  
     
  19.  
    <table>
  20.  
    <thead>
  21.  
    <tr>
  22.  
    <th>FIRST_NAME</th>
  23.  
    <th>LAST_NAME</th>
  24.  
    <th>SPECIALTY</th>
  25.  
    <th></th>
  26.  
    <th></th>
  27.  
    </tr>
  28.  
    </thead>
  29.  
    <tbody th:remove="all-but-first">
  30.  
    <tr th:each="user : ${users}" th:class="${userStat.odd}? 'odd'">
  31.  
    <td th:text="${user.firstName}"></td>
  32.  
    <td th:text="${user.lastName}"></td>
  33.  
    <td th:text="${user.specialty}"></td>
  34.  
     
  35.  
    <td><a th:href="@{/user/edit(id=${user.id})}">edit</a></td>
  36.  
    <td><a th:href="@{/user/delete(id=${user.id})}">delete</a></td>
  37.  
    </tr>
  38.  
    </tbody>
  39.  
    </table>
  40.  
     
  41.  
    <p>
  42.  
    <a href="../home.html" th:href="@{/}">Return to home</a>
  43.  
    </p>
  44.  
     
  45.  
    </body>
  46.  
     
  47.  
    </html>
  48.  
     
学新通

new.html

  1.  
    <!DOCTYPE html>
  2.  
     
  3.  
    <html xmlns:th="http://www.thymeleaf.org">
  4.  
     
  5.  
    <head>
  6.  
    <title>User New Form</title>
  7.  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  8.  
    <link rel="stylesheet" type="text/css" media="all" href="../../../css/style.css" th:href="@{/css/style.css}"/>
  9.  
    </head>
  10.  
     
  11.  
    <body>
  12.  
     
  13.  
    <h1>Add New User</h1>
  14.  
     
  15.  
    <form action="insert" method="post">
  16.  
     
  17.  
    <table>
  18.  
    <tr>
  19.  
    <th>First_Name:</th>
  20.  
    <td>
  21.  
    <input type="text" name="firstName"
  22.  
    value=""
  23.  
    />
  24.  
    </td>
  25.  
    </tr>
  26.  
    <tr>
  27.  
    <th>Last_Name:</th>
  28.  
    <td>
  29.  
    <input type="text" name="lastName"
  30.  
    value=""
  31.  
    />
  32.  
    </td>
  33.  
    </tr>
  34.  
    <tr>
  35.  
    <th>Specialty:</th>
  36.  
    <td>
  37.  
    <input type="text" name="specialty"
  38.  
    value=""
  39.  
    />
  40.  
    </td>
  41.  
    </tr>
  42.  
     
  43.  
     
  44.  
    </table>
  45.  
     
  46.  
    <input type="submit" value="Save"/>
  47.  
    </form>
  48.  
     
  49.  
    </body>
  50.  
     
  51.  
    </html>
学新通

edit.html

  1.  
    <!DOCTYPE html>
  2.  
     
  3.  
    <html xmlns:th="http://www.thymeleaf.org">
  4.  
     
  5.  
    <head>
  6.  
    <title>User Edit Form</title>
  7.  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  8.  
    <link rel="stylesheet" type="text/css" media="all" href="../../../css/style.css" th:href="@{/css/style.css}"/>
  9.  
    </head>
  10.  
     
  11.  
    <body>
  12.  
     
  13.  
    <h1>Edit User</h1>
  14.  
     
  15.  
    <form action="update" method="post">
  16.  
     
  17.  
    <input type="hidden" name="id" th:value="${user.id}"/>
  18.  
     
  19.  
    <table>
  20.  
    <tr>
  21.  
    <th>First_Name:</th>
  22.  
    <td>
  23.  
    <input type="text" name="firstName"
  24.  
    th:value="${user.firstName}"
  25.  
    />
  26.  
    </td>
  27.  
    </tr>
  28.  
    <tr>
  29.  
    <th>Last_Name:</th>
  30.  
    <td>
  31.  
    <input type="text" name="lastName"
  32.  
    th:value="${user.lastName}"
  33.  
    />
  34.  
    </td>
  35.  
    </tr>
  36.  
    <tr>
  37.  
    <th>Specialty:</th>
  38.  
    <td>
  39.  
    <input type="text" name="specialty"
  40.  
    th:value="${user.specialty}"
  41.  
    />
  42.  
    </td>
  43.  
    </tr>
  44.  
     
  45.  
     
  46.  
    </table>
  47.  
    <input type="submit" value="Save"/>
  48.  
    </form>
  49.  
     
  50.  
    </body>
  51.  
     
  52.  
    </html>
学新通

下载:https://github.com/allwaysoft/Servlet-Thymeleaf-Hibernate-Crud

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgkigah
系列文章
更多 icon
同类精品
更多 icon
继续加载