0

저는이 문제에 대한 많은 답변을 통해 많은 스트레스를 받았으며 많은 사람들이 주석을 사용해야한다고 말하고 있습니다. 그러나 나는 그것이 문제가 아니라고 생각합니다. 구성에 오류가 있습니다. 콩이 내 배선되어있을 수 있습니다. 두 지점에서 오류가 발생합니다 1. userName 필드에서 Tab을 누를 때 - 웹 서비스를 실행하고 있으므로2. 제출 버튼을 누르고 POST를 누릅니다. 는 userName 이미 필드 중 내가 탭은 데이터베이스를 확인할 때 내가 그래서 웹 서비스를 사용하고 그래서 존재하는 경우SpringMvc java.lang.NullPointerException - 구성입니다. 정확함

내가 볼 수있는 데이터베이스를 확인하려합니다. 또한 동일한 기능을 다시 호출 할 때 서버에 데이터를 게시 할 때이 동일한 유효성 검사를 수행하려고했습니다.

이 함수는 부울을 반환합니다. 문자열 userName의 매개 변수를 받아들이는 클래스 내의 함수입니다. 어쩌면 콩을 잘못 연결했을 수도 있습니다. 나는 공장 콩 만들고 applicationContext.xml의 새 인스턴스를 만들 경우 그것은 작동 :

FactoryBean.java을

package com.crimetrack.service; 

import org.springframework.context.support.ClassPathXmlApplicationContext; 

public final class FactoryBean { 

     private static ClassPathXmlApplicationContext context; 

     private static ClassPathXmlApplicationContext getContext() { 
      if (context == null) { 
       context = new ClassPathXmlApplicationContext("applicationContext.xml"); 
      } 
      return context; 
     } 

     public static OfficerRegistrationValidation getOfficerRegistrationValidation() { 
      return (OfficerRegistrationValidation) getContext().getBean("officerRegistrationValidation"); 
     } 

} 

하고 내가 사용하는 경우

(FactoryBean.getOfficerRegistrationValidation().validateUserNameManager.DoesUserNameExist(officer.getUserName()) == true){ 

OfficerRegistrationValidation.java 작동하지만 사용할 수 없습니다. 내 응용 프로그램은 각 콩의 새 인스턴스를 applicationContext.xml에 만들고 내 응용 프로그램에 영향을 주므로 사용하십시오.

아래에 내 코드와 두 개의 오류 로그가 있습니다. 1. 사용자 이름 입력란에서 탭을 눌렀을 때 2. 제출 버튼을 통해 양식을 게시 할 때 2. 오류가 발생했습니다. OfficerRegistrationValidation.java

public class OfficerRegistrationValidation implements Validator{ 


    private final Logger logger = Logger.getLogger(getClass()); 


    ValidateUserNameManager validateUserNameManager; 


    public boolean supports(Class<?> clazz) { 

     return Officers.class.equals(clazz); 
    } 


    public void validate(Object target, Errors errors) { 

     Officers officer = (Officers) target; 

     if (officer.getUserName() == null){ 

      errors.rejectValue("userName", "userName.required"); 

     }else{ 

      String userName = officer.getUserName();      

      logger.info("OfficerRegistrationValidation - UserName is not null so going to check if its valid for :" + userName); 
      try { 



       logger.info("OfficerRegistrationValidation - Just before try.....catch block...userName is :" + userName); 

       logger.info("OfficerRegistrationValidation - about to evaluate if (validateUserNameManager.DoesUserNameExist(officer.getUserName()) == true)"); 


       //using a factory bean to instantiate the creation of the bean 
       //in some cases you want to use the existing bean and not instantiate 



       //if (FactoryBean.getOfficerRegistrationValidation().validateUserNameManager.DoesUserNameExist(officer.getUserName()) == true){ 
       if (validateUserNameManager.DoesUserNameExist(officer.getUserName())== true){ 
        errors.rejectValue("userName", "userName.exist"); 
       } 
      } catch (Exception e) { 

       logger.info("OfficerRegistrationValidation - Error Occured When validating UserName"); 
       logger.error("Message", e); 
       errors.rejectValue("userName", "userName.error"); 
      } 

     } 

     if(officer.getPassword()== null){ 
      errors.rejectValue("password", "password.required"); 
     } 

     if(officer.getPassword2()== null){ 
      errors.rejectValue("password2", "password2.required"); 
     } 


    } 


    /** 
    * @return the validateUserNameManager 
    */ 
    public ValidateUserNameManager getValidateUserNameManager() { 
     logger.info("Getting - ValidateUserNameManager"); 
     return validateUserNameManager; 
    } 


    /** 
    * @param validateUserNameManager the validateUserNameManager to set 
    */ 
    public void setValidateUserNameManager(
      ValidateUserNameManager validateUserNameManager) { 

     logger.info("Setting - ValidateUserNameManager"); 
     this.validateUserNameManager = validateUserNameManager; 
    }  

} 

ValidateUserNameManager.java

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 


    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> 

     <style> 
      <%@ include file="../css/forms.css" %> 

     </style> 
     <script type="text/javascript"> 
      <%@ include file="../js/off_reg.js"%> 


      $(document).ready(function(){ 

       $('#userName').blur(function(evt){ 


        CheckAvailability();      
       }); 
      });   

      function CheckAvailability(){ 

       $.ajax({ 
         type:'GET', 
         url:'validateUserName.htm', 
         data:{userName:$('#userName').val()}, 
         dataType: 'json', 
         success:function(data) { 

         if (data == true){ 

          alert("User Name Already Exists"); 

          $("#userNameErr").text("User Name Already Exist"); 

         }else if ($("#userName").val() == ""){ 

          $("#userNameErr").text(" "); 

         }else if(data == false){ 

          $("#userNameErr").text("User Name Valid"); 

         } 


         } 


        }); 

     } 


     </script> 



    <title>Officer Registration</title> 

    </head> 

    <body> 
    <form:form method="post" modelAttribute="officers" action="officer_registration.htm"> 
     <ol> 

      <li><label>User Name</label> 
       <form:input path="userName"/><form:errors path="userName" id="errors"/><label id="userNameErr"></label></li> 
      <li><label>Password</label> 
       <form:password path="password"/><form:errors path="password" id="errors"/></li> 
      <li><label>Re-Enter Password</label> 
       <form:password path="password2"/><form:errors path="password2" id="errors"/></li> 
      <li><label>e-Mail Address</label> 
       <form:input path="emailAdd"/><form:errors path="emailAdd" id="errors"/></li> 

      <br/> 
      <li><input type="submit" name= "request" value="Register" /> 
      <input type="submit" name= "request" value="Update" /></li>   

     </ol> 

    </form:form> 





    </body> 
</html> 

office_registration.jsp :이 내가 달성하기 위해 노력하고 무엇의 좋은 사진을 제공합니다 희망

public class ValidateUserNameManager implements ValidateUserNameIFace { 

    public ValidateUserNameManager(){} 

    private OfficersDAO officerDao; 

    private final Logger logger = Logger.getLogger(getClass()); 


    public boolean DoesUserNameExist(String userName) throws Exception { 

     logger.info("Inside ValidateUserNameManager"); 

     try{ 

      logger.info("ValidateUserNameManager - UserName is : " + userName); 

      if(officerDao.OfficerExist(userName) == true){ 

       logger.info("ValidateUserNameManager - UserName :" + userName + " does exist"); 
       return true; 

      }else{ 
       logger.info("ValidateUserNameManager - UserName :" + userName + " does NOT exist"); 
       return false; 
      } 


     }catch(Exception e){ 
      logger.error("Message", e); 
      logger.info("ValidateUserNameManager - UserName :" + userName + " EXCEPTION OCCURED " + e.toString()); 
      return false; 
     }  

    } 

    /** 
    * @return the officerDao 
    */ 
    public OfficersDAO getOfficerDao() { 
     logger.info("ValidateUserNameManager - getting officerDAO"); 
     return officerDao; 
    } 

    /** 
    * @param officerdao the officerDao to set 
    */ 
    public void setOfficerDao(OfficersDAO officerDao) { 
     logger.info("ValidateUserNameManager - setting officerDAO"); 
     this.officerDao = officerDao; 
    } 



} 

OfficerRegistrationController.java

@Controller 
public class OfficerRegistrationController { 

    private final Logger logger = Logger.getLogger(getClass()); 
    private DivisionManager divisionManager; 
    private PositionManager positionManager; 
    private GenderManager genderManager; 
    private Officers officer = new Officers(); 


    private ValidateUserNameManager validateUserNameManager; 

    Map<String, Object> myDivision = new HashMap<String, Object>(); 
    Map<String, Object> myPosition = new HashMap<String, Object>(); 
    Map<String, Object> myGender = new HashMap<String, Object>(); 


    @InitBinder("officers") 
    protected void initBinder(WebDataBinder binder){ 


     //removes white spaces 
     binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); 

     //formats date 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 

     //By passing true this will convert empty strings to null 
     binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 
     dateFormat.setLenient(false); 


     logger.info("Just before initBinder"); 
     binder.setValidator(new OfficerRegistrationValidation()); 


    } 


    @RequestMapping(value="officer_registration.htm", method = RequestMethod.GET) 
     public ModelAndView loadPage(HttpServletRequest request, 
       HttpServletResponse response,@ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model) throws Exception {  


     try{   


      logger.debug("In Http method for OfficerRegistrationController"); 


       myDivision.put("divisionList", this.divisionManager.getDivisions()); 


       myPosition.put("positionList", this.positionManager.getPositionList()); 


       myGender.put("genderList", this.genderManager.getGenderList()); 

       model.addAttribute("division", myDivision); 
       model.addAttribute("position", myPosition); 
       model.addAttribute("gender", myGender); 

      return new ModelAndView("officer_registration");    


     }catch(Exception e){ 

      request.setAttribute("error",e.getMessage()); 
      return new ModelAndView("error_page");   
     }  
    } 

    @RequestMapping(value="officer_registration.htm", method=RequestMethod.POST) 
    public ModelAndView handleRequest(@Valid @ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model)throws Exception{ 


     if(result.hasErrors()){ 

      model.addAttribute("division", myDivision); 
      model.addAttribute("position", myPosition); 
      model.addAttribute("gender", myGender); 
      return new ModelAndView("officer_registration"); 

     }else{ 

      return null; 
     } 

    } 

    @RequestMapping(value="validateUserName.htm", method=RequestMethod.GET) 


    public @ResponseBody String validateUserName(@RequestParam String userName)throws Exception{ 
     String results = "false"; 
     logger.info("Inside OfficerRegistrationController"); 
     try{ 

      logger.info("In try ..... catch for OfficerRegistrationController"); 
      if (validateUserNameManager.DoesUserNameExist(userName)== true){ 


       results = "true"; 
       return results; 

      } 

     }catch(Exception e){ 

      logger.debug("Error in validateUserName Controller " + e.toString()); 
      return results; 

     } 

      return results; 

    } 



    public void setDivisionManager(DivisionManager divisionManager){ 

     this.divisionManager = divisionManager; 
    } 

    public void setPositionManager(PositionManager positionManager){ 

     this.positionManager = positionManager; 

    } 

    public void setGenderManager(GenderManager genderManager){ 

     this.genderManager = genderManager; 
    } 



    /** 
    * @return the validateUserNameManager 
    */ 
    public ValidateUserNameManager getValidateUserNameManager() { 
     return validateUserNameManager; 
    } 

    /** 
    * @param validateUserNameManager the validateUserNameManager to set 
    */ 
    public void setValidateUserNameManager(
      ValidateUserNameManager validateUserNameManager) { 
     this.validateUserNameManager = validateUserNameManager; 
    } 




    /** 
    * @return the officer 
    */ 
    public Officers getOfficer() { 
     return officer; 
    } 



    /** 
    * @param officer the officer to set 
    */ 
    public void setOfficer(Officers officer) { 
     this.officer = officer; 
    } 


} 

crimetrack-servlet.xml에

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans".............. 


<!-- __________________________________________________________________________________________________ -->  

    <!-- Supports annotations and allows the use of @Controller, @Required, @RequestMapping --> 
    <context:annotation-config/>  

    <context:component-scan base-package="com.crimetrack" /> 
<!-- __________________________________________________________________________________________________ -->  

    <!-- Forwards requests to the "/" resource to the "login" view --> 
    <mvc:view-controller path="/login" view-name="login"/> 

    <!-- Forwards requests to the "/" resource to the "officer_registration" view --> 
    <mvc:view-controller path="/officer_registration" view-name="officer_registration"/> 
<!-- __________________________________________________________________________________________________ -->  

    <!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/> --> 

    <!-- Is used to process method level annotations --> 
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>  
<!-- __________________________________________________________________________________________________ -->  

    <!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> --> 

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 
      <property name="basename" value="messages"/> 
    </bean> 
<!-- __________________________________________________________________________________________________ --> 

    <bean name="/hello.htm" class="com.crimetrack.web.CountryListController"> 
     <property name="countryManager" ref="countryManager"/> 
    </bean> 

    <bean name="/login.htm" class="com.crimetrack.web.AuthenticationController"> 
     <property name="authenticationManager" ref="authenticationManager"/> 
    </bean> 

    <bean name="/officer_registration.htm" class="com.crimetrack.web.OfficerRegistrationController"> 
     <property name="divisionManager" ref="divisionManager" /> 
     <property name="positionManager" ref="positionManager" /> 
     <property name="genderManager" ref="genderManager"/> 
    </bean> 

<!-- __________________________________________________________________________________________________ -->  

    <bean name="/validateUserName.htm" class="com.crimetrack.web.OfficerRegistrationController"> 

     <property name="validateUserNameManager" ref="validateUserNameManager"/>  

    </bean>  


<!-- __________________________________________________________________________________________________ -->  

     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> 
     <property name="prefix" value="/WEB-INF/jsp/"></property> 
     <property name="suffix" value=".jsp"></property>   
     </bean> 



</beans> 

의 ApplicationContext.XML

<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans"............... 


<!-- __________________________________________________________________________________________________ -->    

    <bean id="countryManager" class="com.crimetrack.service.CountryManager"> 
     <property name="countryDao" ref="countryDao"/> 
    </bean> 
    <bean id="countryDao" class="com.crimetrack.jdbc.JdbcCountryDAO"> 
     <property name="dataSource" ref="dataSource"/> 
    </bean> 
<!-- __________________________________________________________________________________________________ --> 

    <bean id="authenticationManager" class="com.crimetrack.service.AuthenticationManager"> 
     <property name="loginDao" ref="loginDao" /> 
    </bean>  
    <bean id="loginDao" class="com.crimetrack.jdbc.JdbcLoginDAO"> 
     <property name="dataSource" ref="dataSource" /> 
    </bean> 
<!-- __________________________________________________________________________________________________ --> 

    <bean id="divisionManager" class="com.crimetrack.service.DivisionManager"> 
     <property name="divisionDao" ref="divisionDao"/> 
    </bean>  
    <bean id="divisionDao" class="com.crimetrack.jdbc.JdbcDivisionDAO"> 
     <property name="dataSource" ref="dataSource"/> 
    </bean> 

<!-- __________________________________________________________________________________________________ -->  

    <bean id="positionManager" class="com.crimetrack.service.PositionManager"> 
     <property name="positionDao" ref="positionDao"/> 
    </bean>  
    <bean id="positionDao" class="com.crimetrack.jdbc.JdbcPositionDAO"> 
     <property name="dataSource" ref="dataSource" /> 
    </bean>  

<!-- __________________________________________________________________________________________________ -->  

    <bean id="genderManager" class="com.crimetrack.service.GenderManager"> 
     <property name="genderDao" ref="genderDao"/> 
    </bean> 

    <bean id="genderDao" class="com.crimetrack.jdbc.JdbcGenderDAO" > 
     <property name="dataSource" ref="dataSource" /> 
    </bean> 

<!-- __________________________________________________________________________________________________ --> 

    <bean id="officerRegistrationValidation" class="com.crimetrack.service.OfficerRegistrationValidation"> 

      <property name="validateUserNameManager" ref="validateUserNameManager"/> 


    </bean> 

    <bean id="validateUserNameManager" class="com.crimetrack.service.ValidateUserNameManager"> 
      <property name="officerDao" ref="officerDao"/> 
    </bean> 


    <bean id="officerDao" class="com.crimetrack.jdbc.JdbcOfficersDAO" > 
      <property name="dataSource" ref="dataSource" /> 
    </bean> 

<!-- __________________________________________________________________________________________________ --> 


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
      <property name="driverClassName" value="${jdbc.driverClassName}"/> 
      <property name="url" value="${jdbc.url}"/> 
      <property name="username" value="${jdbc.username}"/> 
      <property name="password" value="${jdbc.password}"/> 
    </bean> 
<!-- __________________________________________________________________________________________________ -->  

    <bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="locations"> 
      <list> 
       <value>classpath:jdbc.properties</value> 
      </list> 
     </property> 
    </bean> 
<!-- __________________________________________________________________________________________________ -->  

    <bean id="transactionManager" 
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
     <property name="dataSource" ref="dataSource"/> 
    </bean>  


    </beans> 

1. 오류 로그 때 탭 아웃 사용자 이름 필드를 양식 컨트롤러에 POST가

1882370 [http-8084-1] DEBUG org.springframework.web.bind.annotation.support.HandlerMethodInvoker - Invoking request handler method: public java.lang.String com.crimetrack.web.OfficerRegistrationController.validateUserName(java.lang.String) throws java.lang.Exception 
1882370 [http-8084-1] INFO com.crimetrack.web.OfficerRegistrationController - Inside OfficerRegistrationController 
1882370 [http-8084-1] INFO com.crimetrack.web.OfficerRegistrationController - In try ..... catch for OfficerRegistrationController 
1882370 [http-8084-1] INFO com.crimetrack.service.ValidateUserNameManager - Inside ValidateUserNameManager 
1882370 [http-8084-1] INFO com.crimetrack.service.ValidateUserNameManager - ValidateUserNameManager - UserName is : admin 
1882371 [http-8084-1] ERROR com.crimetrack.service.ValidateUserNameManager - Message 
java.lang.NullPointerException 
    at com.crimetrack.service.ValidateUserNameManager.DoesUserNameExist(ValidateUserNameManager.java:26) 
    at com.crimetrack.web.OfficerRegistrationController.validateUserName(OfficerRegistrationController.java:140) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 
    at java.lang.reflect.Method.invoke(Unknown Source) 
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) 
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) 
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) 
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) 
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) 
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) 
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) 
    at java.lang.Thread.run(Unknown Source) 
1882371 [http-8084-1] INFO com.crimetrack.service.ValidateUserNameManager - ValidateUserNameManager - UserName :admin EXCEPTION OCCURED java.lang.NullPointerException 

2.Error 로그 :

1135560 [http-8084-1] DEBUG org.springframework.beans.TypeConverterDelegate - Converting String to [class java.lang.String] using property editor [[email protected]83ad7] 
1135560 [http-8084-1] INFO com.crimetrack.service.OfficerRegistrationValidation - OfficerRegistrationValidation - UserName is not null so going to check if its valid for :admin 
1135560 [http-8084-1] INFO com.crimetrack.service.OfficerRegistrationValidation - OfficerRegistrationValidation - Just before try.....catch block...userName is :admin 
1135560 [http-8084-1] INFO com.crimetrack.service.OfficerRegistrationValidation - OfficerRegistrationValidation - about to evaluate if (validateUserNameManager.DoesUserNameExist(officer.getUserName()) == true) 
1135560 [http-8084-1] INFO com.crimetrack.service.OfficerRegistrationValidation - OfficerRegistrationValidation - Error Occured When validating UserName 
1135561 [http-8084-1] ERROR com.crimetrack.service.OfficerRegistrationValidation - Message 
java.lang.NullPointerException 
    at com.crimetrack.service.OfficerRegistrationValidation.validate(OfficerRegistrationValidation.java:61) 
    at org.springframework.validation.DataBinder.validate(DataBinder.java:725) 
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doBind(HandlerMethodInvoker.java:815) 
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:367) 
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171) 
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) 
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) 
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) 
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) 
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) 
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) 
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) 
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) 
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) 
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) 
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) 
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) 
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) 
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) 
    at java.lang.Thread.run(Unknown Source) 

답변

2

을 귀하의 컨트롤러에 new OfficerRegistrationValidation()을 입력하십시오 initBinder 당신은 인스턴스를 얻을 whe 다시 validateUserNameManager이 Null이므로 NPE입니다. 스프링이 자동으로 클래스 필드를 "채우지"않는다면 요청해야합니다.

또한 컨트롤러는 필드 (클래스 수준)에 사용자 별 항목을 저장하는 것처럼 보이지만 두 사용자가 동일한 페이지를 요청하면 어떻게됩니까?

나는 그런 일

권합니다 :

@Controller 
public class OfficerRegistrationController { 

    private final Logger logger = Logger.getLogger(getClass()); 

    @Autowire // tells spring to populates that for us. 
    private DivisionManager divisionManager; 

    @Autowire 
    private PositionManager positionManager; 

    @Autowire 
    private GenderManager genderManager; 

    @Autowire 
    private OfficerRegistrationValidation officerRegistrationValidation; 

    @InitBinder("officers") 
    protected void initBinder(WebDataBinder binder){ 
     //removes white spaces 
     binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); 

     //formats date 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 

     //By passing true this will convert empty strings to null 
     binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 
     dateFormat.setLenient(false); 


     logger.info("Just before initBinder"); 
     binder.setValidator(officerRegistrationValidation); 
    } 

    @RequestMapping(value="officer_registration.htm", method = RequestMethod.GET) 
    public ModelAndView loadPage(HttpServletRequest request, HttpServletResponse response,@ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model) throws Exception { 
     // ... 
    } 

    @RequestMapping(value="officer_registration.htm", method=RequestMethod.POST) 
    public ModelAndView handleRequest(@Valid @ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model) throws Exception{ 
     // ... 
    } 

    @RequestMapping(value="validateUserName.htm", method=RequestMethod.GET) 
    public @ResponseBody String validateUserName(@RequestParam String userName) throws Exception{ 
     // ... 
    } 
} 

@Component 
public class OfficerRegistrationValidation implements Validator { 

    private final Logger logger = Logger.getLogger(getClass()); 

    @Autowire 
    ValidateUserNameManager validateUserNameManager; 

    public boolean supports(Class<?> clazz) { 
     return Officers.class.equals(clazz); 
    } 

    public void validate(Object target, Errors errors) { 
     // ... 
    } 
} 

@Service 
public class ValidateUserNameManager implements ValidateUserNameIFace { 

    private final Logger logger = Logger.getLogger(getClass()); 

    @Autowire 
    private OfficersDAO officerDao; 

    public boolean doesUserNameExist(String userName) throws Exception { 
     // ... 
    } 
} 

@Repository 
public class OfficersDAO { 
    // ... 
} 

주를 @Component, @Service, 클래스에 대한 @Repository, 상황에 맞는 부팅이 (<context:annotation-config/><context:component-scan base-package="..." /> 문서를 참조) 때이 해당 클래스에 대한 빈을 생성하는 봄 이야기 . @Autowire annotated 필드를 하나의 기존 bean (유형을 사용하는)과 일치 시키려고 봄을 지정하십시오.

전체 아이디어는 컨트롤러, 서비스 및 daos;

  • 컨트롤러는
  • 서비스의 DAO를 사용하는 서비스를 사용합니다.

나는 :) 너무 좋은 독서 조언 :

+0

당신이 날 제공 할 수있는 링크가있는 봄 주석을 사용하는 방법을 이해하고 – devdar

+1

그들을 구성 IOC doc이 하나입니다. http://static.springsource.org/spring/docs/current/spring-framework-reference/html/beans.html#beans-annotation-config를 참조하십시오. –

관련 문제