Java Spring MVC“请求处理失败”500错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29994655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:56:01  来源:igfitidea点击:

Spring MVC "Request processing failed" 500 error

javaspringhibernatespring-mvcannotations

提问by fatiherdem

I am new at Spring and trying to learn with tutorial. And I have a problem. I converted to xml based config to annotation based config. thisis tutorial.

我是 Spring 的新手,正在尝试通过教程学习。我有一个问题。我将基于 xml 的配置转换为基于注释的配置。是教程。

And I receive HTTP 500 error. This is full stacktrace.

我收到 HTTP 500 错误。这是完整的堆栈跟踪。

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause


root cause

   java.lang.NullPointerException   com.ulotrix.spring.service.PersonServiceImpl.listPersons(PersonServiceImpl.java:35) 
    com.ulotrix.spring.controller.PersonController.listPersons(PersonController.java:28)    

     sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Project Structure

项目结构

AppConfig.java

应用程序配置文件

@EnableWebMvc
@Configuration
@ComponentScan({ "com.ulotrix.spring" })
public class AppConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public SessionFactory sessionFactory() {

    LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
    builder.scanPackages("com.ulotrix.spring.model");
    builder.addProperties(getHibernationProperties());

    return builder.buildSessionFactory();
}

private Properties getHibernationProperties() {

    Properties prop = new Properties();
    prop.put("hibernate.format_sql", "true");
    prop.put("hibernate.show_sql", "true");
    prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    return prop;
}

@Bean(name = "dataSource")
public BasicDataSource dataSource() {

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/deneme_db2");
    ds.setUsername("root");
    ds.setPassword("xxxx");

    return ds;
}

@Bean
public HibernateTransactionManager txManger() {
    return new HibernateTransactionManager(sessionFactory());
}

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

}

PersonService.java

人员服务.java

public interface PersonService {

public void addPerson(Person p);
public void updatePerson(Person p);
public List<Person> listPersons();
public Person getPersonById(int id);
public void removePerson(int id);

}

PersonServiceImpl.java

PersonServiceImpl.java

@Service("personService")
public class PersonServiceImpl implements PersonService {

private PersonDAO personDAO;

public void setPersonDAO(PersonDAO personDAO) {
    this.personDAO = personDAO;
}

@Override
@Transactional
public void addPerson(Person p) {
    this.personDAO.addPerson(p);
}

@Override
@Transactional
public void updatePerson(Person p) {
    this.personDAO.updatePerson(p);
}

@Override
@Transactional
public List<Person> listPersons() {
    return this.personDAO.listPersons();
}

@Override
@Transactional
public Person getPersonById(int id) {
    return this.personDAO.getPersonById(id);
}

@Override
@Transactional
public void removePerson(int id) {
    this.personDAO.removePerson(id);
}
}

PersonController.java

个人控制器.java

@Controller
public class PersonController {

private PersonService personService;

@Autowired(required = true)
@Qualifier(value = "personService")
public void setPersonService(PersonService ps) {
    this.personService = ps;
}

@RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person";
}

//For add and update person both
@RequestMapping(value = "/person/add", method = RequestMethod.POST)
public String addPerson(@ModelAttribute("person") Person p) {

    if(p.getId() == 0) {
        this.personService.addPerson(p);
    }else {
        this.personService.updatePerson(p);
    }
    return "redirect:/persons";
}

@RequestMapping(value = "/remove/{id}")
public String removePerson(@PathVariable("id") int id) {

    this.personService.removePerson(id);
    return "redirect:/persons";
}

@RequestMapping(value = "/edit/{id}")
public String editPerson(@PathVariable("id") int id, Model model) {
    model.addAttribute("person", this.personService.getPersonById(id));
    model.addAttribute("listPersons", this.personService.listPersons());
    return "person";
}
}

PersonDAO.java

PersonDAO.java

public interface PersonDAO {

public void addPerson(Person p);
public void updatePerson(Person p);
public void removePerson(int id);
public List<Person> listPersons();
public Person getPersonById(int id);

}

PersonDAOImpl.java

PersonDAOImpl.java

@Component
public class PersonDAOImpl implements PersonDAO {

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

private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf) {
    this.sessionFactory = sf;
}

@Override
public void addPerson(Person p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.persist(p);
    logger.info("Person saved successfully, Person Details="+p);
}

@Override
public void updatePerson(Person p) {
    Session session = this.sessionFactory.getCurrentSession();
    session.update(p);
    logger.info("Person updated successfully, Person Details="+p);
}

@SuppressWarnings("unchecked")
@Override
public List<Person> listPersons() {
    Session session = this.sessionFactory.getCurrentSession();
    List<Person> personList = session.createQuery("from Person").list();
    for(Person p: personList) {
        logger.info("Person List::"+p);
    }
    return personList;
}

@Override
public Person getPersonById(int id) {
    Session session = this.sessionFactory.getCurrentSession();
    Person p = (Person) session.load(Person.class, new Integer(id));
    logger.info("Person loaded successfully, Person details="+p);
    return p;
}

@Override
public void removePerson(int id) {
    Session session = this.sessionFactory.getCurrentSession();
    Person p = (Person) session.load(Person.class, new Integer(id));
    if(null != p) {
        session.delete(p);
    }
    logger.info("Person deleted successfully, person details="+p);
}

}

More Exception

更多例外

 exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
    org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

采纳答案by Chaitanya

You have missed to include @Autowiredto inject the dependencies.

您错过了包含@Autowired以注入依赖项。

1) In PersonServiceImpl:

1) 在PersonServiceImpl

@Autowired
private PersonDAO personDAO;

2) In PersonDAOImpl:

2)在PersonDAOImpl

@Autowired
private SessionFactory sessionFactory;

Finally you need to enable the transaction management by using @EnableTransactionManagementin your Spring configuration class:

最后,您需要通过@EnableTransactionManagement在 Spring 配置类中使用来启用事务管理:

@EnableWebMvc
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ulotrix.spring" })
public class AppConfig extends WebMvcConfigurerAdapter {

回答by Jens

I think you miss the @AutowiredAnnotation before private PersonDAO personDAO;. so it is nullin this line return this.personDAO.listPersons();.

我想你错过了@Autowired之前的注释private PersonDAO personDAO;。所以它null在这一行return this.personDAO.listPersons();