12 Ekim 2016 Çarşamba

Spring MVC , Ajax ve jQuery Kullanımı – 2 (Kayıt İşlemi)


Bu yazımda sizlere Spring MVC , Ajax ve jQuery  , önyüzde ise Semantic UI kullanarak bir kayıt işleminin nasıl gerçekleştiğinden bahsedeceğim.
Senaryomuz şu şekildedir;      
     
  1.           Ad,Soyad,Şifre,Eposta ve Doğum Tarihi alanlarına kullanıcı verilerini girecek.
  2.           Girilen bu veriler Semantic UI form validationundan geçecek.
  3.           Eğer validation başarılı ise kayıt işlemini yapacak.


Semantic UI hakkında daha fazla bilgiye buradan ulaşabilirsiniz.

Senaryomuzu oluşturduğumuza göre artık işin kodlama kısmına geçebiliriz.

springrestornek.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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="<c:url value="/resources/js/springrestornek.js?v=1.1" />"></script>
</head>
<body>
    <div id="container" style="width:600px;margin-left: 400px;height: 300px;"      align="center">
       <h2 style="color: orange;">Yeni Kayıt</h2>
       <div id="sroResponse"></div>
           <form:form id="kayitRestFormId" cssClass="ui tiny form" commandName="sro"
cssStyle="text-align: center;"
action="${pageContext.request.contextPath}/springrestornek/create.json">
             <div class="two fields" >
                 <div class="field">
                    <label><s:message code="springrestornek.ad" /></label>
                    <form:input path="ad" cssStyle="width:220px;" placeholder="Ad"/>
                 </div>
              <div class="field">
                  <label><s:message code="springrestornek.soyad"/></label>
                  <form:input path="soyad" cssStyle="width:220px;" placeholder="Soyad"/>
              </div>
            </div>
         <div class="two fields">
             <div class="field">
                <label><s:message code="springrestornek.sifre"/></label>
                   <form:input type="password" path="sifre" cssStyle="width:220px;" placeholder="Şifre"/>
             </div>
             <div class="field">
                <label><s:message code="springrestornek.eposta"/></label>
                <form:input path="eposta" cssStyle="width:220px;" placeholder="E-Posta"/>
             </div>
            </div>
           <div class="two fields">
               <div class="field">
                   <label><s:message code="springrestornek.dogumtarihi"/></label>
                       <form:input path="dogumtarihi" id="dogumtarihi" name="dogumtarihi" cssStyle="width:220px;" placeholder="Doğumtarihi"/>
               </div>
           </div>
           <div class="ui error message"></div>
               <input type="submit" id="saveButton"
class="ui primary button"
value="<s:message code="register.save"/>" />
&nbsp;&nbsp;&nbsp;&nbsp; <input type="reset"
class="ui button"
value="<s:message code="register.clear"/>" />
        </form:form>
<a href="${pageContext.request.contextPath}/springrestornekliste">Liste</a>
</div>
</body>
</html>



springrestornek.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',
       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!'
   }]
  }
 }
};
$('#kayitRestFormId').form(rules);
if($('#kayitRestFormId').form('validate form')){
$.ajax({
   url: $("#kayitRestFormId").attr( "action"),
   data: JSON.stringify(json),
   type: "POST",
   beforeSend: function(xhr) {
       xhr.setRequestHeader("Accept", "application/json");
       xhr.setRequestHeader("Content-Type", "application/json");
   },
   success: function(smartphone) {
       var respContent = "";
       respContent += "<a class='ui green label'>Kayıt Başarılı.</a>";
       $("#sroResponse").html(respContent);
    }
 });
}
event.preventDefault();
});
});


SpringRESTOrnekController.java

package com.mesutemre.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ResponseBody;

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

/**
* @author mesudemre
*
*/
@Controller
@RequestMapping(value = "/springrestornek")
public class SpringRESTOrnekController {

   @Autowired
   private SpringRestOrnekDAO service;

   @RequestMapping(value = "" , method = RequestMethod.GET)
   public String showSpringRestOrnekPage(Model model){
      model.addAttribute("sro", new SpringRestOrnek());
      return "springrestornek";
   }

   @RequestMapping(value = "/create" , method = RequestMethod.POST , produces =       MediaType.APPLICATION_JSON_VALUE,
  consumes = MediaType.APPLICATION_JSON_VALUE)
   
   @ResponseBody
   public SpringRestOrnek createSpringRestOrnek(@RequestBody SpringRestOrnek sro){
      return service.saveSpringRestOrnek(sro);
   }
}


Kayıt işlemimize ait ekran görüntüleri aşağıda ki gibi olur.











13 Eylül 2016 Salı

Spring MVC , Ajax ve jQuery Kullanımı – 1


4 kısımdan oluşacak olan Spring MVC , Ajax ve jQuery kullanımı yazı dizisinde , Ajax ve jQuery teknoljilerinin Spring MVC ile nasıl kullanıldığını örnek bir ekran üzerinden inceleyeceğiz.

İlk kısımda Semantic UI ile jQuery datatable kullanımına bakıp , ikinci kısımda ise Ajax POST ile bu datatable’a kayıt atma işlemi üzerinde duracağım.
Senaryomuzu oluşturduğumuza göre artık kodlamaya geçebiliriz.

ajaxRegister.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://www.springframework.org/tags" prefix="s"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css"/>
<script src="http:////code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#ajaxmt').dataTable( {
 "ajax": {
 "url""/SpringDispatcherServlet/ajaxMList",
 "dataSrc"""
 },
 "bInfo" : false,
 "columns": [
 { "mData""adAjax" },
 { "mData""soyadAjax" }
 ],
 "oLanguage" : {
 "sLengthMenu" : "_MENU_ ",
 "sSearch" : "<span class='add-on' display:none;><i class='icon-search' ></i>    </span>Ara:",
 "sZeroRecords" : "Kayıt Bulunamadı",
  oPaginate: {
   "sFirst""İlk",
   "sLast""Son",
   "sNext""Sonraki",
   "sPrevious""Önceki"
 },
},
"iDisplayLength" : 5,
"aLengthMenu" : [
[ 5, 10 ],
[ 5, 10] ],
"aaSorting" : [ [ 0, 'asc' ] ]
});
$('#ajaxmt thead tr#filterrow th').each( function () {
 var title = $('#jtab thead th').eq( $(this).index() ).text();
 $(this).html( '<input type="text" style="height:20px;"    onclick="stopPropagation(event);" placeholder="'+title+'" />' );
} );
// DataTable
var table = $('#ajaxmt').DataTable();
// Apply the filter
$("#ajaxmt 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;
  }
 } 
});
</script>
</head>
<body>
<hr>
 <div align="center">
  <table id="ajaxmt" class="ui celled table">
    <thead>
      <tr id="filterrow">
        <th>Ad</th>
        <th>Soyad</th>
     </tr>
     <tr>
       <th style="width200px;colorblue;">Ad</th>
       <th style="width:300px;color:blue;">Soyad</th>
     </tr>
   </thead>
  </table>
 </div>
</body>
</html>



jsp sayfamızı yukarıda ki gibi yazdıktan sonra geriye url kısmında da belirttiğimiz üzere controller sınıfımızda ki metodu yazmamız gerekir. Bu sınıf aşağıdaki gibi yazılır.


AjaxRegisterController.java

package com.mesutemre.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.AjaxmDAO;
import com.mesutemre.model.AjaxM;

@Controller
public class AjaxRegisterController {

@Autowired
private AjaxmDAO service;

@RequestMapping(value = "/ajaxRegister", method = RequestMethod.GET)
public String ajaxRegisterPageOpen() {
      return "ajaxRegister";
}

@RequestMapping(method = RequestMethod.GET, value = "/ajaxMList" ,
produces = "application/json")
public @ResponseBody
List<AjaxM> getAjaxmList() {
     return service.getAllAjaxMList();
  }
}