2013-05-12 10 views
0

제가 양식을 만들었습니다. 게시물에 해당 값을 데이터베이스에 저장하고 페이지에 저장된 값을 표시하려고합니다.
나는 봄 mvc에 새롭다 그러므로 나는 어디에서 잘못되고 있는지 이해하고 있지 않다. 여기 요청 처리에 실패했습니다. 중첩 예외는 java.lang.NullPointerException입니다.

는 스택 트레이스입니다 -

package com.projects.model; 

import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 

@Entity 
@Table(name="customer") 
public class Customer { 

@Id 
int custid; 
String name; 
int age; 

public Customer() 
{} 
public Customer(int custid,String name,int age) 
{ 
    this.custid=custid; 
    this.name=name; 
    this.age=age; 
} 

//Getters And Setters 

public int getCustid() { 
    return custid; 
} 

public void setCustid(int custid) { 
    this.custid = custid; 
} 

public String getName() { 
    return name; 
} 

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

public int getAge() { 
    return age; 
} 

public void setAge(int age) { 
    this.age = age; 
} 

} 

다오 클래스

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException 
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894) 
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) 
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) 
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) 


root cause 

java.lang.NullPointerException 
com.projects.data.HomeController.addCustomer(HomeController.java:36) 
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
java.lang.reflect.Method.invoke(Method.java:601) 
org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) 
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) 
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) 
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) 
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) 
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) 
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) 
javax.servlet.http.HttpServlet.service(HttpServlet.java:641) 
javax.servlet.http.HttpServlet.service(HttpServlet.java:722) 


note The full stack trace of the root cause is available in the VMware vFabric tc Runtime 2.7.2.RELEASE/7.0.30.A.RELEASE logs. 

모델 클래스

package com.projects.model; 


import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 

import com.projects.model.Customer; 

@Repository 
public class CustomerDao { 

@Autowired 
private SessionFactory sessionfactory; 

public SessionFactory getSessionfactory() { 
    return sessionfactory; 
} 

public void setSessionfactory(SessionFactory sessionfactory) { 
    this.sessionfactory = sessionfactory; 
} 

public int save(Customer customer) 
{ 
    return (Integer) sessionfactory.getCurrentSession().save(customer); 
} 


} 

서블릿-context.xml에

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

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> 

<!-- Enables the Spring MVC @Controller programming model --> 
<annotation-driven /> 

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> 
<resources mapping="/resources/**" location="/resources/" /> 

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --> 
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <beans:property name="prefix" value="/WEB-INF/views/" /> 
    <beans:property name="suffix" value=".jsp" /> 
</beans:bean> 

<context:component-scan base-package="com.projects.model" /> 

<beans:bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
    <beans:property name="url" value="jdbc:mysql://localhost:3306/customerdb" /> 
    <beans:property name="username" value="root" /> 
    <beans:property name="password" value="root" /> 
</beans:bean> 

<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 
    <beans:property name="dataSource" ref="dataSource" /> 
    <beans:property name="packagesToScan" value="com.projects.model" /> 

    <beans:property name="hibernateProperties"> 
     <beans:props> 
      <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop> 
      <beans:prop key="hibernate.show_sql">true</beans:prop> 
     </beans:props> 
    </beans:property> 

    </beans:bean> 


<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 
    <beans:property name="sessionFactory" ref="sessionFactory" /> 
</beans:bean> 

</beans:beans> 

컨트롤러 클래스

package com.projects.model; 

import java.text.DateFormat; 
import java.util.Date; 
import java.util.Locale; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.ui.ModelMap; 
import org.springframework.validation.BindingResult; 
import org.springframework.web.bind.annotation.ModelAttribute; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

import com.projects.model.CustomerDao; 
import com.projects.model.Customer; 

/** 
* Handles requests for the application home page. 
*/ 
@Controller 
public class HomeController { 

private static final Logger logger = LoggerFactory.getLogger(HomeController.class); 

/** 
* Simply selects the home view to render by returning its name. 
*/ 

private CustomerDao dao; 


@RequestMapping(value = "/", method = RequestMethod.GET)   
public String customer(Locale locale, Model model) { 
    logger.info("Welcome home! The client locale is {}.", locale); 
    Customer customer=new Customer(); 
    model.addAttribute(customer); 
    return "home"; 
} 

@RequestMapping(value = "/customer", method = RequestMethod.POST) 
    public String addCustomer(@ModelAttribute("customer") Customer customer, ModelMap model) { 

    model.addAttribute("custid", customer.getCustid()); 
    model.addAttribute("name",customer.getName()); 
    model.addAttribute("age", customer.getAge()); 
    dao.save(customer); 
    return "customer/customer"; 
}  

} 

파일보기

//home.jsp

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

<%@ page session="false" %> 
<html> 
<head> 
<title>Home</title> 
</head> 
<body> 


<form:form action="${customer}" method="post" modelAttribute="customer"> 
<form:label path="custid">Id:</form:label> 
<form:input path="custId"/> <br> 

<form:label path="name">Name:</form:label> 
<form:input path="name"/> <br> 

<form:label path="age">Age:</form:label> 
<form:input path="age"/> <br> 

<input type="submit" value="Save"/>  

//customer.jsp

<%@ 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>Submitted Information</title> 
</head> 
<body> 

<h2>Submitted Information</h2> 
<table> 
<tr> 
    <td>Cust id</td> 
    <td>${custid}</td> 
</tr> 
<tr> 
    <td>Name</td> 
    <td>${name}</td> 
</tr> 
<tr> 
    <td>Age</td> 
    <td>${age}</td> 
</tr> 
</table> 
</body> 
</html> 

저장 버튼을 클릭하면 위의 오류 메시지가 나타납니다.이 문제를 해결하는 데 도움을주십시오.

+0

NPE가 어디에 있는지 감지하려면 디버깅을 시도하십시오. – Daniel

+1

저장 버튼을 클릭 한 후 나타나는 오류는 무엇입니까? 나는 당신이 오류 = D에 대해 언급 한 것 같지 않습니다. – Jason

+0

@TemporaryNickName이 질문에 언급 된 것과 같은 오류가 있습니다. 요청 처리에 실패했습니다. 중첩 예외는 java.lang.NullPointerException – user1274646

답변

0

양식에 문제가있는 것 같습니다.

<form method="post" action="<c:url value='/customer/'/>"> 
    Cust_Id : 
    <input type="text" name="custid"> 
    <br> 

    Name : 
    <input type="text" name="name"> 
    <br> 

    Age : 
    <input type="text" name="age"> 

    <input type="submit" value="Save"> 
</form> 

을하지만 당신은 스프링을 사용하고 있기 때문에,이 봄 양식 (봄 URL의도)를 사용하는 것이 바람직하다 : 적어도, 이름을 부여해야합니다 입력 속성

<spring:url var="customer" value="/customer"/> 
<form:form action="${customer}" method="post" modelAttribute="customer"> 
    <form:label path="custid">Id:</form:label> 
    <form:input path="custId"/> <br> 

    <form:label path="name">Name:</form:label> 
    <form:input path="name"/> <br> 

    <form:label path="age">Age:</form:label> 
    <form:input path="age"/> <br> 

    <input type="submit" value="Save"/>  
</form:form> 

편집 그리고 dao을 초기화해야합니다!

@Autowired 
private CustomerDao dao; 
+0

안녕하세요, 제 실수를 바로 잡아 주셔서 감사합니다. 미안 해요. 바보 같아요 .1i 지금 내 견해를 업데이트했지만 여전히 Null Pointer Exception을 얻고 있습니다. 전 전체 예외를 붙여 놓았습니다. 알았어. – user1274646

+1

@ user1274646 hmmm .. 모르겠다. 이제 HomeController의 36 행이 어디 있나.그러나! 내가 오류를 발견 한 것 같습니다. 답변 추가 확인 – Patison

+0

예, 해당 DAO를 초기화하십시오! – arseniyandru

관련 문제