0

我创建了一个表单,在发布后我想将这些值保存到数据库并在页面上显示保存的值。
我是spring mvc的新手,因此我不明白我哪里出错了。

这是 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.

模型类

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

}

道类

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>

控制器类

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>

单击保存按钮后,我收到上述错误。请帮我解决这个问题。

4

2 回答 2

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>

但由于您使用的是 Spring,因此最好使用 Spring 表单(以及 spring 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;
于 2013-05-12T11:04:05.150 回答
0

您的模型的属性已注释@ModelAttribute为可以为空。这样当绑定时发生异常时,就会返回一些东西。

注意模型属性和模型属性参数之间的区别。

绑定和验证期间的异常可能是在整数字段中传递文本。

例外:

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

在科特林

避免从异常student: Student进入。student: Student?

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

并且还要看到异常转换为您可以使用的验证以及@ValidHibernate Validator获得:Binding Result

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"

总帐

于 2020-06-19T10:52:42.207 回答