为什么我在使用Spring MVC + Hibernate Application

时间:2015-10-12 07:07:41

标签: hibernate jsp spring-mvc

这是我的控制者:

            package com.tec.controller;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.stereotype.Controller;
            import org.springframework.ui.Model;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.servlet.ModelAndView;

            import com.tec.domain.RegisterDetails;
            import com.tec.service.RegisterServiceIfc;

            @Controller("registerServiceIfc")

            public class LoginRegisterController {


            private RegisterServiceIfc registerServiceIfc;
            @Autowired(required=true)


                @RequestMapping("/home.sahu")
                public ModelAndView helloWorld() {

                 return new ModelAndView();

                }

                 @RequestMapping("/registration.sahu")

                public ModelAndView LoginPage() {

                        return new ModelAndView();

                 }

                @RequestMapping("/registerDetails.sahu")
                public ModelAndView registerDetails(RegisterDetails perDetails,Model model) {

                    model.addAttribute("pb",perDetails);

                    registerServiceIfc.registerPerson(perDetails);// getting exception here.Its showing perDetails object is null

                    return new ModelAndView();

             }

            }

这是我的服务类:

        package com.tec.service;

        import java.util.List;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;
        import org.springframework.transaction.annotation.Transactional;

        import com.tec.dao.RegisterDaoIfc;
        import com.tec.domain.RegisterDetails;

        @Service("registerDaoIfc")

        public class RegisterServiceIfcImpl implements RegisterServiceIfc{


            private RegisterDaoIfc registerDaoIfc ;
            @Autowired(required=true)


            @Override
            @Transactional
            public void registerPerson(RegisterDetails perDetails) {


                registerDaoIfc.registerPerson(perDetails);
            }

            @Override
            @Transactional
            public List<RegisterDetails> getRegAllDetails() {
                return registerDaoIfc.getRegAllDetails();

            }

        }

这是我的Dao课程:

    package com.tec.dao;

    import java.util.List;
    import org.hibernate.SessionFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;

    import com.tec.domain.RegisterDetails;

    @Repository
    public class RegisterDaoIfcImpl implements RegisterDaoIfc{
        @Autowired(required=true)
        SessionFactory sessionFactory;


        @Override
        @Transactional
        public void registerPerson(RegisterDetails perDetails) {

              this.sessionFactory.getCurrentSession().save(perDetails);

        }

        @Override
        @Transactional
        public List<RegisterDetails> getRegAllDetails() {
            return this.sessionFactory.getCurrentSession().createCriteria(RegisterDetails.class).list();
        }

    }


    This is my POJO class:



    package com.tec.domain;

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


    @Entity
    @Table(name="registerdetails")
    public class RegisterDetails {


        @Id
         @GeneratedValue(strategy=GenerationType.IDENTITY)

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

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

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

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

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

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

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

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

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

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

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



    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }

    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 getMobileNo() {
        return mobileNo;
    }

    public void setMobileNo(String mobileNo) {
        this.mobileNo = mobileNo;
    }

    public String getEmail() {
        return email;
    }

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

    public String getAddress() {
        return address;
    }

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

    public String getLandmark() {
        return landmark;
    }

    public void setLandmark(String landmark) {
        this.landmark = landmark;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getPinno() {
        return pinno;
    }

    public void setPinno(String pinno) {
        this.pinno = pinno;
    }

       }



    This is my JSP page:



    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="css/style.css">

    </head>
    <body>


    <form action="registerDetails.sahu" class="elegant-aero">

    <h1>Registration Form
            <span>Please fill all the texts in the fields.</span>
        </h1>


        <label>
            <span>First Name :</span>

           <input type="text" name="firstName" id="firstName" value="${pb.firstName}">
        </label>


         <label>
            <span>Last Name :</span>
            <input type="text" name="lastName" id="lastName" value="${pb.lastName}">
        </label>

         <label>
            <span>Mobile No :</span>
          <input type="text" name="mobileNo" id="mobileNo" value="${pb.mobileNo}">
        </label>

         <label>
            <span>Email :</span>
          <input type="text" name="email" id="email" value="${pb.email}">
        </label>

         <label>
            <span>Address :</span>
           <input type="text" name="address" id="address" value="${pb.address}">
        </label>

         <label>
            <span>Landmark :</span>
           <input type="text" name="landmark" id="landmark" value="${pb.landmark}">
        </label>


     <label>
            <span>City :</span>
         <input type="text" name="city" id="city" value="${pb.city}">
        </label>

         <label>
            <span>State :</span>
      <input type="text" name="state" id="state" value="${pb.state}">
        </label>

         <label>
            <span>Country :</span>
       <input type="text" name="country" id="country" value="${pb.country}">
        </label>

         <label>
            <span>Pin No :</span>
       <input type="text" name="pinno" id="pinno" value="${pb.pinno}">
        </label>

          <label>
            <span>Register :</span>
       <input type="submit"  value="register"  class="button purple" >
        </label>

    </form>
    </body>
    </html>




This is my XML configuration file:



<?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:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


 <context:component-scan base-package="com.tec.controller." />


    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>




    <!-- For Hibernate -->

    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties"></bean>

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}"
          p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
          p:password="${jdbc.password}"></bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource"/>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.bytecode.use_reflection_optimizer">true</prop>
            <prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
            <prop key="hibernate.sql_comments">true</prop>
            <prop key="hibernate.format_sql">true</prop>
             <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

      <property name="annotatedClasses">
             <list> 
                <value>com.tec.domain.RegisterDetails</value>
                <value>com.tec.domain.StudentRegister</value>
            </list>
        </property>
    </bean>

 <tx:annotation-driven/>
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>




This is my properties file for database:



jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/tecnics
jdbc.username=root
jdbc.password=root



This is my web.xml:


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
     <display-name>Spring3MVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>swikriti</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>swikriti</servlet-name>
        <url-pattern>*.sahu</url-pattern>
    </servlet-mapping>
</web-app>

我收到以下异常:

  

SEVERE:Servlet [swikriti]的Servlet.service()在路径[/ SpringTest]的上下文中引发了异常[请求处理失败;具有根本原因的嵌套异常是java.lang.NullPointerException]   显示java.lang.NullPointerException       在com.tec.controller.LoginRegisterController.registerDetails(LoginRegisterController.java:48)       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)       at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)       at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)       at java.lang.reflect.Method.invoke(Unknown Source)       在org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)       在org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)       at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)       在org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)       在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)       在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)       在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)       在org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:624)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:731)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)       在org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)       在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)       在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)       在org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)       在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)       在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)       在org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)       在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)       在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)       在org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)       at org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:620)       at org.apache.tomcat.util.net.JIoEndpoint $ SocketProcessor.run(JIoEndpoint.java:318)       at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)       at java.util.concurrent.ThreadPoolExecutor $ Worker.run(Unknown Source)       at org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)       在java.lang.Thread.run(未知来源)

我添加了以下库:

enter image description here

1 个答案:

答案 0 :(得分:0)

当然perDetails对象将是null。你错过了很多东西。

首先,在您的GET请求中,您应该在show web form方法中添加以下内容。此外,在每个请求映射处理程序中,返回相应的html视图,而不仅仅是ModelAndView()

     @RequestMapping(value= "/registration.sahu",method = RequestMethod.GET)
     public ModelAndView LoginPage(Model model) {
        RegisterDetails perDetails = new RegisterDetails();
        model.addAttribute("perDetailsForm", perDetails);
        return  new ModelAndview(model,"correspondingHtmlView");
     }

其次,您应该更改POST请求,以便处理表单提交。将Modelattribute添加到您的输入参数中,该参数将html表单绑定到perDetails对象。

    @RequestMapping("/registerDetails.sahu")
    public ModelAndView registerDetails(@ModelAttribute("perDetailsForm") RegisterDetailsperDetails perDetails) {
        registerServiceIfc.registerPerson(perDetails);
        return new ModelAndView("viewname");
}

第三个也是最后一个是将表单从干净的html更改为spring形式。添加spring taglibs!

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<form:form method="post" modelAttribute="perDetailsForm" action="actionUrl">
    <form:input path="property" type="text" /> <!-- bind to perDetail.property-->
</form:form>

here是一个非常好的教程。