Spring MVC "Request processing failed" 500 错误
Spring MVC "Request processing failed" 500 error
我是 Spring 的新人,正在尝试通过教程学习。我有一个问题。我将基于 xml 的配置转换为基于注释的配置。 this 是教程。
我收到 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)
项目结构
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
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
@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
@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
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
@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);
}
}
更多异常
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)
我认为您错过了 private PersonDAO personDAO;
之前的 @Autowired
注释。所以在这一行 return this.personDAO.listPersons();
.
中是 null
您错过了包含 @Autowired
以注入依赖项。
1) 在 PersonServiceImpl
:
@Autowired
private PersonDAO personDAO;
2) 在 PersonDAOImpl
中:
@Autowired
private SessionFactory sessionFactory;
最后,您需要在 Spring 配置中使用 @EnableTransactionManagement
启用事务管理 class:
@EnableWebMvc
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ulotrix.spring" })
public class AppConfig extends WebMvcConfigurerAdapter {
我是 Spring 的新人,正在尝试通过教程学习。我有一个问题。我将基于 xml 的配置转换为基于注释的配置。 this 是教程。
我收到 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)
项目结构
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
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
@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
@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
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
@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);
}
}
更多异常
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)
我认为您错过了 private PersonDAO personDAO;
之前的 @Autowired
注释。所以在这一行 return this.personDAO.listPersons();
.
null
您错过了包含 @Autowired
以注入依赖项。
1) 在 PersonServiceImpl
:
@Autowired
private PersonDAO personDAO;
2) 在 PersonDAOImpl
中:
@Autowired
private SessionFactory sessionFactory;
最后,您需要在 Spring 配置中使用 @EnableTransactionManagement
启用事务管理 class:
@EnableWebMvc
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.ulotrix.spring" })
public class AppConfig extends WebMvcConfigurerAdapter {