Servlet & JSP – 22 – Expression Language – 01

Merhaba Arkadaslar,
Bu yazimda Expression Language konusundan bahsedecegim. Expression Language‘in isimizi nasil kolaylastirdigini anladigimizda cok sevecegiz.

Ornek Uygulama – 1

Oncelikle <jsp:useBean> JSP Action’in yetersiz kaldigi durumu incelemek icin ornek uygulamamiza baslayalim.

Department.java

package _11_ExpressionLanguage.model;

public class Department {

	private int departmentId;
	private String departmentName;

	public Department(int departmentId, String departmentName) {

		this.departmentId = departmentId;
		this.departmentName = departmentName;

	}

	public int getDepartmentId() {
		return departmentId;
	}

	public void setDepartmentId(int departmentId) {
		this.departmentId = departmentId;
	}

	public String getDepartmentName() {
		return departmentName;
	}

	public void setDepartmentName(String departmentName) {
		this.departmentName = departmentName;
	}

	@Override
	public String toString() {
		return "Department [departmentId=" + departmentId + ", departmentName=" + departmentName + "]";
	}
	
	
}

Employee.java

package _11_ExpressionLanguage.model;

public class Employee {
	
	private int empId;
	private String name;
	private Department department;
	
	public Employee() {}
	
	public Employee(int empId, String name, Department department) {
	
		this.empId = empId;
		this.name = name;
		this.department = department;
	}

	public int getEmpId() {
		return empId;
	}

	public void setEmpId(int empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}
	
}

Yeni bir servlet sinifimizi ekleyelim;

WithoutExpressionLanguage.java

package _11_ExpressionLanguage;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import _11_ExpressionLanguage.model.Department;
import _11_ExpressionLanguage.model.Employee;

public class WithoutExpressionLanguage extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		Department department = new Department(100, "Software Department");
		Employee employee = new Employee(1, "Levent Erguder", department);
		req.setAttribute("myemployee", employee);

		RequestDispatcher view = req.getRequestDispatcher("06_EL/withoutEL.jsp");
		view.forward(req, resp);

	}
}

	<servlet>
		<servlet-name>WithoutExpressionLanguage</servlet-name>
		<servlet-class>_11_ExpressionLanguage.WithoutExpressionLanguage</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>WithoutExpressionLanguage</servlet-name>
		<url-pattern>/withoutexpressionlanguage</url-pattern>
	</servlet-mapping>

Servlet sinifinda Employee objesi olusturuldu ve bu obje request scope’a attribute olarak eklendi. Daha sonrasinda withoutEL.jsp dosyasina dispatch islemi yapildi.

withoutEL.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%@page import="_11_ExpressionLanguage.model.Employee"%>

<html>
<body>

	<!--Employee sinifinda Department tipinde instance variable yer almaktadir. (Employee HAS-A Department)
		departmentId ve departmentName alanlarina ulasmak icin request scope'tan myemployee objesini aldik.
	  -->

	<%=((Employee) request.getAttribute("myemployee")).getDepartment().getDepartmentId()%>
	<%=((Employee) request.getAttribute("myemployee")).getDepartment().getDepartmentName()%>


	<br>


	<!-- jsp:useBean ile Employee icerisinden department uzerinden Department beane ulasamayiz!
		jsp:useBean action'i bu konuda yetersiz kalmaktadir. 
	  -->

	<jsp:useBean id="myemployee"
		class="_11_ExpressionLanguage.model.Employee" scope="request">
	</jsp:useBean>

	<jsp:getProperty property="department" name="myemployee" />

</body>
</html>

JSP expression araciligiyla request scope’tan myemployee attribute objemize ulastik sonrasinda cast islemi yaparak departmentName ve departmentId degerlerine ulastik.

<jsp:useBean>sadece bean’in property degerine ulasabilir , ic ice property alanina ulasamayiz!

Yani Employee sinifimizda yer alan instance variable’lara ulasabiliriz (department) fakat department objemizin instance variable alanlarina ulasamayiz.

property=”employee.department” seklinde bir kullanim sekli yoktur !

Expression Language

Expression Language(EL) araciligiyla ic ice(nested) property /instance variable degerlerine ulasabiliriz. Expression Language , Java koduna benzer fakat bazi noktalari Java mantigindan farkli calisir. EL her zaman dolar ile baslar.

${firstThing.secondThing}

Ornek Uygulama – 2

WithExpressionLanguageBean.java

package _11_ExpressionLanguage;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import _11_ExpressionLanguage.model.Department;
import _11_ExpressionLanguage.model.Employee;

public class WithExpressionLanguageBean extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Department department = new Department(100, "Software Department");
		Employee employee = new Employee(1, "Levent Erguder", department);
		req.setAttribute("myemployee", employee);

		RequestDispatcher view = req.getRequestDispatcher("06_EL/withELBean.jsp");
		view.forward(req, resp);
	
	}
}

	<servlet>
	       <servlet-name>WithExpressionLanguageBean</servlet-name>
	       <servlet-class>_11_ExpressionLanguage.WithExpressionLanguageBean</servlet-class>
	</servlet>

	<servlet-mapping>
	       <servlet-name>WithExpressionLanguageBean</servlet-name>
	       <url-pattern>/withexpressionlanguagebean</url-pattern>
	</servlet-mapping>

Employee sinifimiz icin su sekilde departmentName ve departmentId bilgilerine ulasabiliriz ;

withELBean.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<body>

	${myemployee.empId} 
        ${myemployee.name}

	<%--
	
	${myemployee.thereIsNoProperty}
	eger myemployee beani varsa , eger ilgili property yoksa calisma zamaninda exception verir!
	javax.el.PropertyNotFoundException 
		
	 --%>

	<%--eger bean yoksa , property'i olsa da olmasa da hata vermez!. Ekrana bir sey yazmaz !--%>
	${thereIsNoBean.thereIsNoProperty }

	${myemployee.department.departmentName }
	${myemployee.department.departmentId }

</body>
</html>

Nokta Operatoru & Expression Language

Expression Language yapisinda nokta(.) operatoru kullanilmissa , soldaki degisken Map veya bean olmalidir.

${bean.property}
${map.key}

DotOperatorExpressionLanguage.java

package _11_ExpressionLanguage;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DotOperatorExpressionLanguage extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// . operatoru Expression Language icin kullanilabilir.
		// Bu durumda request scope a eklenen Map'e jsp dosyamizdan ulasabiliriz.
		
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		map.put("key3", "value3");

		req.setAttribute("mymap", map);
		
		RequestDispatcher view = req.getRequestDispatcher("06_EL/dotOperatorEL.jsp");
		view.forward(req, resp);

	}
}
	<servlet>
		<servlet-name>DotOperatorExpressionLanguage</servlet-name>
		<servlet-class>_11_ExpressionLanguage.DotOperatorExpressionLanguage</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>DotOperatorExpressionLanguage</servlet-name>
		<url-pattern>/dotoperatorexpressionlanguage</url-pattern>
	</servlet-mapping>

dotOperatorEL.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<body>

    <!-- dot (.) operatoru ile hem Map'e hem de bean property alanlarina ulasabiliriz! -->
	
    ${mymap.key1}
    ${mymap.key2} 
    ${mymap.key3}
    
    <!--mymap var , thereIsNoKey diye bir key yok! Ekrana bir sey yazmaz , hata vermez!  -->
    ${mymap.thereIsNoKey}
    
    <!--thereIsNoMap ve thereIsNoKey yok ! Ekrana bir sey yazmaz , hata vermez!  -->
    
    ${thereIsNoMap.thereIsNoKey} 

</body>
</html>

nokta(.) operatoru ve Expression Language yapisinda ikinci ifade icin Java degisken isimleri kurali gecerlidir. Yani _, $ veya harf ile baslayabilir, rakamla baslayamaz, Java keyword olamaz.

[ ] Operatoru ve Expression Language

[ ] Operatoru , Expression Language yapisinda , nokta operatorunden daha fazla esneklik saglar. Nokta operatorunde ilk ifade Map veya bean olabilir , [ ] operatorunde Map ve bean olabildigi gibi List ve array de olabilir.

[ ] Operatoru Bean ve Map

Nokta operatoru ile ulastigimiz bean property degerlerine ve map value’lerine  [ ] operatoru ile de ulasabiliriz.

BracketBeanAndMapEL.java

package _11_ExpressionLanguage;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import _11_ExpressionLanguage.model.Department;
import _11_ExpressionLanguage.model.Employee;

public class BracketBeanAndMapEL extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	
		Department department = new Department(100, "Software Department");
		Employee employee = new Employee(1, "Levent Erguder", department);
		req.setAttribute("myemployee", employee);
		
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		map.put("key3", "value3");

		req.setAttribute("mymap", map);

		RequestDispatcher view = req.getRequestDispatcher("06_EL/bracketBeanAndMapEL.jsp");
		view.forward(req, resp);
	}
	
}

bracketBeanAndMapEL.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<body>

<%--tek tirnak ya da cift tirnak kullanilabilir ! --%>
${myemployee["empId"]} 
${myemployee['name']}
${myemployee['department']["departmentId"]}
${myemployee["department"]["departmentName"]}

<%--
	yukaridaki ifaleler nokta(dot) operatoru ile su ifadelere karsilik gelmektedir. 
	
	${myemployee.empId} 
	${myemployee.name}
	${myemployee.department.departmentName }
	${myemployee.department.departmentId }

 --%>


<br/>

${mymap["key1"]}
${mymap["key2"]}
${mymap["key3"]}

<%--
    yukaridaki mymap ifadeleri nokta(dot) operatoru ile su ifadelere karsilik gelmektedir.
	
    ${mymap.key1}
    ${mymap.key2} 
    ${mymap.key3}

 --%>


</body>
</html>

[ ] Operatoru ve Arrays & List

BracketArrayAndListEL.java

package _11_ExpressionLanguage;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BracketArrayAndListEL extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String[] strArray = { "str1", "str2", "str3" };
		req.setAttribute("myArray", strArray);

		List list = new ArrayList();
		list.add("list element1");
		list.add("list element2");
		req.setAttribute("myList", list);

		RequestDispatcher view = req.getRequestDispatcher("06_EL/bracketArrayAndListEL.jsp");
		view.forward(req, resp);

	}

}
	<servlet>
		<servlet-name>BracketArrayAndListEL</servlet-name>
		<servlet-class>_11_ExpressionLanguage.BracketArrayAndListEL</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>BracketArrayAndListEL</servlet-name>
		<url-pattern>/bracketarrayandlistel</url-pattern>
	</servlet-mapping>

bracketArrayAndListEL.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<html>
<body>

	<%--[] operatoru ile array ve list elemanlarina ulasabiliriz. 
	dot operatoru ile bunu yapamayiz! --%>
	
	<%--index 0 dan baslar. 0 , "1" ya da '2' seklinde yapabiliriz. --%>
	
	${myArray[0]} 
	${myArray["1"]}
        ${myArray['2']}

	<br> 
	
	<%--list elemanlarina da array elemanlari gibi ulasabiliriz. --%>
	
	${myList[0]} 
	${myList["1"]}

</body>
</html>

Dizi indeks degerini tam sayi seklinde verebildigimiz gibi “1” ya da ‘2’ seklinde de verebiliriz. Tabi burada indeksi tamsayiya parse edilebilecek sekilde deger vermemiz gerekir. Aksi halde java.lang.NumberFormatException hatasina neden olur.

Dikkat edecek olursak array’e ulastigimiz gibi list’e de ulastik. Unutmayalim Expression Language Java kodu degildir !

Array veya List icin index degeri String literal olabilir. Tamsayi degerine parse edilebilecek String literal sorunsuz calisir.

Expression Language Evaluated

[ ] arasinda ” “(quote) isareti yoksa , Container bu isimde bir attribute olup olmadigini arayacaktik. request scope’a EvaluatedString adinda bir String attribute ekleyelim.

req.setAttribute("EvaluatedString", "key1");

Degeri key1 oldugu icin value1 degerine ulasabiliriz;

${mymap[EvaluatedString]}

EvaluatedEL.java

package _11_ExpressionLanguage;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EvaluatedEL extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("key1", "value1");
		map.put("key2", "value2");
		map.put("key3", "value3");

		req.setAttribute("mymap", map);
		req.setAttribute("EvaluatedString", "key1");

		String[] array = { "key2" };
		req.setAttribute("myarray", array);

		RequestDispatcher view = req.getRequestDispatcher("06_EL/evaluated.jsp");
		view.forward(req, resp);

	}
}

	<servlet>
		<servlet-name>EvaluatedEL</servlet-name>
		<servlet-class>_11_ExpressionLanguage.EvaluatedEL</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>EvaluatedEL</servlet-name>
		<url-pattern>/evaluatedel</url-pattern>
	</servlet-mapping>

evaluated.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"
%>

<html>
<body>

	<%--EvaluatedString " " karakterleri arasinda olmadigi icin 
	Container EvaluatedString isimli attribute var mi diye bakacaktir ! --%>

	<%--EvaluatedString isimli attribute mevcut bu nedenle degeri kullanilacaktir "key1" --%>
	${mymap[EvaluatedString]}

	<%--
	Yukaridaki ifade bu ifadeye donusturulecektir.
	${mymap["key1"]}
	 --%>

	${mymap[myarray[0]] }

</body>
</html>

Ic ice [ ] yapisini kullanabiliriz.  Yeni bir request scope attribute ekleyelim;

 String[] array= {"key2"};
 req.setAttribute("myarray", array);
${mymap[myarray[0]] }

myarray[0] ,  “key2” string degerine donusur.

${mymap["key2"]


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, PDF & Email

Leave a Reply

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