0

Github: https://github.com/Gaputin97/my-app.git

При деплое war'ки на tomcat возникают следующие ошибки:

    28-Feb-2018 15:14:42.528 INFO [localhost-startStop-6] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
28-Feb-2018 15:14:42.726 INFO [localhost-startStop-6] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'dispatcher'
28-Feb-2018 15:14:49.669 SEVERE [http-nio-8080-exec-35] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/page] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
 java.lang.NullPointerException
    at com.mycompany.app.controller.TypeController.listAll(TypeController.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
    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.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    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(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)

Controller:

   @Controller
    public class TypeController {

    private TypeService typeService;

    @RequestMapping(value = "/main")
    public String listAll(ModelMap model) {
        model.addAttribute("type", new Type());
        model.addAttribute("typeList", typeService.listAll());
        return "index";
    }

    @RequestMapping("/")
    public String home() {
        return "redirect:/main";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("type") Type type, BindingResult bindingResult) {
        typeService.add(type);
        return "redirect:/main";
    }

    @RequestMapping(value = "/delete/{id}")
    public String deleteType(@PathVariable("id") Integer id) {
        typeService.delete(id);
        return "redirect:/main";
    }
}

Service:

@Service
public class TypeServiceImpl implements TypeService {

    private Transaction transaction;
    private Session session;

    private SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

    private void openTransaction() {
        transaction = sessionFactory.openSession().beginTransaction();
    }

    private void closeTransaction() {
        if (transaction.isActive()) {
            transaction.commit();
        }

        if (session.isOpen()) {
            session.close();
        }
    }

    public void add(Type type) {
        openTransaction();
        sessionFactory.getCurrentSession().save(type);
        closeTransaction();
    }

    @SuppressWarnings("unchecked")
    public List<Type> listAll() {
        openTransaction();
        System.out.println(sessionFactory.getCurrentSession().createQuery("from Type").list());
        List<Type> list = sessionFactory.getCurrentSession().createQuery("from Type").list();
        closeTransaction();
        return list;
    }

    public void delete(Integer id) {
        openTransaction();
        Type type = sessionFactory.getCurrentSession().load(Type.class, id);
        if (type != null) {
            sessionFactory.getCurrentSession().delete(type);
            closeTransaction();
        }
    }
}

index.jsp

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World Page</title>
</head>
<body>
    <form:form modelAttribute="type">
        <table>
            <tr>
                <td><form:label path=type.id_type>Type's ID</form:label></td>
                <td><form:input path="type.id_type" /></td>
            </tr>
            <tr>
                <td><form:label path=type.type_name>Type name</form:label></td>
                <td><form:input path="type.type_name" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </form:form>
    <h3>Types</h3>
    <!-- <c:if test="${!empty typeList}"> -->
    <table class="data">
        <tr>
            <th>Type ID</th>
            <th>Type Name</th>
            <th>&nbsp;</th>
        </tr>
        <c:forEach var="type" items=${typeList}>
            <tr>
                <td><c:out value="${type.id_type}" /></td>
                <td><c:out value="${type.type_name}" /></td>
                <td><a href=delete/${type.id_type}>Delete</a></td>
            </tr>
        </c:forEach>
    </table>
    <!--  </c:if> -->
</body>
</html>

<!-- method="post" action="add" -->
1
  • Hibernate нормально выводит в консоль. Однако на jsp - страницу ругается. Commented 28 февр. 2018 в 12:28

1 ответ 1

2

Ошибка говорит о том, что ваш typeService = NULL в контроллере. И я не вижу, что вы инжектите сервис.

Можно инжектить в поле:

@Autowired
private TypeService typeService;

Или через конструктор (более предпочтительный вариант, рекомендуемый в Spring):

@Controller
public class TypeController {

    private TypeService typeService;

    @Autowired
    public TypeController(TypeService typeService) {
        this.typeService = typeService;
    }

    // остальные методы

}

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.