23 Ekim 2016 Pazar

Spring MVC , Ajax ve jQuery Kullanımı – 4 (Güncelleme İşlemi)

Serimizin son yazısında Spring MVC, Ajax ,jQuery ve önyüzde Semantic UI ile Datatable'dan seçtiğimiz bir item ı bir modal üzerinde güncelleyeceğiz. Burada ki senaryomuz şu şekilde olacaktır.
Kullanıcı DataTable'dan bir veriyi seçecek ardından "Güncelle" butonuna basıp seçtiği veriyi güncellemek için modal dialog ' u açacak. Veri seçmeden butona bastığı zaman ise "Lütfen Seçim Yapınız" uyarısını alacaktır.
Senaryomuzu oluşturduğumuza göre artık kodlamaya başlayabiliriz.

springrestliste.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/select/1.2.0/css/select.dataTables.min.css">
<link rel="stylesheet" href="https://datatables.net/release-datatables/extensions/TableTools/css/dataTables.tableTools.css">
<script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.0/js/dataTables.select.min.js"></script>

<script src="<c:url value="/resources/js/springrestornekliste.js?v=1.3" />"></script>
</head>
<body>
 <table id="restdt" class="ui selectable celled table">
  <thead>
   <tr id="filterrow">
    <th>Ad</th>
    <th>Soyad</th>
    <th>E-Posta</th>
    <th>Doğum Tarihi</th>
   </tr>
   <tr>
    <th style="width: 100px;color: blue;">Ad</th>
    <th style="width:100px;color:blue;">Soyad</th>
    <th style="color:blue;">E-Posta</th>
    <th style="width: 100px;color: blue;">Doğum Tarihi</th>
   </tr>
 </thead>
 <tbody></tbody>
  <tfoot>
   <tr>
    <td>
     <input type="submit" id="deleteSpringRestrecordId"
            class="ui red button"
            value="Sil" />
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     <input type="submit" id="updateSpringRestrecordId"
           class="ui blue button"
           value="Güncelle" />
    </td>
  </tr>
 </tfoot>
</table>
<div id="srolDelResponse" style="width: 350px;" align="center"></div>
<div id="updateDlgId" class="ui modal" style="width: 510px;height: 230px;">
<jsp:include page="/popup/springrestornekUpdate.jsp"/>
</div>
</body>

</html>



Burada include ettiğimiz modal dialog ' un sayfası springrestornekUpdate.jsp aşağıdaki gibidir.


springrestornekUpdate.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<div class="ui tiny form" align="center">
<div class="header" align="center" style="margin-top: 20px;">
  <a class="ui blue label">Güncelleme Formu</a>
</div>
<div class="content">
 <div class="two fields" >
   <div class="field">
    <label><s:message code="springrestornek.ad" /></label>
    <input type="text" name="ad" id="ad" style="width:220px;" placeholder="Ad"/>
   </div>
   <div class="field">
    <label><s:message code="springrestornek.soyad" /></label>
    <input type="text" name="soyad" id="soyad" style="width:220px;"       placeholder="Soyad"/>
   </div>
  </div>
  <div class="two fields">
   <div class="field">
     <label><s:message code="springrestornek.eposta"/></label>
     <input type="text" name="eposta" id="eposta" style="width:220px;"      placeholder="E-Posta"/>
   </div>
   <div class="field">
     <label><s:message code="springrestornek.dogumtarihi"/></label>
     <input type="text" id="dogumtarihi" name="dogumtarihi" style="width:220px;"  placeholder="Doğumtarihi"/>
   </div>
  </div>
</div>
<div class="actions" align="center">
  <input type="submit" id="updateDlgButton"
         class="ui blue button"
         onclick="updateD()"
         value="Güncelle" />
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="submit" id="cancelDlgButton"
         class="ui cancel button"
         onclick="closeDlg()"
         value="Vazgeç" />
 </div>
</div>


springrestliste.js

$(document).ready(function(){
var picker = new Pikaday(
{
   field: document.getElementById('dogumtarihi'),
   firstDay: 1,
   format : 'DD.MM.YYYY',
   minDate: new Date(1900, 0, 1),
   maxDate: new Date(2016, 12, 31),
   yearRange: [1900,2016],  
   i18n: {
         previousMonth : 'Önceki',
         nextMonth : 'Sonraki',
         months :     ['Ocak','Şubat','Mart','Nisan','Mayıs','Haziran','Temmuz','Ağustos','Eylül','Ekim','Kasım','Aralık'],
         weekdays : ['Pazar','Pazartesi','Salı','Çarşamba','Perşembe','Cuma','Cumartesi'],
weekdaysShort : ['Paz','Pzt','Sal','Çar','Per','Cum','Cmt']
}
});
$('#kayitRestFormId').submit(function(event) {
var ad = $('#ad').val();
var soyad = $('#soyad').val();
var sifre = $('#sifre').val();
var eposta = $('#eposta').val();
var dogumtarihi = $('#dogumtarihi').val();
var json = { "ad" : ad, "soyad" : soyad, "sifre": sifre , "eposta" : eposta , "dogumtarihi" : dogumtarihi};
var rules = {
        on : 'blur',
        inline : true,
        fields: {
        ad: {
            identifier: 'ad',//Bu kısım düzenlenecek
            rules: [
                   {
                    type : 'empty',
                    prompt : 'Ad boş geçilemez!'
            }
          ]
       },
       soyad:{
       identifier : 'soyad',
       rules: [{
       type : 'empty',
       prompt : 'Soyad boş geçilemez!'
       }]
    }, 
       sifre:{
       identifier : 'sifre',
       rules: [{
       type: 'empty',
       prompt : 'Şifre boş geçilemez!'
     }]
   }
  }
};
var table = $('#restdt').DataTable();
$('#restdt tbody').on( 'click', function () {
 if ( $(this).hasClass('selected') ) {
  $(this).removeClass('selected');
}
else {
   table.$('selected').removeClass('selected');
   $(this).addClass('selected');
  }
});
$('#restdt thead tr#filterrow th').each( function () {
 var title = $('#restdt thead th').eq( $(this).index() ).text();
 $(this).html( '<input type="text" style="height:20px;"    onclick="stopPropagation(event);" placeholder="'+title+'" />' );
} );
$("#restdt thead input").on( 'keyup change', function () {
  table
  .column( $(this).parent().index()+':visible' )
  .search( this.value )
  .draw();
} );
function stopPropagation(evt) {
   if (evt.stopPropagation !== undefined) {
      evt.stopPropagation();  
   } else {
      evt.cancelBubble = true;
  }
}
$('#updateSpringRestrecordId').click(
  function(){
    if(table.rows('.selected').data().length == 0){
    alert('Lütfen Seçim Yapınız!');
  }else{
    $('#updateDlgId').modal('show');
    openUpdateSpringRestDlg(table.rows('.selected').data()[0]);
   }
 });
});

function updateD(){
   updateSpringRest(selectedUpdateId);
}

function updateSpringRest(selectedId){
  var ad = $('#ad').val();
  var soyad = $('#soyad').val();
  var eposta = $('#eposta').val();
  var dogumtarihi = $('#dogumtarihi').val();
$.ajax({
 url: "/SpringDispatcherServlet/springrestorneklisteupdate",
 data:   "id="+selectedId+"&ad="+ad+"&soyad="+soyad+"&eposta="+eposta+"&dogumtarihi="+dogum tarihi,
 type: "POST",
 success: function(smartphone) {
  var respContent = "";
  closeDlg();
  $('#restdt').DataTable().ajax.reload();
  selectedUpdateId = null;
  respContent +="<div class='ui green message'><i class='close icon' id='closeIcon'                  onClick='closeIcon()'></i>"+
                "<div class='header'>"+
                "Kayıt Başarıyla Güncellendi"+
                " </div></div>";
  $("#srolDelResponse").html(respContent);
 }
});
event.preventDefault();
}

function closeIcon(){
    $('#closeIcon').parent().hide();
}

function openUpdateSpringRestDlg(data){
    selectedUpdateId = data.id;
    $('#ad').val (data.ad);
    $('#soyad').val(data.soyad);
    $('#eposta').val(data.eposta);
    $('#dogumtarihi').val(data.dogumtarihi);
}

function closeDlg(){
$('#updateDlgId').modal('hide');
}



SpringRestListeController.java


package com.mesutemre.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mesutemre.dao.SpringRestOrnekDAO;
import com.mesutemre.model.SpringRestOrnek;

/**
* @author mesudemre
*
*/
@Controller
public class SpringRestOrnekListeController {

 @Autowired
 private SpringRestOrnekDAO service;

 @RequestMapping(value = "/springrestornekliste" , method = RequestMethod.GET)
 public String showSpringRestOrnekListe(Model model){
   return "springrestornekliste";
 }

 @RequestMapping(method = RequestMethod.GET , produces = "application/json"
                value= "/springorneklistejson")
 public @ResponseBody List<SpringRestOrnek> getSpringRestOrneks(){
   return service.getSpringRestOrnekListe();
 }

 @RequestMapping(value = "/springrestorneklisteupdate" , method =      RequestMethod.POST)
 @ResponseBody
 public SpringRestOrnek updateSpringRestOrnek(@ModelAttribute("sro")      SpringRestOrnek sro, BindingResult resultAjax){
   return service.updateSpringRestOrnek(sro);
 }
}



Güncelleme işlemine ait ekran görüntüleri aşağıdaki gibidir.