自动装配时出现空指针异常

时间:2015-04-03 10:45:42

标签: model-view-controller spring-security nullpointerexception autowired

嗨我正在获取空指针异常,而我尝试从我的导出Excel类自动装配到后台控制器,但另一种方式是工作。请帮帮我,我需要从我的后台控制器获取数据.... 下面是我的代码片段

这是我的ExportExcelView

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.rectrix.exide.controller.BackOfficeController;
import com.rectrix.exide.form.model.QuestionBankDetails;
import com.rectrix.exide.service.ModuleService;
@Configuration
@Component
@Repository
@Service
@Transactional
public class ExportExcelView extends AbstractExcelView {

    private BackOfficeController backOfficeController;


    public BackOfficeController getBackOfficeController() {
        return backOfficeController;
    }

    @Resource(name="backOfficeController")
    public void setBackOfficeController(BackOfficeController backOfficeController) {
        this.backOfficeController = backOfficeController;
    }

    private static final Logger logger = Logger.getLogger(ExportExcelView.class);
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String value=(String) model.get("excel");


        if(value.equalsIgnoreCase("questionbankupload")){
                        /* List<QuestionBankDetails> list=(List<QuestionBankDetails> )model.get("transactiondata");*/
                         HSSFSheet excelSheet = workbook.createSheet("Question Bank Excel");
                         setExcelForQuestionBankUpload(excelSheet/*,list*/);                            
                                }

        }
        public void setExcelForQuestionBankUpload(HSSFSheet excelSheet/*, List<QuestionBankDetails> list*/) {


        HSSFRow excelHeader = excelSheet.createRow(0);
        excelHeader.createCell(0).setCellValue("QUESTION");
        excelHeader.createCell(1).setCellValue("OPT1");
        excelHeader.createCell(2).setCellValue("OPT2");
        excelHeader.createCell(3).setCellValue("OPT3");
        excelHeader.createCell(4).setCellValue("OPT4");
        excelHeader.createCell(5).setCellValue("OPT5");
        excelHeader.createCell(6).setCellValue("CORRECT_ANSWER_OPTION");
        excelHeader.createCell(7).setCellValue("QUESTION_TYPE");
        excelHeader.createCell(8).setCellValue("SECTION_ID");
        excelHeader.createCell(9).setCellValue("LEVEL");

        // just for try
        List<QuestionBankDetails> list = new ArrayList<QuestionBankDetails>();

        try {
            list=backOfficeController.toGet();  // from this part my code is not going to controller
                    int i=1;
            for(QuestionBankDetails qd : list) {

                excelHeader = excelSheet.createRow(i++);
                    excelHeader.createCell(0).setCellValue(qd.getQuestion());
                    excelHeader.createCell(1).setCellValue(qd.getOpt1());
                    excelHeader.createCell(2).setCellValue(qd.getOpt2());
                    excelHeader.createCell(3).setCellValue(qd.getOpt3());
                    excelHeader.createCell(4).setCellValue(qd.getOpt4());
                    excelHeader.createCell(5).setCellValue(qd.getOpt5());
                    excelHeader.createCell(6).setCellValue(qd.getCorrectAnswer());
                    excelHeader.createCell(7).setCellValue(qd.getQuestionType());
                    excelHeader.createCell(8).setCellValue(qd.getSectionId());
                    excelHeader.createCell(9).setCellValue(qd.getLevel());
                }

        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
}

}

这是我的控制器(后台控制器)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.mail.Multipart;
import javax.management.relation.Role;
import javax.resource.spi.AdministeredObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.hibernate.engine.jdbc.batch.spi.Batch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.messaging.support.ErrorMessage;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import sun.security.jca.GetInstance;

import com.rectrix.exide.dao.LanguageDetailsDao;
import com.rectrix.exide.dao.RoleDetailsDao;
import com.rectrix.exide.dao.SlotDao;
import com.rectrix.exide.exception.BatchNotFound;
import com.rectrix.exide.exception.DuplicateFound;
import com.rectrix.exide.exception.EmployeeIdNotFound;
import com.rectrix.exide.exception.GroupNotFound;
import com.rectrix.exide.exception.LanguageNotFound;
import com.rectrix.exide.exception.ModuleNotFound;
import com.rectrix.exide.exception.RoleNotFound;
import com.rectrix.exide.exception.TopicNotFound;
import com.rectrix.exide.form.model.AddConfigDetails;
import com.rectrix.exide.form.model.AddToModuleDetails;
import com.rectrix.exide.form.model.AddVariable;
import com.rectrix.exide.form.model.AttendanceDetailsForm;
import com.rectrix.exide.form.model.CreateBatchDetails;
import com.rectrix.exide.form.model.CreateModuleDetails;
import com.rectrix.exide.form.model.DummyModel;
import com.rectrix.exide.form.model.EditModuleAdminDetails;
import com.rectrix.exide.form.model.EmployeeDetails;
import com.rectrix.exide.form.model.EmployeeFormDetails;
import com.rectrix.exide.form.model.ExternalUploadDetails;
import com.rectrix.exide.form.model.InternalUploadDetails;
import com.rectrix.exide.form.model.LangDetailsForm;
import com.rectrix.exide.form.model.ListAdminDetails;
import com.rectrix.exide.form.model.ListModuleDetails;
import com.rectrix.exide.form.model.QuestionBankDetails;
import com.rectrix.exide.form.model.RoleModuleDetails;
import com.rectrix.exide.form.model.SectionDetailsForm;
import com.rectrix.exide.form.model.SessionStoreDetails;
import com.rectrix.exide.form.model.SlotForm;
import com.rectrix.exide.form.model.TopicDetailsForm;
import com.rectrix.exide.form.model.TopicSectionCountDetails;
import com.rectrix.exide.hris.model.EmployeeMasterLookUp;
import com.rectrix.exide.model.BatchDetails;
import com.rectrix.exide.model.GroupMaster;
import com.rectrix.exide.model.LanguageDetails;
import com.rectrix.exide.model.LoginUserDetail;
import com.rectrix.exide.model.ModuleConfigDetails;
import com.rectrix.exide.model.RoleDetails;
import com.rectrix.exide.model.Slot;
import com.rectrix.exide.model.StudentDetails;
import com.rectrix.exide.model.ModuleDetails;
import com.rectrix.exide.service.AttendanceService;
import com.rectrix.exide.service.BatchService;
import com.rectrix.exide.service.ModuleService;
import com.sun.java.swing.plaf.motif.resources.motif;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.sun.org.apache.regexp.internal.recompile;
import com.sun.org.apache.xml.internal.serializer.EmptySerializer;

@Controller
@RequestMapping(value="/admin/")
@Component
@ComponentScan

public class BackOfficeController {

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



    public BackOfficeController() {
        // TODO Auto-generated constructor stub
    }



    @Autowired
    private ModuleService moduleService;



    @RequestMapping(value="questionuploadtemplate", method=RequestMethod.GET)
    public ModelAndView getQuestionUploadTemplate(){
        return new ModelAndView("ExportExcel","excel","questionbankupload");
    }



@RequestMapping(value="listquestions",method={RequestMethod.POST,RequestMethod.GET})
    public @ResponseBody List<QuestionBankDetails> getQuestionListByTopicId(@RequestParam String topicId, @RequestParam String langId, @RequestParam Long moduleId){
        List<QuestionBankDetails>list = new ArrayList<QuestionBankDetails>();
        try {

            /*String topicId = "1";
                        String langId = "l1";
                        Long moduleId =  (long)1;*/
            list = moduleService.getQuestionListByTopicId(topicId, langId, new Long(moduleId));
            return list;

        }catch (Exception e) {
            logger.error("error in fetching the questions from the topic id", e);
        }
        return list;

    }





public List<QuestionBankDetails> toGet(){

        List<QuestionBankDetails> list = new ArrayList<QuestionBankDetails>();
        try {
            String topicId ="1";
            String langId ="l1";
            Long moduleId =(long)1;
            list=getQuestionListByTopicId(topicId, langId, new Long(moduleId));
            return list;

        }catch(Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
        return new ArrayList<QuestionBankDetails>();
    } 

  }

这是我的bean

 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    <context:component-scan base-package="com.rectrix.exide.controller"></context:component-scan>

    <mvc:annotation-driven />

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:system.properties" />
    </bean>



    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="${spring.view.prefix}" /> <property name="suffix" 
        value="${spring.view.suffix}" /> </bean>



    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
     <property name="location">
         <value>classpath:/META-INF/spring/spring-excel-views.xml</value>
     </property>
     <property name="order" value="0" />
  </bean>
  <bean id="excelExport" class="com.rectrix.exide.excel.ExportExcelView">
  <property name="backOfficeController" ref="backOfficeController"/>
  </bean>

    <bean id="backOfficeController" class="com.rectrix.exide.controller.BackOfficeController"/> 



    <mvc:default-servlet-handler />



</beans>

1 个答案:

答案 0 :(得分:1)

你的配置很乱。首先修复你的课程..

public class ExportExcelView extends AbstractExcelView { ... }

删除所有这些注释。

@Controller
@RequestMapping(value="/admin/")
public class BackOfficeController { ... }

@Component@ComponentScan在这里没有意义。

清理你的xml。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <context:component-scan base-package="com.rectrix.exide.controller" />
    <context:property-placeholder location="classpath:system.properties" />

    <mvc:annotation-driven />
    <mvc:default-servlet-handler />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="${spring.view.prefix}" /> 
        <property name="suffix" value="${spring.view.suffix}" /> 
    </bean>

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="location" value="classpath:/META-INF/spring/spring-excel-views.xml" />
        <property name="order" value="0" />
    </bean>

</beans>

注意:我假设您的基于Excel的视图也在spring-excel-views.xml中定义了!

然而,真正的问题是为什么你在视图中注入控制器?视图应仅使用模型来呈现自身。它不应该做任何其他事情。您应该正确地准备模型,而不是将控制器注入视图中。

你的观点应该是这样的。

public class ExportExcelView extends AbstractExcelView {

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

    @Override
    protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String value=(String) model.get("excel");

        if(value.equalsIgnoreCase("questionbankupload")){
            /* List<QuestionBankDetails> list=(List<QuestionBankDetails> )model.get("transactiondata");*/
            HSSFSheet excelSheet = workbook.createSheet("Question Bank Excel");
            setExcelForQuestionBankUpload(excelSheet, model);                            
        }        
    }

    public void setExcelForQuestionBankUpload(HSSFSheet excelSheet, model) {

        HSSFRow excelHeader = excelSheet.createRow(0);
        excelHeader.createCell(0).setCellValue("QUESTION");
        excelHeader.createCell(1).setCellValue("OPT1");
        excelHeader.createCell(2).setCellValue("OPT2");
        excelHeader.createCell(3).setCellValue("OPT3");
        excelHeader.createCell(4).setCellValue("OPT4");
        excelHeader.createCell(5).setCellValue("OPT5");
        excelHeader.createCell(6).setCellValue("CORRECT_ANSWER_OPTION");
        excelHeader.createCell(7).setCellValue("QUESTION_TYPE");
        excelHeader.createCell(8).setCellValue("SECTION_ID");
        excelHeader.createCell(9).setCellValue("LEVEL");

        // just for try
        List<QuestionBankDetails> list = model.get("details");

        try {
            int i=1;
            for(QuestionBankDetails qd : list) {
                excelHeader = excelSheet.createRow(i++);
                excelHeader.createCell(0).setCellValue(qd.getQuestion());
                excelHeader.createCell(1).setCellValue(qd.getOpt1());
                excelHeader.createCell(2).setCellValue(qd.getOpt2());
                excelHeader.createCell(3).setCellValue(qd.getOpt3());
                excelHeader.createCell(4).setCellValue(qd.getOpt4());
                excelHeader.createCell(5).setCellValue(qd.getOpt5());
                excelHeader.createCell(6).setCellValue(qd.getCorrectAnswer());
                excelHeader.createCell(7).setCellValue(qd.getQuestionType());
                excelHeader.createCell(8).setCellValue(qd.getSectionId());
                excelHeader.createCell(9).setCellValue(qd.getLevel());
            }

        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
        }
    }
}

并且您的控制器应该准备模型。

@RequestMapping(value="questionuploadtemplate", method=RequestMethod.GET)
public ModelAndView getQuestionUploadTemplate(){
    ModelAndView mav = new ModelAndView("ExportExcel");
    mav.addObject("excel", "questionbankupload");
    mav.addObject("details", doGet());
    return mav;
}