spring etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
spring etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

23 Ocak 2017 Pazartesi

Spring RestTemplate Kullanımı


Bir önceki yazımda yazdığımız web service’i başka bir uygulama da kullanmak istediğimizi bir anlık düşünelim. Zaten web service’lerin görevi de bu şekil bir ara katman görevi görmektir. İşte tam bu esnada devreye RestTemplate girer.

Ben yazdığım service’i stand alone bir Java uygulamasında kullanacağım. Siz de kendi yazdığınız web service’i bir Android uygulamasında ya da başka bir web uygulamasında kullanabilirsiniz. Tek yapmanız gereken şey yazdığınız web service’in bir server üzerinde deploy edilmiş olmasıdır.

Lafı fazla uzatmadan kodlamaya başlayalım.

 RestTemplateKullanimiMain.java


public class RestTemplateKullanimiMain {

     private static final String LIST_URL = "http://localhost:9090
/SpringDispatcherServlet/kitaplarRest/kitaplar";
     private static final String FIND_BY_ID_URL= "http://localhost:9090/SpringDispatcherServlet/kitaplarRest/findKitapById";
     private static final String CREATE_URL = "http://localhost:9090/SpringDispatcherServlet/kitaplarRest/createKitap";
     private static final String UPDATE_URL = "http://localhost:9090/SpringDispatcherServlet/kitaplarRest/updateKitap";
     private static final String DELETE_URL = "http://localhost:9090/SpringDispatcherServlet/kitaplarRest/deleteKitap";

   public static void main(String[] args) {
     RestTemplate restTemplate = new RestTemplate();
     Kitap kitap = new Kitap();
     KitapResult kitapResult = new KitapResult();
     ArrayList<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

     HttpHeaders headers = new HttpHeaders();
     headers.setAccept(acceptableMediaTypes);

     HttpEntity<Kitap> entity = new HttpEntity<Kitap>(kitap, headers);
     HttpEntity<KitapResult> resultEntity = new HttpEntity<KitapResult>   (kitapResult, headers);
     HttpStatus statusCode = null;
     ResponseEntity<Kitap> result = null;
     ResponseEntity<KitapResult> kayitResult = null;

   
    // Kitap Listesi
    kitapListele(restTemplate);
  
    // Kitap Arama
    kitap.setKitapId(126);
 
    try {
       result = kitapAra(restTemplate, entity, kitap);
       statusCode = result.getStatusCode();
    } catch (HttpClientErrorException e) {
       statusCode = e.getStatusCode();
    }
    if(statusCode == HttpStatus.NOT_FOUND){
      System.err.println("Kayıt bulunamadı.");
    }else if(statusCode == HttpStatus.OK){
      System.out.println(result.getBody().getKitapAd() + " "   +result.getBody().getYazarAd());
    }

   //Kitap Kayıt
   kitapResult.setKitapAd("Şah Baba");
   kitapResult.setYazarAd("Murat BARDAKÇI");
   kitapResult.setKitaptur("Tarih");
   kitapResult.setKitapDurum("Rafta");
   try {
       kayitResult = kitapKayit(restTemplate,resultEntity,kitap);
       statusCode = kayitResult.getStatusCode();
   } catch (HttpClientErrorException e) {
       statusCode = e.getStatusCode();
   }

   if(statusCode == HttpStatus.CREATED){
      System.out.println(kitapResult.getKitapAd()+" adlı kitap kaydedildi.");
   }
 
   //Kitap Sil
   kitap.setKitapId(275);
   try {
      result = deleteKitap(restTemplate, entity, kitap);
      statusCode = result.getStatusCode();
   } catch (HttpClientErrorException e) {
      statusCode = e.getStatusCode();
   }
   if(statusCode == HttpStatus.OK){
      System.out.println(result.getBody().getKitapAd()+" adlı kitap silindi!");
   }else if(statusCode == HttpStatus.NOT_FOUND){
      System.out.println("Kayıt bulunamadı!");
   }

}


private static void kitapListele(RestTemplate restTemplate){
    List<LinkedHashMap> emps = restTemplate.getForObject(LIST_URL, List.class);
    for(LinkedHashMap map : emps){
       System.out.println("Kitap ID="+map.get("kitapId")+" , Kitap  Ad="+map.get("kitapAd")+" "
+ ", Yazar Ad="+map.get("yazarAd")+" , Kitap Tür = "+map.get("kitaptur")+" , "
+ "Kitap Durum = "+map.get("kitapDurum"));
    }
}

private static ResponseEntity<Kitap> kitapAra(RestTemplate  restTemplate,HttpEntity<Kitap> entity,Kitap kitap){
    return restTemplate.exchange(FIND_BY_ID_URL,
           HttpMethod.POST, entity, Kitap.class);
}

private static ResponseEntity<KitapResult> kitapKayit(RestTemplate restTemplate,HttpEntity<KitapResult> entity,Kitap kitap){
    return restTemplate.exchange(CREATE_URL,
           HttpMethod.POST, entity, KitapResult.class);
}

private static ResponseEntity<Kitap> deleteKitap(RestTemplate restTemplate,HttpEntity<Kitap> entity,Kitap kitap){
    return restTemplate.exchange(DELETE_URL,
           HttpMethod.POST, entity, Kitap.class);
}

private static ResponseEntity<Kitap> updateKitap(RestTemplate restTemplate,HttpEntity<Kitap> entity,Kitap kitap) {
    return restTemplate.exchange(UPDATE_URL,
          HttpMethod.POST, entity, Kitap.class);
   }

}

 Bir sonra ki yazımda görüşmek üzere. İyi çalışmalar...

18 Haziran 2016 Cumartesi

Spring MVC – Apache Tiles 3 Entegrasyonu


Bu yazımda sizlere Spring MVC uygulamalarında annotation tabanlı ayar yaparak Apache Tiles 3 entegrasyonundan bahsedeceğim.
Apache Tiles template tabanlı bir composite frameworktür. Tiles kullanarak kullanışlı templateler oluşturabiliriz.

Apache Tiles kullanmak için öncelikle pom.xml imize aşağıda ki satırları eklememiz gerekmektedir.

         <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-api</artifactId>
            <version>3.0.5</version>
         </dependency>

         <dependency>
            <groupId>org.apache.tiles</groupId>
            <artifactId>tiles-core</artifactId>
            <version>3.0.5</version>
         </dependency>

        <dependency>
           <groupId>org.apache.tiles</groupId>
           <artifactId>tiles-servlet</artifactId>
           <version>3.0.5</version>
        </dependency>

        <dependency>
           <groupId>org.apache.tiles</groupId>
           <artifactId>tiles-jsp</artifactId>
           <version>3.0.5</version>
        </dependency>



Artık uygulamada kullanacağımız templateleri yazmaya başlayabiliriz. Fakat öncelikle Spring MVC ' nin Apache Tiles resolver unu config classımızda tanımlamamız gerekmektedir. WebConfig classımız aşağıda ki gibidir.

WebConfig.java

package com.mesutemre.dispatcherservlet;

import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
import org.springframework.web.servlet.view.tiles3.TilesViewResolver;

/**
* @author mesudemre
*
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.mesutemre")
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public TilesConfigurer tilesConfigurer(){
   TilesConfigurer tiles = new TilesConfigurer();
   tiles.setDefinitions(new String[] {
"tiles-definitions.xml"
});
   tiles.setCheckRefresh(true);
   return tiles;
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
   TilesViewResolver viewResolver = new TilesViewResolver();
   registry.viewResolver(viewResolver);
 }

}


tiles-definition.xml dosyamız aşağıda ki gibi olur.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>

<definition name="base-definition"
template="/layout/template.jsp">
    <put-attribute name="header" value="/layout/header.jsp" />
    <put-attribute name="menu" value="/layout/menu.jsp" />
    <put-attribute name="footer" value="/layout/footer.jsp" />
    <put-attribute name="body" value="" />
</definition>

<definition name="home" extends="base-definition">
   <put-attribute name="title" value="Anasayfa" />
   <put-attribute name="body" value="/home.jsp" />
</definition>

<definition name="apacheTiles" extends="base-definition">
   <put-attribute name="title" value="Apache Tiles" />
   <put-attribute name="body" value="/apacheTiles.jsp" />
</definition>
</tiles-definitions>

Uygulamada ki bütün JSP sayfalarını burada tanımlamamız gerekmektedir. Aksi takdir de aşağıda ki gibi bir hata ile karşılaşırız.

javax.servlet.ServletException: Could not
resolve view with name 'example' in servlet with name 'dispatcher'

Bu örnekte header.jsp , footer.jsp ve menu.jsp den oluşan 3 template dosyası kullandık. Bunlar aşağıda ki gibidir.

header.jsp

<div class="header">
<h1>Merhabalar...</h1>
</div>

footer.jsp

<div class="footer">Her hakkı saklıdır</div>

menu.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<nav>
<a href="/SpringDispatcherServlet/home"><img class="logo" src="http://icons.iconarchive.com/icons/kearone/comicons/128/linux-icon.png"></a>
<ul id="menu">
<li><a href="/SpringDispatcherServlet/home">Anasayfa</a></li>
<li><a href="/SpringDispatcherServlet/liste">Liste</a></li>
<li><a href="/SpringDispatcherServlet/register">Kayıt</a></li>
<li><a href="/SpringDispatcherServlet/ajaxRegister">Ajax Kayıt</a></li>
<li><a href="/SpringDispatcherServlet/apacheTiles">Apache Tiles</a></li>
</ul>
</nav>

Bunları için de barındıran ana template sayfamız aşağıda ki gibidir.

template.jsp

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

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><tiles:getAsString name="title" /></title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<style type="text/css">
html{
background-color:#2F2F2F;
}

body{
height: 100%;
background-color:rgb(245, 245, 245);
}


#header {
margin-left:20%;
top: 0px;
width: 80%;
height: 20%;
position: fixed;
font-family: 'bgMed',arial,helvetica,sans-serif;
font-size: 0.6em;
color: #fff;
z-index: 15;
text-transform: uppercase;
background-color: #272727;
border-bottom: 2px solid hsl(180,70%,55%);
padding-top:20px;
text-align:center;
}

#footer {
margin-left:20%;
left: 0px;
bottom: 0px;
width: 80%;
height: 10%;
position: fixed;
font-family: 'bgMed',arial,helvetica,sans-serif;
font-size: 0.6em;
color: #fff;
z-index: 15;
text-transform: uppercase;
background-color: #272727;
padding-top:20px;
text-align:center;
}


#sidemenu {
width: 20%;
background-color:#2B2B2B;
height: 100%;
overflow: auto;
float: left;
z-index: 20;
position: fixed;
left: 0px;
margin-top:
}

#sidemenu #menu {
color: #fff;
text-align: right;
list-style-type: none;
margin-right: 40px;
float: right;
}

#sidemenu #menu li {
width: 150px;
height: 35px;
font-size: 1.2em;
padding-right:5px;
}

#sidemenu #menu li a {
text-decoration: none;
text-transform: uppercase;
color: #fff;
}

#sidemenu #menu li:active{
border-left: 5px solid hsl(180,70%,55%);
}

#sidemenu #menu li:hover {
background-color: #635555;
border-left: 5px solid hsl(180,70%,55%);
}

.logo{
float:left;
}

#site-content {
width: 80%;
height: 100%;
overflow: auto;
float: left;
z-index: 20;
position: fixed;
min-height: 600px;
margin-top:10%;
margin-bottom:10%;
margin-left:20%;
padding-left:10px;
}

</style>
</head>

<body>
<header id="header">
<tiles:insertAttribute name="header" />
</header>

<section id="sidemenu">
<tiles:insertAttribute name="menu" />
</section>

<section id="site-content">
<tiles:insertAttribute name="body" />
</section>

<footer id="footer">
<tiles:insertAttribute name="footer" />
</footer>
</body>
</html>


Bu templatimiz ; yukarıda bir header , solda bir menu ortada content ve aşağıda bir footer sayfamızı içeriyor. Bu uygulama boyunca görünümde değişen tek kısım content olacaktır. Örneğin anasayfamızın da kulandığı bu template aşağıda ki gibidir.

home.jsp

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

<div class="body">
<h1>Merhabalar...</h1>
<a href="<c:url value="/home" />">Uygulama</a> <br> <a
href="<c:url value="/liste"/>">Liste</a> <br> <a
href="<c:url value="/register" />">Kayıt</a> <br> <a
href="<c:url value="/ajaxRegister" />">Ajax Register</a> <br> <a
href="<c:url value="/apacheTiles" />">Apache Tiles</a>
</div>


Bu sayfanın görünümü aşağıda ki gibi olur.