0
votes

I want to search the data from database, and when I press the searching button console give me some information like:

嚴重: Servlet.service() for servlet [dispatcherServlet] in context with path [/FirstSpring] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at tw.idv.firstspring.dao.imp.StudentDAOImpl.search(StudentDAOImpl.java:19) at tw.idv.firstspring.service.imp.StudentServiceImpl.search(StudentServiceImpl.java:37) at tw.idv.firstspring.controller.StudentController.johnnySearch(StudentController.java:45) 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) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) 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) at java.lang.Thread.run(Unknown Source)

This is my controller:

package tw.idv.firstspring.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import tw.idv.firstspring.bean.StudentBean;
import tw.idv.firstspring.service.StudentService;

@Controller
@RequestMapping("/Student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent")
    public  ModelAndView addStudent(StudentBean StudentBean) throws Exception {
        studentService.addStudent(StudentBean);
        ModelAndView modelAndView = new ModelAndView("FormCheckResultView");
        return modelAndView;
    }

    @RequestMapping("/updateStudent")
    public @ResponseBody String updateStudent(StudentBean StudentBean) throws Exception {
        studentService.updateStudent(StudentBean);
        return null;
    }

    @RequestMapping("/searchStudent")
    public @ResponseBody List<StudentBean> searchStudent(StudentBean StudentBean) throws Exception {
        List<StudentBean> sbList = studentService.search(StudentBean);
        return sbList;
    }


    @RequestMapping( value= "/johnnySearch",method = RequestMethod.GET)// Johnny do in yourself.
    public @ResponseBody ModelAndView johnnySearch(StudentBean StudentBean) throws Exception {

        List<StudentBean> stu=studentService.search(StudentBean);
        return new ModelAndView("index","studentList",stu);
    }
}

This is the view (index.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%> 

<%
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!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=utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">

<base href="<%=basePath%>">

<title>student information</title>

</head>

<body>

    <table border="1" cellpadding="10" cellspacing="0">
        <tr>
            <th>學生姓名</th>
            <th>學號</th>
            <th>學制</th>
            <th>性别</th>
            <th>班級</th>
            <th>老師姓名</th>
            <th>聯絡電話</th>
            <th>聯絡地址</th>
            <th>日間部/夜間部</th>

        </tr>
        <c:forEach items="${studentList}" var="stu">
            <tr>
                <td>${stu.name}</td>
                <td>${stu.stuNo}</td>
                <td>${stu.type}</td>
                <td>${stu.gender}</td>
                <td>${stu.classStr}</td>
                <td>${stu.teacher}</td>
                <td>${stu.phone}</td>
                <td>${stu.address}</td>
                <td>${stu.status}</td>

            </tr>
        </c:forEach>
    </table>
</body>

</html>

This is the serviceImp

    package tw.idv.firstspring.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import tw.idv.firstspring.bean.StudentBean;
import tw.idv.firstspring.dao.StudentDAO;
import tw.idv.firstspring.service.StudentService;
import tw.idv.firstspring.utils.BeanUtility;
import tw.idv.firstspring.vo.Student;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDAO studentDAO;

    @Override
    public void addStudent(StudentBean StudentBean) {
        Student s = new Student();
        BeanUtility.copyProperties(StudentBean, s);
        studentDAO.insertOrUpdate(s);
    }

    @Override
    public void updateStudent(StudentBean StudentBean) {
        Student s = new Student();
        BeanUtility.copyProperties(StudentBean, s);
        studentDAO.insertOrUpdate(s);
    }

    @Override
    public List<StudentBean> search(StudentBean StudentBean) {
        List<Student> sList = studentDAO.search(StudentBean);
        List<StudentBean> sbList = new ArrayList<>();
        for (Student s : sList) {
            StudentBean sb = new StudentBean();
            sb.setStuNo(s.getStuNo());
            sb.setAddress(s.getAddress());
            sb.setClassStr(s.getClass_());
            sb.setGender(s.getGender());
            sb.setName(s.getName());
            sb.setPassword(s.getPassword());
            sb.setTeacher(s.getTeacher());
            sb.setType(s.getType());
            sb.setPhone(s.getPhone());
            sb.setStatus(s.getStatus());
        }
        return sbList;
    }

}

studentBean

package tw.idv.firstspring.bean;

public class StudentBean {

    private String stuNo;
    private String name;
    private String gender;
    private String type;
    private String classStr;
    private String teacher;
    private String phone;
    private String address;
    private String password;
    private String status;

    public String getStuNo() {
        return stuNo;
    }

    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getClassStr() {
        return classStr;
    }

    public void setClassStr(String classStr) {
        this.classStr = classStr;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

studentDAOImp

package tw.idv.firstspring.dao.imp;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import tw.idv.firstspring.bean.StudentBean;
import tw.idv.firstspring.dao.StudentDAO;
import tw.idv.firstspring.vo.Student;

@Repository
public class StudentDAOImpl extends BaseDAOImpl<Student> implements StudentDAO {

    @Override
    public List<Student> search(StudentBean studentBean) {
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Student.class);
        if (!studentBean.getAddress().equals("") && studentBean.getAddress() != null) {
            detachedCriteria.add(Restrictions.eq("address", studentBean.getAddress()));
        }
        if (!studentBean.getName().equals("") && studentBean.getName() != null) {
            detachedCriteria.add(Restrictions.eq("name", studentBean.getName()));
        }
        if (!studentBean.getPhone().equals("") && studentBean.getPhone() != null) {
            detachedCriteria.add(Restrictions.eq("phone", studentBean.getPhone()));
        }
        if (!studentBean.getStuNo().equals("") && studentBean.getStuNo() != null) {
            detachedCriteria.add(Restrictions.eq("stuNo", studentBean.getStuNo()));
        }
        if (!studentBean.getGender().equals("") && studentBean.getGender() != null) {
            detachedCriteria.add(Restrictions.eq("gender", studentBean.getGender()));
        }
        if (!studentBean.getType().equals("") && studentBean.getType() != null) {
            detachedCriteria.add(Restrictions.eq("type", studentBean.getType()));
        }
        if (!studentBean.getClassStr().equals("") && studentBean.getClassStr() != null) {
            detachedCriteria.add(Restrictions.eq("class", studentBean.getClassStr()));
        }
        if (!studentBean.getTeacher().equals("") && studentBean.getTeacher() != null) {
            detachedCriteria.add(Restrictions.eq("teacher", studentBean.getTeacher()));
        }
        if (!studentBean.getPassword().equals("") && studentBean.getPassword() != null) {
            detachedCriteria.add(Restrictions.eq("password", studentBean.getPassword()));
        }
        if (!studentBean.getStatus().equals("") && studentBean.getStatus() != null) {
            detachedCriteria.add(Restrictions.eq("status", studentBean.getStatus()));
        }
        return this.getHibernateTemplate().findByCriteria(detachedCriteria);
    }

}
1
Please add code for StudentDAOImpl. There is a NPE in thatgargkshitiz
Thanks, I already add codeJohnny Wang

1 Answers

2
votes

StudentDaoImpl is throwing a null pointer exception (NPE) at line no. 19:

if (!studentBean.getAddress().equals("") && studentBean.getAddress() != null) {

Either studentBean OR studentBean.getAddress() is null here, hence the exception. Logically, you would need to re-write all of your conditions inside search(StudentBean studentBean) method to avoid NPEs. Example:

if (studentBean!= null && !"".equals(studentBean.getAddress()) {

Also, validate once that studentBean is not null. Infact, if it comes as null, you don't need to execute all this code (and you can throw an exception right in the beginning of search method) and your conditions would be shortened like:

if (!"".equals(studentBean.getAddress()) {