0

i created a form and on post i want to save those values to the database and show the saved values on the page.
i am new to spring mvc and hence i am not understanding where i am going wrong.

Here is the StackTrace -

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.

Model class

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;
}

}

Dao Class

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);
}


 }

servlet-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>

Controller class

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";
}      

}

View Files

//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>

After i click the save button i get the above mentioned error.Please help me resolve this.

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
user1274646
  • 921
  • 6
  • 21
  • 46
  • Try debugging to detect where the NPE is. – Daniel Conde Marin May 12 '13 at 06:15
  • 1
    What is the error you are receiving after clicking the save button? I don't think you have mentioned about the error =D.. – Jason May 12 '13 at 06:34
  • @TemporaryNickName hey its the same error mentioned in the question Request processing failed; nested exception is java.lang.NullPointerException – user1274646 May 12 '13 at 07:06
  • @user1274646: the exception comes with the name of a source file, the line number where it occurs, and a complete stack trace. Post that. Without this information, we're in the dark. How comes you're doing Spring and Hibernate without knowing that? – JB Nizet May 12 '13 at 07:28
  • @JBNizet hey i have now pasted my entire exception.Please see can u suggest me now..how to solve this i m still stuck up with it. – user1274646 May 13 '13 at 06:21
  • 1
    Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – chrylis -cautiouslyoptimistic- Jan 10 '16 at 11:05

2 Answers2

0

Seems to be a problem in your form. At least, the inputs must be given the name attributes:

 <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>

But since you are using Spring, it is preferable to use the Spring forms (and spring url's also):

<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>

Edit And you should initialize dao!

@Autowired
private CustomerDao dao;
Patison
  • 2,591
  • 1
  • 20
  • 33
  • hey thanks 4 rectifying my mistake sorry it ws silly one.i updated my view now but i am still getting the Null Pointer Exception i hav pasted my entire exception..please have alook at it. – user1274646 May 13 '13 at 06:22
  • 1
    @user1274646 hmmm.. I don't know, where is your 36 line of HomeController now. But! Seems like I found error. Check answer addition – Patison May 13 '13 at 08:39
  • YES, initialize that dao! – arseniyandru Sep 19 '16 at 16:42
0

The attribute of your model has annotated with @ModelAttribute to be nulleable. This is so that when an exception occurs in times of bind there is something to return.

Note the difference between the model attribute and the model attribute parameter.

An exception during bind and validation times could be passing text in an integer field.

Exception:

org.springframework.web.util.NestedServletException: 
Request processing failed; nested exception is java.lang.NullPointerException: 
Parameter specified as non-null is null: method yourMethod, parameter yourParam

In Kotlin

Going from student: Student to student: Student? exception is avoided.

@RequestMapping("/processFormRegister") 
fun processFormRegister(
        @Valid @ModelAttribute("firstStudent") student: Student?,
        validationResult: BindingResult
): String {
    return if (validationResult.hasErrors()) {
        "StudentFormRegister"
    } else {
        "ResultFormRegister"
    }
}

And also to see the exception transformed into a validation you could use @Valid and Binding Result of Hibernate Validator obtaining:

failed to convert value of type java.lang.string[] to required type java.lang.integer; nested exception is java.lang.numberformatexception: for input string: "a"

GL

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62