带有Maven客户表单Web应用程序的Spring MVC无法正常工作

Posted

技术标签:

【中文标题】带有Maven客户表单Web应用程序的Spring MVC无法正常工作【英文标题】:Spring MVC with maven Customer Form web application not working 【发布时间】:2019-12-15 02:00:51 【问题描述】:

我是 Spring MVC 的新手,我正在尝试编写一个简单的 Web 应用程序来开始使用 Spring。我不知道应用程序没有在哪里执行。导入这个 Maven 项目代码并在你的 IDE 中运行。请在代码中帮助我运行项目。

这是我所拥有的:

web.xml:

<?xml version="1.0" encoding="UTF-8" ?> 
  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-crm-rest</display-name> 
  <absolute-ordering /> 
  <welcome-file-list>
  <welcome-file>list-customers.jsp</welcome-file> 
  <welcome-file>index.html</welcome-file> 
  </welcome-file-list>
  <servlet>
  <servlet-name>dispatcher</servlet-name> 
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
  <init-param>
  <param-name>contextConfigLocation</param-name> 
  <param-value>/WEB-INF/spring-crm-rest-demo-servlet.xml</param-value> 
  </init-param>
  <load-on-startup>1</load-on-startup> 
  </servlet>
  <servlet-mapping>
  <servlet-name>dispatcher</servlet-name> 
  <url-pattern>/</url-pattern> 
  </servlet-mapping>
  </web-app>

main servlet.xml:spring-crm-rest-demo-servlet.xml

        <?xml version="1.0" encoding="UTF-8" ?>  
      <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:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx.xsd">

      <!--  Add support for component scanning --> 
      <context:component-scan base-package="com.luv2code.springdemo" />

      <!--  Add support for conversion, formatting and validation support --> 
      <mvc:annotation-driven /> 

      <!--  Define Spring MVC view resolver --> 
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/view/jsp" /> 
      <property name="suffix" value=".jsp" /> 
      </bean>

      <!--  Step 1: Define Database DataSource / connection pool --> 
      <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
      <property name="driverClass" value="com.mysql.jdbc.Driver" /> 
      <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/demo_customer_db?" /> 
      <property name="user" value="hbstudent" /> 
      <property name="password" value="hbstudent" />

     <!--  these are connection pool properties for C3P0 --> 
      <property name="initialPoolSize" value="5" />
      <property name="minPoolSize" value="5" /> 
      <property name="maxPoolSize" value="20" /> 
      <property name="maxIdleTime" value="30000" /> 
      </bean>


  <!--  Step 2: Setup Hibernate session factory --> 
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="myDataSource" /> 
  <property name="packagesToScan" value="com.luv2code.springdemo.entity" /> 
  <property name="hibernateProperties">
  <props>
  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
  <prop key="hibernate.show_sql">true</prop> 
  </props>
  </property>
  </bean>

  <!--  Step 3: Setup Hibernate transaction manager --> 
  <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" /> 
  </bean>

  <!--  Step 4: Enable configuration of transactional behavior based on annotations --> 
  <tx:annotation-driven transaction-manager="transactionManager" /> 

  <!--  Add support for reading web resources: css, images, js, etc ... --> 
  <mvc:resources location="/resources/" mapping="/resources/**" /> 
  </beans>

CustomerController.java

package com.luv2code.springdemo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.luv2code.springdemo.dao.CustomerDAO;
import com.luv2code.springdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController 

    // need to inject the customer dao
    @Autowired
    private CustomerDAO customerDAO;

    @RequestMapping("/list")
    public String listCustomers(Model theModel)
    
        // get the customers from dao
        List<Customer> theCustomers = customerDAO.getCustomers();

        // add the customer to the model 
        theModel.addAttribute("customers", theCustomers);

        return "list-customers";
    

实体类:Customer.java

package com.luv2code.springdemo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="customerform")
public class Customer 

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private int id;

    @Column(name="first_name")
    private String firstName;

    @Column(name="last_name")
    private String lastName;

    @Column(name="father_name")
    private String fatherName;

    @Column(name="gender")
    private String gender;

    @Column(name="dob")
    private String dob;

    @Column(name="address")
    private String address;

    public Customer() 

    

    public int getId() 
        return id;
    

    public void setId(int id) 
        this.id = id;
    

    public String getFirstName() 
        return firstName;
    

    public void setFirstName(String firstName) 
        this.firstName = firstName;
    

    public String getLastName() 
        return lastName;
    

    public void setLastName(String lastName) 
        this.lastName = lastName;
    

    public String getFatherName() 
        return fatherName;
    

    public void setFatherName(String fatherName) 
        this.fatherName = fatherName;
    

    public String getGender() 
        return gender;
    

    public void setGender(String gender) 
        this.gender = gender;
    

    public String getDob() 
        return dob;
    

    public void setDob(String dob) 
        this.dob = dob;
    

    public String getAddress() 
        return address;
    

    public void setAddress(String address) 
        this.address = address;
    

    @Override
    public String toString() 
        return "CustomerForm [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", fatherName="
                + fatherName + ", gender=" + gender + ", dob=" + dob + ", address=" + address + "]";
    


接口:CustomerDAO.java

package com.luv2code.springdemo.dao;

import java.util.List;

import com.luv2code.springdemo.entity.Customer;


public interface CustomerDAO 

    public List<Customer> getCustomers();

CustomerDAO 实现类:CustomerDAOImpl

package com.luv2code.springdemo.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.luv2code.springdemo.entity.Customer;

@Repository
public class CustomerDAOImpl implements CustomerDAO 

    // need to inject the session factory
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    @Transactional
    public List<Customer> getCustomers() 

        // get the current hibernate session
        Session currentSession = sessionFactory.getCurrentSession();

        // create a query 
        Query<Customer> theQuery =
                currentSession.createQuery("from Customer", Customer.class);

        // execute query and get result list
        List<Customer> customers = theQuery.getResultList();

        // return the list
        return customers;
    


查看页面:list-customer.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>

<html>
<head>
<title>List Customers</title>
</head>

<body>

    <div id="wrapper">
        <div id="header">
            <h2>CRF-Customer Registration Form</h2>
        </div>
    </div>

    <div id="container">
        <div id="content">
        <!-- add out html table here -->
            <table>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Father Name</th>
                    <th>Gender</th>
                    <th>Dob</th>
                    <th>Address</th>
                </tr>

                <!-- loop over and print our customers -->
                <c:forEach var="tempCustomer" items="$customers">

                    <tr>
                        <td> <c:out value="$tempCustomer.firstName" /></td>
                        <td> <c:out value="$tempCustomer.lastName" /></td>
                        <td> <c:out value="$tempCustomer.fatherName" /></td>
                        <td> <c:out value="$tempCustomer.gender" /></td>
                        <td> <c:out value="$tempCustomer.dob" /></td>
                        <td> <c:out value="$tempCustomer.address" /></td>

                        <%-- <td> $tempCustomer.lastName </td>
                        <td> $tempCustomer.fatherName </td>
                        <td> $tempCustomer.gender </td>
                        <td> $tempCustomer.dob </td>
                        <td> $tempCustomer.address </td> --%>
                    </tr>


                </c:forEach>

            </table>

        </div>

    </div>      

</body>
</html>

数据库:MySql 工作台 表名:customerform

表格名称:图片 2:客户表格

这是我的 pom.xml

<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>com.luv2code.springdemo</groupId>
    <artifactId>spring-crm-rest</artifactId>
    <version>1.0.0</version>
    <packaging>war</packaging>

    <properties>
        <springframework.version>5.0.6.RELEASE</springframework.version>
        <hibernate.version>5.4.1.Final</hibernate.version>
        <mysql.connector.version>5.1.6</mysql.connector.version>
        <c3po.version>0.9.2.1</c3po.version>

        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>$springframework.version</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>$springframework.version</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>$springframework.version</version>
        </dependency>

        <!-- Add Jackson for JSON converters -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>$hibernate.version</version>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>$mysql.connector.version</version>
        </dependency>

        <!-- C3PO -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>$c3po.version</version>
        </dependency>

        <!-- Servlet+JSP+JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>

        <!-- to compensate for java 9+ not including jaxb -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId> 
            <artifactId>jstl</artifactId> 
            <version>1.2</version> 
        </dependency>

    </dependencies>

    <build>

        <finalName>spring-crm-rest</finalName>

        <plugins>

            <!-- Builds a Web Application Archive (WAR) file from the project output 
                and its dependencies. -->
            <plugin>
                <!-- Add Maven coordinates (GAV) for: maven-war-plugin -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.0</version>
            </plugin>

        </plugins>
    </build>
</project>

项目结构:

这是我的控制台错误:

HTTP Status 500 – Internal Server Error
Type Exception Report

Message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause

org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
    org.springframework.orm.hibernate5.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:564)

我是 Spring-MVC + Hibrenate 和 MySql 的新手。运行时,我的应用程序浏览器没有访问不包括 list-controller.jsp 页面的控制器。导入此 Maven 项目代码并在您的 IDE 中运行。请在代码中帮助我运行项目。

【问题讨论】:

【参考方案1】:

这看起来像数据库连接问题:

试试这个

<!-- declare datasource bean -->  

 <bean id="dataSource"  
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  <property name="url" value="jdbc:mysql://localhost:3306/databaseName? 
   useSSL=false"/>  
  <property name="username" value="databaseUsername" />  
  <property name="password" value="databasePassword" />  
 </bean> 

这是一个项目:

https://github.com/imrangthub/BlogSolutionUsingSpringJdbcWithXmlConfig

【讨论】:

你好,兄弟没跑 在我的控制台中:HTTP 状态 500 – 内部服务器错误 ------------------------------- - - - - - - - - - - - - - - - - - - - - - - - - - 类型异常报告消息 Servlet [dispatcher] 的 Servlet.init() 引发异常 说明 服务器遇到了阻止其完成请求的意外情况。异常 javax.servlet.ServletException: Servlet.init() for servlet [dispatcher] 抛出异常 org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) 设置属性值时出错;嵌套异常是 org.springframework.beans.NotWritablePropertyException:bean 类 [org.springframework.jdbc.datasource.DriverManagerDataSource] 的无效属性“jdbcUrl”:Bean 属性“jdbcUrl”不可写或设置方法无效。 setter的参数类型和getter的返回类型是否匹配?【参考方案2】:

在数据库连接中你不需要使用:?,如果是3306,你需要验证数据库端口:

 <!--  Step 1: Define Database DataSource / connection pool --> 
      <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
      <property name="driverClass" value="com.mysql.jdbc.Driver" /> 
      <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/demo_customer_db" /> 
      <property name="user" value="hbstudent" /> 
      <property name="password" value="hbstudent" />

最后你需要确定用户 hbstudent 是否拥有所有用户访问权限

【讨论】:

你好老板,项目很好哈哈 为你高兴 :) 这是控制台:异常 org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 org.springframework.transaction.CannotCreateTransactionException:无法为事务打开 Hibernate Session;嵌套异常是 org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) 你会在这里找到我的项目,我使用了几乎相同的技术; github.com/azzabihaythem/newTest/tree/master/PFE.test01 尝试删除你的数据库并创建一个空的

以上是关于带有Maven客户表单Web应用程序的Spring MVC无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot构建的Web项目如何在服务端校验表单输入

使用 Spring 和 Maven 的模块化 Web 应用程序

《spring实战》学习笔记-第五章:构建spring web应用程序

如何使用 Spring Boot Web 客户端为内容类型 application/x-www-form-urlencoded 的表单数据发布请求

带有 Spring Security 的 Spring Boot - 使用 SMS/PIN/TOTP 的两因素身份验证

带有 Spring Data 的 Spring Boot Maven 多模块项目