Spring MVC – 08 – RequestMapping – 02 |@PathVariable | @RequestParam | @MatrixVariable

Merhaba Arkadaslar
Bu bolum Spring MVC yazilarimi gozden gecirirken ilgili konulari biraz daha fazla aciklamak adina araya ekledigim bir bolum oldu. Buradaki annotation’lari ornekler ile biraz daha iyi aciklamak istedim.

Bu yazida su annotation’lari ornekler ile anlamaya calisacagiz.

  • @PathVariable
  • @RequestParam
  • @MatrixVariable

@PathVariable 

Bir CustomerController sinifimiz olsun burada her Customer id’ye karsilik olarak bir method tanimlamamiz mumkun olmayacaktir.

customer/1
customer/2
customer/100
...

Ya da bir baska ornek olarak urunleri(product) listelemek istiyoruz burada bir cok kategori olabilir. Her birini karsilacak bir method yazamayiz.

products/laptop
products/tablet
products/monitor
products/tv
...

Bu sekilde bir cok kategori olabilir , her bir URI’a karsilik bir @RequestMapping annotation tanimlayip metot kullanmamiz mumkun olmayacaktir.

Iste bu noktada bize yardimci olarak @PathVariable annotation’ini kullanabiliriz.

CustomerController.java

package _07.uri.arguments.controller;
//imports
@Controller
@RequestMapping("/customer")
public class CustomerController {

	// @PathVariable
	// @RequestParam
	// @MatrixVariable

	@RequestMapping("/pathVariable/{customerId}")
	// http://localhost:8080/injavawetrust.springmvc/customer/pathVariable/100
	public String getCustomerById(@PathVariable("customerId") String customerId, Model model) {
		model.addAttribute("message1", "CustomerController#getCustomerById is called.");
		model.addAttribute("message2", "Customer Id : " + customerId);
		return "07.uri.arguments.view/customer";
	}

	@RequestMapping("/pathVariable2/{day}/{month}/{year}")
	// http://localhost:8080/injavawetrust.springmvc/customer/pathVariable2/18/06/1989
	public String getCustomersByBirthDate(@PathVariable("day") int day, @PathVariable("month") int month,
			@PathVariable("year") int year, Model model) {
		LocalDate date = LocalDate.of(year, month, day);
		model.addAttribute("message1", "CustomerController#getCustomersByBirthDate is called.");
		model.addAttribute("message2", "Customer BirthDate : " + date);
		return "07.uri.arguments.view/customer";
	}


Ornek kodumuzu inceleyelim ;
Oncelikle @Controller ve @RequestMapping(“/customer”) annotation’ini class taniminda ekledik.

@RequestMapping annotation’ininda path bilgisini suslu parantezler (curly brace) arasinda yaziyoruz {customerId}
Boylece bunun bir URI template variable oldugunu belirtiyoruz.

@PathVariable annotation’ini ,@PathVariable(“customerId”) String customerId seklinde kullanabiliriz.
@PathVariable , URI template variable’i okumak icin kullanilir.
@RequestMapping ‘te tanimladigimiz URI template variable ismi ile (customerId) @PathVariable annotation’da kullandigimiz isim ayni olmalidir.
Eger @PathVariable annotation’da bir isim kullanilmazsa bu durumda variable ismiyle ayni isim olur. Yani su kodlar ayni anlama gelmektedir ;

@PathVariable String customerId
@PathVariable("customerId") String customerId

Ornegimizi calistirdigimizda;

@RequestMapping("/pathVariable/{customerId}")
http://localhost:8080/injavawetrust.springmvc/customer/pathVariable/100

Diger metodumuzu test edelim , burada da birden fazla @PathVariable kullaniyoruz.

@RequestMapping("/pathVariable2/{day}/{month}/{year}")
// http://localhost:8080/injavawetrust.springmvc/customer/pathVariable2/18/06/1989

Ornegimizi calistirdigimizda;

@RequestParam

@RequestParam annotation’ini ile query paremeter’lara erisim saglayabiliriz.
Genel format ;

/path?queryParam=value&queryParam2=value2&queryParam3=value3

Ornek metotlarimizi ekleyelim;

CustomerController.java

@RequestMapping("/reqeustParam")
// http://localhost:8080/injavawetrust.springmvc/customer/reqeustParam?name=Levent
public String getCustomerByName(@RequestParam("name") String customerName, Model model) {
	model.addAttribute("message1", "CustomerController#getCustomerByName is called.");
	model.addAttribute("message2", "Customer Name : " + customerName);
	return "07.uri.arguments.view/customer";
}

@RequestMapping("/reqeustParam2")
// http://localhost:8080/injavawetrust.springmvc/customer/reqeustParam2?name=Levent&surname=Erguder
public String getCustomerByNameAndSurname(@RequestParam("name") String customerName,
		@RequestParam("surname") String customerSurname, Model model) {
	model.addAttribute("message1", "CustomerController#getCustomerByNameAndSurname is called.");
	model.addAttribute("message2", "Customer Information: " + customerName + " " + customerSurname);
	return "07.uri.arguments.view/customer";
}	

Ornegimizi calistiralim ;

http://localhost:8080/injavawetrust.springmvc/customer/reqeustParam?name=Levent
http://localhost:8080/injavawetrust.springmvc/customer/reqeustParam2?name=Levent&surname=Erguder

Dikkat edecek olursak kullandigimiz query parameter bilgisi ile @RequestParam(“name”) ve @RequestParam(“surname”) ayni degere sahiptir.

@MatrixVariable

Matrix parameter’lar Spring 3.2 versiyonuyla birlikte Spgring’e dahil oldu.

Matrix variable , complex ve fazla sayidaki HTTP GET , URI argument/parametreleri yonetmek icin kolaylik saglamaktadir.

Matrix parameter’lar , URI ‘da equals (=) karakteriyle tanimlanir ve noktali virgul karakteriyle (;) birden fazla matrix parameter’i ayirabiliriz.
Ayni matrix parameter icin birden fazla deger vermek icin virgul (,) karakterini kullanabiliriz.

Genel format;

path/matrixParam=value1,value2,... valueX;matrixParam2=value1,value2... valueX

Marix Paremeter’lar varsayilan/default olarak kapalidir. (false)
Kullanabilmek icin XML konfigurasyon dosyamizda <mvc:annotation-driven> tag’inda enable-matrix-variable attribute’unu true yapabiliriz.

<mvc:annotation-driven	enable-matrix-variables="true"/>

Ornek metotlarimizi inceleyelim;

	@RequestMapping("/matrixParam/{filter}")
	// http://localhost:8080/injavawetrust.springmvc/customer/matrixParam/phoneNumber=555
	public String getCustomerByFilter1(@MatrixVariable(pathVar = "filter") String phoneNumber, Model model) {
		model.addAttribute("message1", "CustomerController#getCustomerByFilter1 is called.");
		model.addAttribute("message2", "Customer PhoneNumber: " + phoneNumber);
		return "07.uri.arguments.view/customer";
	}

	// http://localhost:8080/injavawetrust.springmvc/customer/matrixParam2/gender=male;city=istanbul
	// http://localhost:8080/injavawetrust.springmvc/customer/matrixParam2/gender=male;city=istanbul,ankara,izmir
	@RequestMapping("/matrixParam2/{filter}")
	public String getCustomerByFilter2(@MatrixVariable(pathVar = "filter") String gender,
			@MatrixVariable(pathVar = "filter") List<String> city, Model model) {
		model.addAttribute("message1", "CustomerController#getCustomerByFilter2 is called.");
		model.addAttribute("message2", "Customer Information: " + gender + " " + city);
		return "07.uri.arguments.view/customer";
	}

	@RequestMapping("/matrixParam3/{filter}")
	// http://localhost:8080/injavawetrust.springmvc/customer/matrixParam3/gender=male;city=istanbul,ankara,izmir
	public String getCustomerByFilter3(@MatrixVariable(pathVar = "filter") Map<String, List<String>> matrixVariables,
			Model model) {
		model.addAttribute("message1", "CustomerController#getCustomerByFilter3 is called.");
		model.addAttribute("message2", "Customer Information: " + matrixVariables);
		return "07.uri.arguments.view/customer";
	}

@MatrixVariable annotation’ininda pathVar attribute kullanabiliriz. @RequestMapping de {filter} seklinde deger belirttik.
Boylece bu URI path’de yazilan bilgilerin Matrix Variable oldugunu belirtiyoruz.

http://localhost:8080/injavawetrust.springmvc/customer/matrixParam/phoneNumber=555

@MatrixVariable annotation’ini List degiskeni ile de kullanabiliriz , boylece birden fazla value bind edilmis olacaktir.

http://localhost:8080/injavawetrust.springmvc/customer/matrixParam3/gender=male;city=istanbul,ankara,izmir

Son olarak , butun Matrix Variable’lari bir Map<String,List<String> icerisinde bind edebiliriz.

http://localhost:8080/injavawetrust.springmvc/customer/matrixParam3/gender=male;city=istanbul,ankara,izmir

XML Configuration

07.uri.arguments.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        ">
	
	<!-- enabled @MatrixVariable , default false! -->
	<mvc:annotation-driven	enable-matrix-variables="true"/>

	<!--Auto-scanning ozelligini aktif ettigimizde bean tanimlamasini xml dosyamizada 
		yapmamiza gerek kalmaz. @Controller  @Service gibi annotation icin yeterli olacaktir. -->
	<context:component-scan base-package="_07.uri.arguments.controller" />
	
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

web.xml
07.uri.arguments.xml dosyamizi web.xml dosyamizda aktif hale getirelim.

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>

<init-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
	<!-- 
	 /WEB-INF/01.appContext.xml			 
	 /WEB-INF/02.00.appContext.xml			
	 /WEB-INF/03.multiActionController.xml
	 /WEB-INF/04.propertiesMethodNameResolver.xml			 	
	 /WEB-INF/05.parameterMethodNameResolver.xml
         /WEB-INF/06.requestMapping.xml         
	-->		
	 /WEB-INF/07.uri.arguments.xml
	</param-value> 
 </init-param>

<load-on-startup>1</load-on-startup>
</servlet>
....

Github kaynak kodlar / source folder
Injavawetrust-springmvc-tutorial

Yazimi burada sonlandiriyorum.
Herkese Bol Javali Gunler dilerim.
Be an oracle man , import java.*;
Levent Erguder
OCP, Java SE 6 Programmer
OCE, Java EE 6 Web Component Developer

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *