当前位置: 首页 > 知识库问答 >
问题:

Struts 2在提交表单时Hibernate空指针异常

姜运珧
2023-03-14

我试图通过集成Struts 2来创建一个注册页面

Hibernate配置文件:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost/db_socialnetwork</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping resource="hibernate.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Hibernate映射文件:

<hibernate-mapping>
  <class name="models.User" table="tbl_user"> //DAO Class
        <meta attribute="class-description">
            This class contains a sample.
        </meta>
        <id column="user_id" name="id" type="int">
            <generator class="increment"/>
        </id>
        <property column="user_name" name="name" type="string"/>
        <property column="user_pwd" name="pwd" type="string"/>

        <property column="user_email" name="email" type="string"/>
        <property column="user_address" name="address" type="string"/>
        <property column="user_phno" name="phno" type="int"/>
    </class>
</hibernate-mapping>

struts。xml:

<struts>
    <!-- Configuration for the default package. -->
    <constant name="struts.devMode" value="true" />
    <package name="default" extends="struts-default" namespace="/">
        <action name="register" class="models.RegisterAction" method="execute">
            <result name="success">/home.jsp</result>
        </action>
    </package>
</struts>

web。xml:

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

HibernateUtil

public class HibernateUtil {
private static final SessionFactory sessionFactory;

    static {
        try {
                  //new SchemaExport(config).create(true,true);

        sessionFactory = new Configuration().configure().buildSessionFactory();

        } catch (Throwable ex) {
            // Log the exception.
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

报名表格:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <s:form action="register">
            <s:textfield name="name" label="Name"/>
            <s:textfield name="pwd" label="Password"/>

            <s:textfield name="email" label="Email"/>
            <s:textarea name="address" label="Address"/>
            <s:textfield name="phno" label="Mobile"/>

            <s:submit value="Register"/>
        </s:form>
    </body>
</html>

注册表操作

public class RegisterAction extends ActionSupport implements ModelDriven<User>{
    User u = new User();
    UserDao udao = new UserDao();
    public RegisterAction() {
    }

    public String execute() throws Exception {

        udao.addUser(u);
        return "success";
    }

    @Override
    public User getModel() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public User getU() {
        return u;
    }

    public void setU(User u) {
        this.u = u;
    }
}    

用户类:

public class User {
        int id, phno;
    String name, pwd, email, address;

    public String getAddress() {
        return address;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPhno() {
        return phno;
    }

    public void setPhno(int phno) {
        this.phno = phno;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

UserDao

class UserDao {


    public UserDao() {
    }

    public static void addUser(User u) {

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        int i = (Integer)session.save(u);
        t.commit();
        session.close();
    }
}

数据库由以下字段组成:

  • id-自动生成,int,主键
  • 姓名,
  • pwd,
  • 电子邮件,
  • 地址-字符串,
  • phno-int

显示的错误是:

INFO: Hibernate 3.2.5
INFO: hibernate.properties not found
INFO: Bytecode provider name : cglib
INFO: using JDK 1.4 java.sql.Timestamp handling
INFO: configuring from resource: /hibernate.cfg.xml
INFO: Configuration resource: /hibernate.cfg.xml
INFO: Reading mappings from resource : hibernate.hbm.xml
SEVERE: Error parsing XML: XML InputStream(17) The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)".
SEVERE: Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource hibernate.hbm.xml
WARNING: StandardWrapperValve[default]: PWC1406: Servlet.service() for servlet default threw exception
org.xml.sax.SAXParseException: The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)".
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
        at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:387)
        at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:321)
        at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleEndElement(XMLDTDValidator.java:2020)
        at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.endElement(XMLDTDValidator.java:904)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1750)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2906)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:624)
        at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
        at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:486)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:810)
        at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:740)
        at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:110)
        at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1208)
        at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:525)
        at org.dom4j.io.SAXReader.read(SAXReader.java:465)
        at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:499)
        at org.hibernate.cfg.Configuration.addResource(Configuration.java:566)
        at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1587)
        at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1555)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1534)
        at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1508)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1428)
        at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
        at models.HibernateUtil.<clinit>(HibernateUtil.java:24)
        at models.RegisterAction.<init>(RegisterAction.java:10)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:539)
        at java.lang.Class.newInstance0(Class.java:372)
        at java.lang.Class.newInstance(Class.java:325)
        at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:119)
        at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
        at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:139)
        at com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:109)
        at com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:288)
        at com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:388)
        at com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:187)
        at org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
        at org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
        at com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:47)
        at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:478)
        at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
        at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
        at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
        at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
        at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
        at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
        at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
        at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
        at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
        at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
        at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
        at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
        at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
        at java.lang.Thread.run(Thread.java:717) 

共有2个答案

李开宇
2023-03-14

RealsterAction类中,您调用了静态方法UserDao.addUser(u)User道类的sf字段仅在您调用User道的构造函数时初始化,但在您的情况下,构造函数永远不会被调用=

在调用它的一个方法之前,应该初始化sf

请注意,在无静态和/或无同步方法中初始化静态字段是一种非常糟糕的做法。

禹正阳
2023-03-14

你误解了DAO/DTO模式。DAO/DTO不应该是静态的。而且,sessionFactory更好,通常每个应用程序只构建一次,因为这是一个耗时的过程

最好为每个线程模式实现会话。编写类HibernateUtil来构建setsionFactory并获取会话。

那你的刀看起来像

public class UserDao {

    public Session getSession() {
      return HibernateUtil.getSession();
    }

    public void closeSession() {
      HibernateUtil.closeSession();
    }

    public void addUser(User u) {    
        Session session = getSession();
        Transaction t = session.beginTransaction();
        int i = (Integer)session.save(u);
        t.commit();
        closeSession();
    }
}

在你写的动作中

private UserDao userDao = new UserDao();

public String execute() throws Exception {
    User u = new User();
    u.setAddress(address);
    u.setEmail(email);
    u.setName(name);
    u.setPhno(phno);
    u.setPwd(pwd);
    userDao.addUser(u);
    return "success";
}
 类似资料:
  • 我是struts2框架的新手,当我点击submit按钮时,我得到了空指针预期值,注册表表单值没有传递给Bean类,我在Bean类中打印表单值,它打印了空值,我找不到我的错误,请帮助我。。 指数jsp Struts.xml 动作课 例外

  • 问题内容: 在我的appium + testng应用程序中,我输入的是: 给出以下堆栈跟踪: 似乎Appium服务器没有使用该功能成功实例化,但这几乎是在线示例的复制和粘贴-我无法弄清楚出了什么问题。 问题答案: 用if语句括住“ driver”,以了解是否== null。 这是我的能力 使用appium 1.2 *

  • 我在使用hibernate 4.1.3的新的多租户特性时遇到了问题,我使用Glassfish 3.1和JPA2,Hibernate 4.1.3作为提供者。 这是我的坚持.xml 这是我在尝试部署应用程序时遇到的异常。 信息:HCANN000001:Hibernate Commons注解{4.0.1.Final}。找不到属性信息:HHH000021:Bytecode提供程序名称:javassist

  • 问题内容: 有可能这可能是一个双重问题。我将String变量初始化为null。我可能会或可能不会使用一个值更新它。现在我想检查此变量是否不等于null以及我尝试执行的操作是否会得到null指针异常。空指针异常,因为它代价高昂。是否有任何有效的解决方法.TIA 问题答案: 如果您使用 你 不会 得到。 我怀疑你在做什么: 这是因为null 而引发,而不是因为null。 如果仍然无法解释,请发布您用于

  • 我已经更新了我的项目中的一些依赖关系之后,我的Hibernate配置类显示Nullpointerx的。 我将SpringDataJPA存储库与hibernate一起使用,已经超过24小时了,仍然没有找到任何关于小问题的适当解决方案。 我已经尝试过的一些解决方案:- 使用@bean(name=“entityManagerFactory”)提供bean名称 我面临的问题 波姆。xml文件 配置类 db

  • 我试图通过参考YT的一些教程来创建一个表视图。当我做一个简单的表视图及其相关的控制器时,它工作。 主类: TestTableView2.fxml: