2017-11-22 5 views
1

Maven, Spring 및 MySQL을 사용하여 Java MVC 프로젝트를 수행하고있다.Spring MVC JSP 뷰에서 Ajax 호출을 구현하는 방법

실제로 "선택"양식에서 값을 선택할 때와 캘린더에서 날짜를 선택할 때 텍스트 메시지를 표시하려고합니다.

나는 내 JSP보기에 다음 코드를 다음과 같습니다

 <div class="well lead">Formulario De Registro De Tarea</div> 
    <form:form method="POST" modelAttribute="task" class="form-horizontal"> 
     <form:input type="hidden" path="id" id="id"/> 

     <div class="row"> 
      <div class="form-group col-md-12"> 
       <label class="col-md-3 control-lable" for="type">Tipo de tarea</label> 
       <div class="col-md-7"> 
        <select id="type" name="type"> 
         <c:forEach var="item" items="${typesList}"> 
          <option value="${item.type}">${item.type}</option> 
         </c:forEach> 
        </select> 
       </div> 
      </div> 
     </div> 


     <div class="row"> 
      <div class="form-group col-md-12"> 
       <label class="col-md-3 control-lable" for="date">Fecha</label> 
       <div class="col-md-7"> 
        <form:input type="text" path="date" id="datepicker" style="width:100px" class="form-control input-sm"/> 
        <div class="has-error"> 
         <c:if test="${fechaFestivo != null}"> 
          <p> ${fechaFestivo}</p> 
         </c:if> 
         <form:errors path="date" class="help-inline"/> 
        </div> 
       </div> 
      </div> 
     </div> 

     <div class="row"> 
      <div class="form-group col-md-12"> 
       <label class="col-md-3 control-lable" for="duration">Duración (horas)</label> 
       <div class="col-md-7"> 
        <form:input type="text" path="duration" id="duration" style="width:60px" class="form-control input-sm" /> 
        <div class="has-error"> 
         <c:if test="${duracionMaxima != null}"> 
          <p> ${duracionMaxima}</p> 
         </c:if> 
         <form:errors path="duration" class="help-inline"/> 
        </div> 
       </div> 
      </div> 
     </div> 

(이 질문의 핵심입니다)이 있습니다

enter image description here

enter image description here

무엇을 나는 그것을 선택할 때부터 선택하고 싶습니다 "Tipo de tarea", 선택 말 아래에 텍스트 표시 : "해당 유형의 모든 작업의 ​​평균 지속 시간은 ... (평균 숫자)"입니다. 또한

, 내 말은 "Duracion" 필드에서 텍스트를 표시, 달력에서 날짜를 선택 : "당신은 실제로이를 위해 X 시간 (기간의 합) (취음) 날짜가". 자세한 정보와

편집

TaskController :

/** 
* This method will provide the medium to add a new task. 
*/ 
@RequestMapping(value = { "/newtask" }, method = RequestMethod.GET) 
public String newTask(ModelMap model) { 
    Task task = new Task(); 
    typesService.loadTypes(); 

    Collection<Types> typesList = typesService.findAllTypes(); 
    model.addAttribute("task", task); 
    model.addAttribute("typesList", typesList); 
    model.addAttribute("edit", false); 
    model.addAttribute("loggedinuser", getPrincipal()); 
    return "task/register"; 
} 

/** 
* This method will be called on form submission, handling POST request for 
* saving task in database. It also validates the task input 
*/ 
@RequestMapping(value = { "/newtask" }, method = RequestMethod.POST) 
public String saveTask(@Valid Task task, BindingResult result, 
     ModelMap model) { 

    Collection<Task> dayTasks = taskService.findTasksDateUserType(task.getDate(), task.getDate(), getPrincipalUser().getId(), null); 
    Double tasksDuration = taskService.getTasksDuration(dayTasks); 

    if(task.getDuration()+tasksDuration>12.0) { 
     ObjectError error = new ObjectError("duracionMaxima", "No se pueden incurrir más de 12 horas un mismo día"); 
     result.addError(error); 
    } 

    if(festivoService.isFestivo(task.getDate())) { 
     ObjectError error = new ObjectError("fechaFestivo", "La fecha de la tarea es un día festivo"); 
     result.addError(error); 
    } 

    if (result.hasErrors()) { 
     Collection<Types> typesList = typesService.findAllTypes(); 
     //List<TaskType> typesList = new ArrayList<TaskType>(Arrays.asList(TaskType.values())); 
     model.addAttribute("typesList", typesList); 
     model.addAttribute("loggedinuser", getPrincipal()); 
     for(ObjectError o: result.getAllErrors()) { 
      System.out.println(o.getObjectName()); 
      if(o.getObjectName().equals("fechaFestivo")) { 
       model.addAttribute("fechaFestivo", "La fecha de la tarea es un día festivo"); 
      } 
      if(o.getObjectName().equals("duracionMaxima")) { 
       model.addAttribute("duracionMaxima", "No se pueden incurrir más de 12 horas un mismo día"); 
      } 
     } 
     return "task/register"; 
    } 

    if(task.getDate().after(new Date())){ 
     FieldError dateError =new FieldError("task","date",messageSource.getMessage("date.before", new String[]{}, Locale.getDefault())); 
     result.addError(dateError); 

     Collection<Types> typesList = typesService.findAllTypes(); 
     model.addAttribute("typesList", typesList); 
     model.addAttribute("loggedinuser", getPrincipal()); 
     return "task/register"; 
    } 

    User user = getPrincipalUser(); 
    taskService.save(task,user); 

    model.addAttribute("success", user.getName() + " ha registrado la tarea"+ task.getId() + " correctamente"); 
    model.addAttribute("loggedinuser", getPrincipal()); 
    //return "success"; 
    return "task/registerSuccess"; 
} 

AJAX RequestMapping을 얻고 만드는 작업 JSP의 게시물 : AJAX와는

를 호출하기위한는 난 그냥 그 방법을 수행 한
@RequestMapping(value= {"/ajax/type-{id}"}) 
public Double ajaxType(@PathVariable Integer typeId) { 
    return typesService.getAvgDailyEffort(typeId); 
} 

@RequestMapping(value= {"/ajax/date-{date}"}) 
public Double ajaxDate(@PathVariable String date) { 
    Double result = 0.; 
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    try { 
     Date dateF = formatter.parse(date); 
     Collection<Task> tasks = taskService.findTasksDateUserType(dateF, dateF, getPrincipalUser().getId(), null); 
     result = taskService.getTasksDuration(tasks); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return result; 
} 
,363,210

나는 또한 내 JSP보기에이를 추가 한

 <div class="row"> 
      <div class="form-group col-md-12"> 
       <label class="col-md-3 control-lable"></label> 
       <div class="col-md-7"> 
        <p id="avg"> Media de horas del tipo de tarea</p> 
       </div> 
      </div> 
     </div> 


     <div class="row"> 
      <div class="form-group col-md-12"> 
      <label class="col-md-3 control-lable"></label> 
       <div class="col-md-7"> 
        <p id="durationday">Horas incurridas en la fecha</p> 
       </div> 
      </div> 
     </div> 

지금 내 JSP보기는 다음과 같습니다

enter image description here

내가 jQuery를에 대한 책을 읽은 후에 할 싶은 것이이 값을 얻을 수 있어요 " (Tipo de tarea) 및 "날짜 " (Fecha)이 변경되면 이전에 설명한 내용을 계산하고 해당 텍스트를 계산 결과로 바꿉니다.

편집이 다시 그냥 내 JSP 헤드에이 코드를 추가 (JQuery와 스크립트)

$(document).ready(function(){ 
    $("#type").change(function(){ 
     $('#avg').load('/ajax-type', 
       "type="+$('#type').find('option').val()) 
    }); 
    $("#datepicker").change(function(){ 
     $('#durationday').load('/ajax-date', 
       "date="+$('#datepicker').val()) 
    }); 
}); 

그리고는 내 컨트롤러 방법을 변경 :

@RequestMapping(value= {"/ajax-type"}) 
public @ResponseBody String ajaxType(@RequestParam("type") String type) { 
    Collection<Types> types = typesService.findAllTypes(); 
    int typeId = 0; 
    for(Types t: types) { 
     if(t.getType().equals(type)) { 
      typeId = t.getId(); 
     } 
    } 
    double avgDailyEffort = typesService.getAvgDailyEffort(typeId); 
    return "Media de horas del tipo de tarea: " + avgDailyEffort; 
} 

@RequestMapping(value= {"/ajax-date"}) 
public @ResponseBody String ajaxDate(@RequestParam("date") String date) { 
    Double tasksDuration = 0.; 
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    try { 
     Date dateF = formatter.parse(date); 
     Collection<Task> tasks = taskService.findTasksDateUserType(dateF, dateF, getPrincipalUser().getId(), null); 
     tasksDuration = taskService.getTasksDuration(tasks); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return "Horas incurridas en la fecha: " + tasksDuration; 
} 

그러나 나는군요 404 GET (찾을 수 없음) 두 필드를 변경할 때.

답변

0

자바 스크립트와 같은 클라이언트 측 기술을 사용해야합니다. JQuery라는 훌륭한 자바 스크립트 라이브러리에는 ajax 호출을 작성하기위한 훌륭한 사전 빌드 함수가 있지만 일부 연구를 수행하고 시도해야합니다. 만약 네가 붙어 있다면 나는 자바 스크립트 (JQuery를 사용하기로 결정했다면)와 관련된 특정 질문을 할 필요가 있다고 생각한다. 다음은 도움이 될 수 Getting started with JQueryJQuery ajax api

을 추가 정보로, 먼저 당신이 경로 변수를 (날짜에 대해 동일한 작업을 수행)를 사용 할 수 @RequestMapping(value= {"/ajax/type/{id}"})이에 @RequestMapping(value= {"/ajax/type-{id}"})을 변경합니다. 또한 요청 매핑 이후와 메소드 선언 앞에 @ResponseBody을 직접 추가해야하므로 spring은 값을 반환 할 것을 알고 있습니다.

+0

답장을 보내 주시면 감사하겠습니다. –

+0

글쎄, 당신이 당신의 대답에 대해 제공 한 모든 정보를 읽은 후에, 나는 내가 원하는 것을 알고 있다고 생각하지만 나는 스스로 할 수는 없다. (또는 튜토리얼을 따른다. 왜냐하면 그들 모두는 상장, PHP로 객체 삭제 또는 수정). 난 그냥 MySQL의 DB에 삽입 된 값으로 쿼리를 만들고 jQuery를 사용하여 입력 아래에 결과를 인쇄 싶습니다. –

+0

필요한 값/객체를 반환하는 ajax 호출을 위해 컨트롤러에 특정 매핑을 설정해야합니다. '@RequestMapping ("ajax")'등 현재 컨트롤러를 게시 할 수 있다면 서버 측 코드를 보는 것이 도움이 될 수 있습니다. – craigwor