2015-12-15 36 views
0

我創建了一個servlet,但我無法注入一個存儲庫對象。有沒有人有這個問題?jirster注入servlet

我的配置在WebConfigurer:

@Override 
public void onStartup(ServletContext servletContext) throws ServletException { 
    log.info("Web application configuration, using profiles: {}", Arrays.toString(env.getActiveProfiles())); 
    // Create the dispatcher servlet's Spring application context 
    AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext(); 
    dispatcherServlet.register(WebMvcAutoConfiguration.class); 

    // Register and map the dispatcher servlet 
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet)); 
    dispatcher.setLoadOnStartup(1); 
    dispatcher.addMapping("/"); 

我的servlet:

@WebServlet(urlPatterns = "/servlet/preview") 
    public class ServletPreViewHtml extends HttpServlet { 
     private static final long serialVersionUID = 1L; 

     @Autowired 
     private PagecontentRepository pagecontentRepository; 

     public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
      doGet(request,response); 
     } 
     public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ 
      response.setContentType("text/html"); 
      PrintWriter out = response.getWriter(); 
      Pagecontent p = pagecontentRepository.getOne(2l); //line 34 
      out.println(p.getFullHtml()); 

總是返回我下面的錯誤:

java.lang.NullPointerException: null at br.com.dmsolutions.netfarmacontentmanager.web.rest.ServletPreViewHtml.doGet(ServletPreViewHtml.java:34)

線NPE的:pagecontentRepository.getOne(2L);

回答

1

而不是使用@WebServlet,我寧願使用@Controller,以便Spring可以注入您的存儲庫。