Function tags

Function tags provide many functions we can use to perform common operations, most of which are for String manipulation, such as String COncatenation, Split String, etc. 

Here are some tags that you can refer to before looking at examples. 

 

Tag Description
fn:contains() It is used to test if an input string containing the specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case insensitive way.
fn:endsWith() It tests whether an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of the first occurrence of a specified substring.
fn:trim() It removes the blank spaces from both ends of a string.
fn:startsWith() It is used to check whether the given string starts with a particular string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lowercase.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:substringAfter() It returns the subset of the string after a specific substring.
fn:substringBefore() It returns the subset of the string before a specific substring.
fn:length() It returns the number of characters inside a string or items in a collection.
fn:replace() It replaces all the occurrences of a string with another string sequence.

Example

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<style>
@import url('https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap');
</style>

<html>
<head><title>Function Tag</title></head>
<body style="font-family: 'Josefin Sans', sans-serif;">
<c:set var="str1" value="Happy days!"/>
<c:set var="str2" value="app" />
<c:set var="tokens" value="1,2,3,4,5,6,7,8,9,10" />

length(str1) = ${fn:length(str1)} <br>
toUpperCase(str1) = "${fn:toUpperCase(str1)}" <br>
toLowerCase(str1) = "${fn:toLowerCase(str1)}" <br>
substring(str1, 3, 6) = "${fn:substring(str1, 3, 6)}" <br>
substringAfter(str1, str2) = "${fn:substringAfter(str1, str2)}" <br>
substringBefore(str1, str2) = "${fn:substringBefore(str1, str2)}" <br>
trim(str1) = "${fn:trim(str1)}" <br>
replace(str1, src, dest) = "${fn:replace(str1, " ", "-")}" <br>
indexOf(str1, str2) = "${fn:indexOf(str1, str2)}" <br>
startsWith(str1, str2) = "${fn:startsWith(str1, 'Fun')}" <br>
endsWith(str1, str2) = "${fn:endsWith("Using", str1)}" <br>
contains(str1, str2) = "${fn:contains(str1, str2)}" <br>
containsIgnoreCase(str1, str2) = "${fn:containsIgnoreCase(str1, str2)}" <br>

<c:set var="array" value="${fn:split(tokens, ',')}" />

join(array, "-") = "${fn:join(array, "-")}" <br>
escapeXml(str1) = "${fn:escapeXml(str1)}" <br>

</body>
</html>

SQL tags

SQL tags support interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags, we can run database queries. We first need to create a table with the totoro account to demonstrate. 

create table test(
	num number,
	name varchar2(10),
	primary key(num) );

In the code, first, we insert the data and print out the data with the select SQL.

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<html>
<head>
<title>JSTL sql Tags</title>
</head>
<body>

	<sql:setDataSource var="conn" driver="oracle.jdbc.driver.OracleDriver"
		url="jdbc:oracle:thin:@localhost:1521:xe" user="totoro"
		password="totoro123" />

	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (1, 'Meadow')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (2, 'Dodo')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (3, 'Forest')
</sql:update>
	<sql:update dataSource="${conn}">
	INSERT INTO test (num, name) VALUES (4, 'Jenny')
</sql:update>

	<sql:query var="rs" dataSource="${conn}">
	SELECT * FROM test WHERE name=?
	<sql:param>Meadow</sql:param>
	</sql:query>

	<c:forEach var="data" items="${rs.rows}">
		<c:out value="${data['num']}" />
		<c:out value="${data['name']}" />
		<br>
	</c:forEach>

</body>
</html>

Search the table with select * from test; , you will see the inserted data.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

Internationalization tags are the second most used tags in JSTL. The most used tags are core tags, as you can refer to in my last post.

2022.09.17 - [JSP] - JSP) JSTL (JSP Standard Tag Library) - Core tags

 

Internationalization tags are related to numbers, dates, and timezone. The example tag with the URI is like this : 

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

The prefix value is "fmt" and the URI ends with "fmt" which refers to the internationalization tag. 

For your better understanding, let us look through some simple examples. 

 

numberFormat Tag

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

<html>
<head><title>numberFormat Tag</title></head>
<body>

<c:set var="now" value="<%= new java.util.Date() %>" />
${now }<br>
<c:out value="${now }"/><br>

<fmt:formatDate value="${now}" type="date" dateStyle="full" /> <br> <!-- in detail -->
<fmt:formatDate value="${now}" type="date" dateStyle="short" /> <br> <!-- simple -->
<fmt:formatDate value="${now}" type="time" /> <br>
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" /> <br>
<fmt:formatDate value="${now}" pattern="z a h:mm" /> <br><br> <!-- z: timezone a: am/pm -->
<fmt:formatDate value="${now}" pattern="MM/dd/yy EEEE h:mm a z"/><br>
</body>
</html>

timeZone tag

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

<html>
<head><title>timeZone Tag</title></head>
<body>

<c:set var="now" value="<%= new java.util.Date() %>" />


<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />

<br>
<fmt:timeZone value="Hongkong">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>

<fmt:timeZone value="America/New_York">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>

<fmt:timeZone value="Asia/Seoul">
<fmt:formatDate value="${now}" type="both" 
                dateStyle="full" timeStyle="full" />
</fmt:timeZone>
<br>


</body>
</html>

formatNumber Tag

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

<html>
<head>
<title>formatNumber Tag</title>
</head>
<body>

	<c:set var="price" value="10000" />
	<fmt:formatNumber value="${price}" type="number" var="numberType" />
	Number: ${numberType}  <!-- Variable name -->
	<br> KRW:
	<fmt:formatNumber value="${price}" type="currency" currencySymbol="\\" />
	<br> USD:
	<fmt:formatNumber value="${price}" type="currency" currencySymbol="$" />
	<br> Percentage:
	<fmt:formatNumber value="${price}" type="percent" groupingUsed="true" />
	<br> Percentage:
	<fmt:formatNumber value="${price}" type="percent" groupingUsed="false" />
	<br> Pattern:
	<fmt:formatNumber value="${price}" pattern="00000000.00" />

</body>
</html>

 

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Function tags / SQL tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

As we discussed, Model 2 consists of Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library). In this post, we will learn about JSTL. 

JSLT, itself stands for JSP Standard Tag Library. So what do we need to do first? 

To download the library!

 

First, go to apache taglibs.

https://tomcat.apache.org/taglibs/standard/

And click the download. 

That's actually it for the configuration!

 

These are the five types of tags in JSTL. Among then, we use mostly the core and Internationalization library.

Tags Description Example
Core Provide support for iteration, conditional logic, catch exception, url, forward or redirect response etc. <%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
Internationalization  For formatting of Numbers, Dates and i18n support through locales and resource bundles. <%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
SQL Provide support for interaction with relational databases such as Oracle, MySql etc. Using JSTL SQL tags we can run database queries. <%@ taglib uri="https://java.sun.com/jsp/jstl/sql" prefix="sql" %>
XML
Used to work with XML documents such as parsing XML, transforming XML data, and evaluating XPath expressions. <%@ taglib uri="https://java.sun.com/jsp/jstl/xml" prefix="x" %>
Functions 
Provide many functions that we can use to perform common operation, most of them are for String manipulation such as String Concatenation, Split String etc.  <%@ taglib uri="https://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Here are some most used JSTL Core Tags and examples of them.

Tags Description
c:set Sets the result of an expression under evaluation in a 'scope' variable.
c:if Conditional tag used for testing the condition and display the body content only if the expression evaluates is true.
c:choose Simple conditional tag that includes its body content if the evaluated condition is true.
c:forEach Repeats the nested body content for fixed number of times or over collection.
c:import Retrieves relative or an absolute URL and display the contents to either a String in 'var',a Reader in 'varReader' or the page.
c:out Displays the result of an expression, similar to the way <%=...%> tag work.

 

Set tag / Remove tag

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

<c:set var="num1" value="${20}" />
<c:set var="num2">
10.5
</c:set>
<c:set var="today" value="<%= new java.util.Date() %>" />

<html>
	<head>
		<title>set Tag & remove Tag</title>
	</head>

	<body>
		Variable num1 = ${num1} <br>
		Variable num2 = ${num2} <br>
		num1 + num2 = ${num1 + num2} <br>
		Today is ${today}.

		<c:remove var="num1" scope="page" />

		<p>
		num1 after deletion = ${num1} <br>
		num1 + num2 after deletion = ${num1 + num2}
	</body>
</html>

As you can see above, EL is used to print out in JSTL, which means you can use EL by itself, but JSTL has to collaborate with EL. 

You need to use the request object to use the EL tag.

	<%
		String str = "JSP Variable";
		request.setAttribute("st", str); 
	%>
		Variable1: str1 = <%=str %> <br>	<!-- Printed -->
		Variable2: str2 = ${str} <br> 		<!-- Not printed -->
		Variable3: str3 = ${st} <br> 		<!-- Printed -->

if tag

if tag is to process a single condition.

ifTagForm.jsp

<%@ page contentType = "text/html; charset=utf-8" %>

<html>	
	<body>
	<form method=post action=ifTag.jsp>
	Name <input type=text name=name><br>
	Age <input type=text name=age><br>
	<input type=submit value="Submit">
	</form>
	</body>
</html>

ifTag.jsp

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

<c:if test="true">
If the test value is "true", it always runs. <br>
</c:if>

<c:if test="${param.name == 'Meadow' }">
 Hello ${param.name }, welcome! <br>
</c:if>

<c:if test="${param.age >= 18 }">
You are an adult! haha!<br>
</c:if>

choose tag 

choose ~ when ~ otherwise tag is used when we process multiple conditions.

It is the same as switch ~ case ~ default in java.

If there is a condition that the value meets, it will execute the tag and stop execution. 

ifTagFrom.jsp

<%@ page contentType = "text/html; charset=utf-8" %>

<html>	
	<body>
	<form method=post action=chooseTag.jsp>
	Name <input type=text name=name><br>
	Bloodtype <input type=text name=bloodtype><br>
	<input type=submit value="Submit">
	</form>
	</body>
</html>

chooseTag.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
	<ul>
		<c:choose>
			<c:when test="${param.name == 'Meadow' }">
				<li>Your name is ${param.name }.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'O' }">
				<li>Your bloodtype is O! People with type O blood less
					susceptible to malaria.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'A' }">
				<li>Your bloodtype is A! People with type A blood are more
					likely to develop stomach cancer.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'AB' }">
				<li>Your bloodtype is AB! People with type AB blood are much
					more likely to develop cognitive issues.</li>
			</c:when>
			<c:when test="${param.bloodtype == 'B' }">
				<li>Your bloodtype is B! About 9% of the population have B
					positive blood.</li>
			</c:when>
			<c:otherwise>
				<li>Your name is not Meadow, and there is no such bloodtype. 
				</li>
			</c:otherwise>
		</c:choose>
	</ul>

</body>
</html

If I enter the name "Meadow", it will stop executing at the first condition since it meets the condition. 

 

If I enter the other name and the blood type(O,A,AB, or B), it will execute that condition.

catch tag / out tag

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>JSTL core Library Example 1</title>
</head>
<body>
	<c:set var="test" value="Hello JSTL!" />
	<h3>
		Using &lt;c:set&gt; :
		<c:out value="${test}" />
	</h3>
	<c:remove var="test" />
	<h3>
		Using &lt;c:remove&gt; :
		<c:out value="${test}" />
	</h3>

	<c:catch var="err">
		<%=10 / 0%>
	</c:catch>
	<h3>
		An error caught by &lt;c:catch&gt;:
		<c:out value="${err}" />
	</h3>

	<c:if test="${5<10}">
		<h3>5 is lesser than 10.</h3>
	</c:if>
	<c:if test="${6+3==9}">
		<h3>6 + 3 equals 9.</h3>
	</c:if>

	<c:choose>
		<c:when test="${5+10==50}">
			<h3>5+10 equals 50.</h3>
		</c:when>

		<c:otherwise>
			<h3>5+10 not equal 50.</h3>
		</c:otherwise>
	</c:choose>
</body>
</html>

forEach tag

It is like a loop in java, while the format is different from it. 

There are two big types in this forEach tag. Type 1 is more used than the other. Let us look at the example codes.

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	java.util.HashMap mapData = new java.util.HashMap();
	mapData.put("name", "Meadow");
	mapData.put("today", new java.util.Date());
%>
<c:set var="intArray" value="<%=new int[] { 1, 2, 3, 4, 5 }%>" />
<c:set var="map" value="<%=mapData%>" />
<html>
<head>
<title>forEach Tag</title>
</head>
<body>
	<h4>Sum of odd integers from 1 to 100.</h4>
	<c:set var="sum" value="0" />
	<c:forEach var="i" begin="1" end="100" step="2">
		<c:set var="sum" value="${sum + i}" />
	</c:forEach>
	Result = ${sum}

	<h4>4 Times table</h4>
	<ul>
		<c:forEach var="i" begin="1" end="9">
			<li>4 * ${i} = ${4 * i}
		</c:forEach>
	</ul>

	<h4>Array - Datatype int</h4>

	<c:forEach var="i" items="${intArray}" begin="2" end="4">
    [${i}]
</c:forEach>

	<h4>Map</h4>

	<c:forEach var="i" items="${map}">
    ${i.key} = ${i.value}<br>
	</c:forEach>
	<br>
	<br>

	<%
		List list = new ArrayList();
	list.add("Toronto");
	list.add("Halifax");
	list.add("Vancouver");
	list.add("Calgary");
	list.add("Airdrie");
	list.add("Winnipeg");
	list.add("Yellowknife");

	request.setAttribute("slist", list);
	%>
	<!-- Type 1 -->
	<c:forEach var="s" items="${slist}">
		${s} <br>
	</c:forEach>
	<br>
	<br>

	<%
		// Origianl code
	List li = (List) request.getAttribute("slist");
	for (int i = 0; i < li.size(); i++) {
		String str = (String) li.get(i);
		out.println(str + "<br>");
	}
	%><br><br>
	
	<!-- Type 2 -->
	<c:set var="s1" value="<%=list %>"/>
	<c:forEach var="s2" items="${s1}">
		${s2} <br>
	</c:forEach>
</body>
</html>

Other tags(not used a lot)

forTokens tag

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

<html>
<head><title>forTokens tag</title></head>
<body>

delims= ",." :<br>
<c:forTokens var="token" 
             items="Red,Orange.Yellow.Green,Blue,Navy.Purple"
             delims=",.">
${token} 
</c:forTokens>

</body>
</html>

forEach tag / forTokens tag

<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>JSTL core Library Example</title>
</head>
<body>
	<c:forEach var="test" begin="1" end="10" step="2">
		<b>${test}</b>&nbsp;
</c:forEach>
	<br>
	<c:forTokens var="alphabet" items="a,b,c,d,e,f,g,h,i,j,k,l,m,n"
		delims=",">
		<b>${alphabet}</b>&nbsp;
</c:forTokens>
	<br>
	<c:set var="data" value="Banana,Orange,Melon" />
	<c:forTokens var="varData" items="${data}" delims=",">
		<b>${varData}</b>&nbsp;
</c:forTokens>
</body>
</html>

So far, we have learned about Core tags, which are the most used, in the next post, we will see the second most used ones, internationalization tags.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Function tags / SQL tags  (0) 2022.09.19
JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15

To develop with the Model2 MVC patterns, we need to know Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library), and we already covered the Java Servlet class in the last posts. If you want to go check out, please click the link below.

2022.09.15 - [JSP] - JSP) Model2 - Java Servlet 1

2022.09.16 - [Codes & Projects] - JSP) Model2 - Java Servlet 2

 

 

In this post, we will discuss Expression Language, which we use instead of Expression tags in the model2, we use Expression language. It looks different from the expression tags we have been using, but once we get used to it, it will be easier and simpler.

 

For example, param is used as${param.name} and sessionScope is used as${sessionScope.id}

 

For a better understanding, let us look through the examples.

 

Example 1

Arithmetic Operators

To print out the EL on the browser, you must use "\". 

  <TR>
    <TD>\${2 + 5}</TD>
    <TD>${2 + 5}</TD>
  </TR>

To divide, you can use either "/" or "div" and the result will be the same. "mod" is to get the remainder.

  <TR>
    <TD>\${4/5}</TD>
    <TD>${4/5}</TD>
  </TR>
  <TR>
    <TD>\${5 div 6}</TD>
    <TD>${5 div 6}</TD>
  </TR>
  <TR>
    <TD>\${5 mod 7}</TD>
    <TD>${5 mod 7}</TD>
  </TR>

Comparison Operators

"<" is same as "gt"(greater) and ">" is same as "le"(less).

  <TR>
    <TD>\${2 < 3}</TD>
    <TD>${2 < 3}</TD>
  </TR>
  <TR>
    <TD>\${2 gt 3}</TD>
    <TD>${2 gt 3}</TD>
  </TR>
  <TR>
    <TD>\${3.1 le 3.2}</TD>
    <TD>${3.1 le 3.2}</TD>
  </TR>

Conditional Operators

<TR>
    <TD>\${(5 > 3) ? 5 : 3}</TD>
    <TD>${(5 > 3) ? 5 : 3}</TD>
  </TR>

Implicit Objects

  <TR>
    <TD>\${header["host"]}</TD>
    <TD>${header["host"]}</TD>
  </TR>
  <TR>
    <TD>\${header["user-agent"]}</TD>
    <TD>${header["user-agent"]}</TD>
  </TR>

Example 2

Processing parameter value

<%@ page contentType="text/html;charset=utf-8"%>
<% request.setCharacterEncoding("utf-8");%>

<HTML>
<HEAD>
<TITLE>EL Example2</TITLE>
</HEAD>

<BODY>

<H3>Processing parameter value</H3>
<P>
<FORM action="eLEx2.jsp" method="post">
   Name : <input type="text" name="name" value="${param['name']}">
          <input type="submit" value="Submit">
</FORM>

<P>
Hello <%=request.getParameter("name") %>, how are you today? <br>
Would you like to have a cup of tea, ${param.name}?

</BODY>
</HTML>

The followings bring the same result, but as you can see, EL is simpler than JSP expression tag. 

You can also use ${param['name']}.

Hello <%=request.getParameter("name") %>, how are you today? <br>
Would you like to have a cup of tea, ${param.name}?
${param['name']}

There are several ELs that you can use simpler way.

Object EL JSP expression tag
param ${param.name} <%=request.getParameter("name"%>
sessionScope ${sessionScope.id} <%=session.getAttribute("id")%>
requestScope ${requestScope.page} <%=request.getAttribute("page")%>

 

Example 3

Product.java

package jspbook;

public class Product {

	// Products (Array)
	private String[] productList = {"item1","item2","item3","item4","item5"};
	
	// Variables
	private int num1 = 10;
	private int num2 = 20;
	
	public int getNum1() {
		return num1;
	}

	public int getNum2() {
		return num2;
	}

	public String[] getProductList() {
		return productList;
	}
}

productList.jsp

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

<html>

	<head>
		
<meta charset="utf-8">

		<title>EL Example 3</title>

	</head>

	<body>

	<center>
		<H2>Product list</H2>
		<HR>
	<form method="post" action="productSel.jsp">
		<jsp:useBean id="product" class="jspbook.Product" scope="session"/>
		<select name="sel">
			<%
			for(String item : product.getProductList()) {
				out.println("<option>"+item+"</option>");
			}
			%>
		</select>
		<input type="submit" value="Select"/>
	</form>
	</center>
</body>

</html>

productSel.jsp

<%@page import="jspbook.Product"%>
<%@ page language="java" contentType="text/html; charset=utf-8"%>

<html>
	<head>		
		<meta charset="utf-8">
		<title>EL Example 3</title>
	</head>
	<body>
		<center>
		<H2>Selected product</H2>
		<HR>
		1. (EL) You selected : ${param.sel} <br> 
		1. (Expression tag) You selected : <%=request.getParameter("sel") %><br>
		
		2. num1 + num2 = ${product.num1+product.num2} <br>
<%
	Product pro = (Product) session.getAttribute("product");
%>
		2.(Expression tag) num1 + num2 = <%=pro.getNum1() + pro.getNum2()%>
		</center>
	</body>
</html>

As you explored in this post, Expression Language is often simpler, so as we learn, we will use it more often than the expression tags of the JSP.

'Java > JSP' 카테고리의 다른 글

JSP) JSTL - Internationalization tags  (0) 2022.09.19
JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31

In the last post, we talked about the difference between Model1 and Model2. 

To know more about Model2, we need to know Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library). First, let us discuss about Java Servlet Class.

 

Java Servlet Class
Java Servlet Class means all the web programs that is written in Java language. This class can include the HTML, and JavaScript codes and it can print out the codes on the web browser right away. 

 

To create the Java Servlet Class in Eclipse, Java EE has to be selected as a perspective. 

In the new dynamic web project, in the src folder, create a new Servlet. 

The class name and the file name will be the same. As you can see, its superclass is automatically designated as the HttpServlet class, so this class will be inherited as extends.

Since we don't need any constructors, we are ticking out the box, and we will leave others as they are. 

Then, you will see this codes with doGet method and doPost method, as we checked the box.

package send;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet(description = "My first Java Servlet", urlPatterns = { "/HelloWorld" })
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

When you fun the code, you will see this on the browser. 

Here, this is called Annotation.

Let us change the code a bit.

package send;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet(description = "My first Java Servlet", urlPatterns = { "/HelloWorld" })
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello World!</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hi there!!</h1>");
        out.println("</body>");
        out.println("</html>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 Before running the code, if there are other files with the same annotation, you need to close them to run this well. 

To encode, in the jsp files, we used the contentType and the charset, whereas, in this servlet class, we use setContentType.

response.setContentType("text/html;charset=utf-8");

 

 

For better understanding, this time, let us make another servlet class with HTML file. 

 

Example 1

 

Method.java

doPost class is connected to the Call with get method, and the doGet class is connected to the Call with post method.

package send;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Method
 */
@WebServlet("/Method")
public class Method extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<h1>Processed with a get method.</h1>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<h1>Processed with a post method.</h1>");
	}

}

Method.html

The action has to correspond to the annotation(@) in the servlet class.

<html lang="en">
<head>
	<meta charset="utf-8">
</head>
<body>
	<!-- action = "/Project name/Servlet file name"  
		No package name needed.
	-->
	<form method="get" action="/jsppro/Method">
		<input type="submit" value="Called with get method">
	</form>

	<form method="post" action="/jsppro/Method">
		<input type="submit" value="Called with post method">
	</form>
</body>
</html>

 

Example 2

 

Let us exercise more with a little bit more complicated example. 

QueryString.html

<html lang="en">
 <head>
  <meta charset="utf-8">
 </head>
 <body>

<form method="get" action="/jsppro/QueryString">
ID : <input type="text" name="id"  size="20"> <br>
Password : <input type="password" name="pw"  size="20"> <br>
Name : <input type="text" name="name"  size="20"> <br>
Group : <input type="radio" name="group"  value="member"> Member
           <input type="radio" name="group"  value="Manager"> Manager<br>
Phone : <select name="phone1">
                 <option value="010" selected> 010 </option>    
                 <option value="011"> 011 </option>    
                 <option value="016"> 016 </option> 
                 <option value="017"> 017 </option>    
                 <option value="018"> 018 </option>    
                 <option value="019"> 019 </option>
           </select>              
    -      <input type="text" name="phone2" size="4" maxlangth="4">
    -
			<input type="text" name="phone3" size="4" maxlangth="4"><br>
			<input type="submit" value="Sumbit">
		</form>
	</body>
</html>

QueryString.java

package send;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class QueryString
 */
@WebServlet(description = "Exercise", urlPatterns = { "/QueryString" })
public class QueryString extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		response.setContentType("text/html;charset=utf-8");

		PrintWriter out = response.getWriter();
		String id = "", name = "", vclass = "", phone1 = "", phone2 = "", phone3 = "";
		id = request.getParameter("id");
		name = request.getParameter("name");
		vclass = request.getParameter("group");
		phone1 = request.getParameter("phone1");
		phone2 = request.getParameter("phone2");
		phone3 = request.getParameter("phone3");
		
		out.println("<html><head></head><body>");
		out.println("The data that you inserted is processed with [GET method].<br> ID : <b>");
		out.println(id);
		out.println("</b><br> Name : <b>");
		out.println(name);
		out.println("</b><br> Group : <b>");
		out.println(vclass);
		out.println("</b><br> Phone : <b>");
		out.println(phone1);
		out.println("-");
		out.println(phone2);
		out.println("-");
		out.println(phone3);
		out.println("</b><br><a href='javascript:history.go(-1)'>Go back</a>");
		out.println("</body></html>");
		out.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		response.setContentType("text/html;charset=utf-8");

		request.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		String id = "", name = "", vclass = "", phone1 = "", phone2 = "", phone3 = "";
		id = request.getParameter("id");
		name = request.getParameter("name");
		vclass = request.getParameter("group");
		phone1 = request.getParameter("phone1");
		phone2 = request.getParameter("phone2");
		phone3 = request.getParameter("phone3");
		
		out.println("<html><head></head><body>");
		out.println("The data that you inserted is processed with [POST method].<br> ID : <b>");
		out.println(id);
		out.println("</b><br> Name : <b>");
		out.println(name);
		out.println("</b><br> Group : <b>");
		out.println(vclass);
		out.println("</b><br> Phone : <b>");
		out.println(phone1);
		out.println("-");
		out.println(phone2);
		out.println("-");
		out.println(phone3);
		out.println("</b><br><a href='javascript:history.go(-1)'>Go back</a>");
		out.println("</body></html>");
		out.close();
	}

}

If you change the method from "get" to "post" it will change like this below.

Now, we will add the DTO and DAO classes. We also have to edit a little bit of QueryString.java.

We add this(below) is in the doPost class,

String pw = "";

this(below) to connect to the DTO and DAO.

QueryDTO query = new QueryDTO();
query.setId(id);
query.setPw(pw);
query.setName(name);
query.setVclass(vclass);
query.setPhone(phone1+"-"+phone2+"-"+phone3);
		
QueryDAO dao = QueryDAO.getInstance();
dao.insert(query);		//Sign up

 

QueryDTO.java

package send;

public class QueryDTO {

	private String id;
	private String pw;
	private String name;
	private String vclass;
	private String phone;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getVclass() {
		return vclass;
	}
	public void setVclass(String vclass) {
		this.vclass = vclass;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	
}

QueryDAO.java

package send;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class QueryDAO {

	private static QueryDAO instance = new QueryDAO();
	
	public static QueryDAO getInstance(){
		return instance;
	}
	
	public void insert(QueryDTO dto){
		Connection conn = null;
		PreparedStatement pstmt = null;
		String url = "jdbc:oracle:thin:@localhost:1521:xe";
		String sql="";
		
		try{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection(url,"totoro","totoro123");
			
			sql="insert into query values(?,?,?,?,?)";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, dto.getId());
			pstmt.setString(2, dto.getPw());
			pstmt.setString(3, dto.getName());
			pstmt.setString(4, dto.getVclass());
			pstmt.setString(5, dto.getPhone());
			pstmt.executeUpdate();		
			
		}catch(Exception e){
			
		}finally{
			if(pstmt != null){
				try{
					pstmt.close();
				}catch(Exception e){					
				}
			}
			if(conn != null){
				try{
					conn.close();
				}catch(Exception e){					
				}
			}			
		}
		
	}
	
}

Now, we will create a table on Oracle to connect the database and save the data. 

create table query(
		id varchar2(20),
		pw varchar2(20),
		name varchar2(20),
		vclass varchar2(20),
		phone varchar2(30));

 

Checkboxes

Here is an example of dealing with the checkboxes in the servlet.

multiPara.html

<html lang="en">
 <head>
  <meta charset="UTF-8">
</head>
<body>
<form method="post" action="/jsppro/multiPara">
<h2>Programming Languages</h2><br>
Which languages can you use for programming?<br>
<hr>
 <input type="checkbox" name="plang" value="C"> c
 <input type="checkbox" name="plang" value="Java"> Java
 <input type="checkbox" name="plang" value="JavaScript"> JavaScript<br>
 <input type="checkbox" name="plang" value="C++"> C++
 <input type="checkbox" name="plang" value="Python"> Python
 <input type="checkbox" name="plang" value="Assembly"> Assembly<br>  
 <input type="submit" value="Submit"> 
</form>
</body>
</html>

multiPara.java

Since the "post" method is requested, it will be processed in the doPost method.

package send;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class multiPara
 */
@WebServlet(description = "Exercise", urlPatterns = { "/multiPara" })
public class multiPara extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String[] item;

		item = request.getParameterValues("plang");
		out.println("Selected languages are");
		
		try {
			for (int i = 0; i < item.length; i++)
				out.println(" : " + item[i]);
//				out.println(" : " + HanConv.toKor(item[i]));
		} catch (Exception e) {
			out.println(" nothing.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		String[] item;

		item = request.getParameterValues("plang");
		out.println("Selected languages are");
		
		try {
			for (int i = 0; i < item.length; i++)
				out.println(" : " + item[i]);
//				out.println(" : " + HanConv.toKor(item[i]));

		} catch (Exception e) {
			out.println(" nothing.");
		}
	}

}

 

 

'Java > JSP' 카테고리의 다른 글

JSP) JSTL (JSP Standard Tag Library) - Basic / Core tags  (0) 2022.09.17
JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31
JSP) JavaBean  (0) 2022.08.31

So far, in JSP, what we do was Model1, and in this post, we will explore Model2.

The biggest difference between Model1 and Model2 is whether there is Servlet(Controller class) or not. 

Here are the architectures of each model. 

Source: Oracle
Source: Oracle

In Model1, we use only JSP, JSP, or Java Bean. It is relatively easy to learn and fast to develop. 

However, it can be confusing on the JSP page since the presentation, and business logic are on one page. For this reason, it is sometimes hard to separate the developer's and the designer's work. 

 

On the other hand, Model2 separates the roles of the application into model, view, and controller. It is certainly easy to maintain and expand the service and split the responsibility of each developer and the designer. However, as it is better arranged than Model1, the projects often take longer. Moreover, the programmers must understand the MVC(Model-View-Controller) structure. 

 

So, what is MVC? 

MVC is a development methodology that separates the application into three parts: Model, View, and Controller. 

Model process the application's data by using the service and DAO class. View process the user interface, normally designers develop this part, consisting of EL(Expression Language) and JSTL(JSP Standard Tag Library). The controller adjusts the flow between the Model and View with the Java Servlet. 

To know better about the MVC patterns, we first need to study Java Servlet, EL(Expression Language), and JSTL(JSP Standard Tag Library) and in the next posts, we will study more about them.

'Java > JSP' 카테고리의 다른 글

JSP) EL(Expression Language)  (0) 2022.09.16
JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31
JSP) JavaBean  (0) 2022.08.31
JSP) Action tags - include  (0) 2022.08.31

It would help if you had some place to store your data on any website or webpage. Even if you made a perfect website with JSP, unless you connect it to DB, it wouldn't have any function to store the users' information. So, It is essential to know how to connect the two sources. 

 

There are three significant ways to connect JSP and Oracle: JDBC(Java DataBase Connectivity), DBCP(DataBase Connection Pool), and ORM(Object Relational Mapping) framework. iBatis, MyBatis, hibernate, and JPA are ORM frameworks. Among them, we will discuss JDBC first.

 

JDBC

 

JDBC Configuration

To connect to Oracle, you first need a JDBC Driver. Depending on the version set on your PC, I will download an ojdbc6.jar

After then, we will test if the connection is successfully run or not. Oracle Smith account must be connected if you want to connect them successfully. 

To connect Oracle

<%@ page contentType="text/html; charset=euc-kr" %>
<%@ page import="java.sql.*" %>

<%
  Connection con=null;

  try{

/**************** Oracle *****************************/
    String driver = "oracle.jdbc.driver.OracleDriver";  	

    String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:xe";
    String dbId = "scott";
    String dbPass = "tiger";
/*****************************************************/


	Class.forName(driver);
	con=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	out.println("Successfully connected.");

	} catch(Exception e){ 

		e.printStackTrace();

	}
%>

To connect MySQL

<%@ page contentType="text/html; charset=euc-kr" %>
<%@ page import="java.sql.*" %>

<%
  Connection con=null;

  try{

/***************** My-SQL *****************************/
    String driver = "com.mysql.jdbc.Driver";

    String jdbcUrl = "jdbc:mysql://localhost:3306/jsptest";
    String dbId = "jspid";
    String dbPass = "jsppass";	
/*******************************************************/	


	Class.forName(driver);
	con=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	out.println("Successfully connected.");

	} catch(Exception e){ 

		e.printStackTrace();

	}
%>

If you get this message, it is all set! 

Now, to run the Oracle in Eclipse, we will make a folder named "sql" in the webcontent folder and create a new SQL file.

Open the Data Source Explorer and connect the Scott account to run the codes. 

 

Now, let us look at the overall procedure of connecting the database to JSP. 

1. Load JDBC Driver 

Create a class.forName() 

 

2. Connect Database

java.sql.Connection

 

3. Create SQLs

java.sql.Statement

java.sql.PreparedStatement - The most used

java.sql.CallableStatement

 

4. Send SQLs 

executeQuery()

executeUpdate()

 

5. Receive result

java.sql.ResultSet

 

6. Disconnect

Connection.close()

 

To start connecting, we need first to create a table.

create  table  member1( 
			 id varchar2(12) primary key,
             passwd varchar2(12) not null,
		     name varchar2(10) not null,
		     reg_date timestamp not null );
             
select * from tab;
select * from member1;

 

'Java > JSP' 카테고리의 다른 글

JSP) Model2 - Java Servlet 1  (0) 2022.09.15
JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JavaBean  (0) 2022.08.31
JSP) Action tags - include  (0) 2022.08.31
JSP) Handling Exceptions  (0) 2022.08.30

In this post, we will discuss JavaBean. 

Before, let us look at the JSP Model1 architecture.

JSP Model1 architecture

We already made a DTO class in Java, and that is JavaBean.

JavaBean is a component written in Java. 

There are some things that you need to consider when you make a Javabean.

1. In JavaBean, the member variable is called property.
2. Property is a field for storing values created by declaring the access controller private.
3. Properties are used as intermediate data storage when the contents of the JSP page are stored in the DB or when the contents stored in the DB are printed on the JSP page.
4. set() method and get() method are used a lot in JavaBean, and they
mainly use public access modifiers.
5. The Java Bean file's storage location should be in the WEB-INF/classes folder.

 

 

We will make a java file called "SimpleBean.java" in the src folder.

You can easily write generate getters and setters by right-clicking the mouse.

SimpleBean.java

// JavaBean, DTO Class(Data Transfer Object)

package javaBean;

public class SimpleBean {
	
	private String msg;	    // Property

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
}

There are three action tags related to JavaBean.

Action tags related to JavaBean Description
<jsp:useBean id=" " class=" " scope=" " /> to locate or instantiate a bean class
<jsp:setProperty name=" " property=" " value=" "/> to save a property value in a JavaBean object
<jsp:getProperty name=" " property=" " /> to bring the property value from the JavaBean object

 

<Example>

MemberInfo.java (JavaBean class)

package madvirus.member;

import java.sql.Timestamp;

public class MemberInfo {
    
    private String id;
    private String password;
    private String name;
    private String address;
    private Timestamp registerDate;
    private String email;
    
    public String getId() {
        return id;
    }
    public void setId(String val) {
        this.id = val;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String val) {
        this.password = val;
    }
    public String getName() {
        return name;
    }
    public void setName(String val) {
        this.name = val;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String val) {
        this.address = val;
    }
    public Timestamp getRegisterDate() {
        return registerDate;
    }
    public void setRegisterDate(Timestamp val) {
        this.registerDate = val;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String val) {
        this.email = val;
    }
}

 

 

'Java > JSP' 카테고리의 다른 글

JSP) Model1 vs Model2  (0) 2022.09.15
JSP) JSP and Oracle  (0) 2022.08.31
JSP) Action tags - include  (0) 2022.08.31
JSP) Handling Exceptions  (0) 2022.08.30
JSP) Action tags - forward  (0) 2022.08.30

The <jsp:include>action tag includes other pages along with (<%@include file=heheader.jsp" %>).
While the include directive simply contains text from a specific source, the <jsp:include> action tag includes the processing results of the page. You can include HTML, JSP, Servlet, and etc.

Let us look at the examples for a better understanding.

 

<Example 1>

incldeForm.jsp

<%@ page contentType="text/html;charset=euc-kr"%>

<html>
	<body>

	<h1>include Example</h1>

	<form method=post action="includeMain.jsp">
	Name : <input type="text" name="name"><p>
	<input type="submit" value="Submit">
	</form>	

	</body>
</html>

includeMain.jsp

<%@ page contentType="text/html;charset=euc-kr"%>

<html>
	<body>

	<h1>includeMain.jsp</h1>

	<%
		request.setCharacterEncoding("euc-kr");
	%>

	<hr>

	<jsp:include page="includeSub.jsp" flush="false"/>
	includeMain.jsp's content

	</body>
</html>

includeSub.jsp

<%@ page contentType="text/html;charset=euc-kr"%>

<%
	String name = request.getParameter("name");
%>

 includeSub.jsp<p>
<b>Hey, <%=name%>!</b>
<hr>

So, in the browser, you will see includeMain.jsp page including includeSub.jsp page.

 

<Example 2>

incldeForm2.jsp

<%@ page contentType="text/html;charset=euc-kr"%>

<html>
	<body>

	<h2>include Example2</h2>

	<form method=post action="includeMain2.jsp">
	Site Name : <input type="text" name="siteName1"><p>
				<input type="submit" value="Submit">
	</form>

	</body>
</html>

includeMain2.jsp

Here, <jsp:param> convey the "siteName" to this file from includeForm2.jsp.

<%@ page contentType="text/html;charset=euc-kr"%>

<html>
	<body>
	
	<h2>includeMain2.jsp Page</h2>

	<%
		request.setCharacterEncoding("euc-kr");
		String siteName1 = request.getParameter("siteName1");
	%>

	<hr>
	<jsp:include page="includeSub2.jsp">
		<jsp:param name="siteName" value="<%=siteName1%>"/>
	</jsp:include>

	includeMain2.jsp Page Content<p>

	</body>
</html>

includeSub2.jsp

With the request object, the siteName is conveyed to the includeSub2.jsp.

<%@ page contentType="text/html;charset=euc-kr"%>

<html>
	<body>

	<%
		String siteName = request.getParameter("siteName");
	%>

	includeSub2.jsp Page<p>

	<b><%=siteName%></b>
	<hr>

	</body>
</html>

Both include directive tag and include action tag are similar in that they all include other pages, but the include directive tag contains only the text, whereas the include action tag contains the results of the page's processing.

 

Here is another example. 

 

<Example 3>

includer.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>

<html>
	<head><title>include Directive</title></head>
	<body>

<%
    int number = 10;
%>

<%@ include file="includee.jspf" %>

Common Variable DATAFOLDER = "<%= dataFolder %>"

	</body>
</html>

includee.jspf

The 'f' in jspf means 'fraction'.

<%@ page contentType = "text/html; charset=euc-kr" %>

Number saved in includer.jsp page: <%= number %>

<p>

<%
    String dataFolder = "c:\\data";
%>

 

'Java > JSP' 카테고리의 다른 글

JSP) JSP and Oracle  (0) 2022.08.31
JSP) JavaBean  (0) 2022.08.31
JSP) Handling Exceptions  (0) 2022.08.30
JSP) Action tags - forward  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29

There are two ways to handle exceptions in JSP: by errorPage and isErrorPage attributes of page directive and by <error-page> element in web.xml file. 

Let's first get to know about the formal way. 

 

Handling Exception using page directive attributes

Two attributes can be used in JSP: errorPage and isErrorPage.

 

errorPage 

 <%@page errorPage="url of the error page"%>

isErrorPage 

 <%@page isErrorPage="true"%>

If the attribute of isErrorPage is true, it is designated as an error page. 

 

Let's discuss it more with some examples. 

In this code, there is no value in the name parameter; yet, we didn't handle the exception, so you will encounter the HTTP status code 500.

<%@ page contentType = "text/html; charset=utf-8" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

Parameter value of name: <%= request.getParameter("name").toUpperCase() %>

</body>
</html>

with errorPage attribute

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page errorPage = "/error/viewErrorMessage.jsp" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

Parameter value of name: <%= request.getParameter("name").toUpperCase() %>

</body>
</html>

vieErrorMessage.JSP

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page isErrorPage = "true" %>
<html>
<head><title>Error</title></head>
<body>

Sorry, an error occurred while processing your request.<br>
<p>
Error type: <%= exception.getClass().getName() %> <br>
Error message: <b><%= exception.getMessage() %></b>
</body>
</html>

You can also use try ~ catch like Java.

<%@ page contentType = "text/html; charset=utf-8" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

name parameter value: 
<% try { %>
<%= request.getParameter("name").toUpperCase() %>
<% } catch(Exception ex) { %>
Wrong name parameter.
<% } %>
</body>
</html>

 

The error data should exceed 512 bytes. If the length of the error page is less than 512 bytes, Internet Explorer does not print the error page that this page prints It outputs its own 'HTTP error message' screen. To print the contents of an error page correctly in Internet Explorer, you need to include the same in responding to this comment. 

 

errorPage 02

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page buffer="1kb" %>
<%@ page errorPage = "/error/viewErrorMessage.jsp" %>
<html>
<head><title>Buffer flush Exception</title></head>
<body>

<%  for (int i = 0 ; i < 300 ; i++) { out.println(i); }  %>

<%= 1 / 0 %>

</body>
</html>

So far, we have discussed the formal way of handling exceptions, but unless you have just several pages, you will need to use the latter way to handle exceptions using error-page element en web.xml file.

Instead of the errorPage directive, the error page can be specified in the web.xml file of <error-page> tags.

The web.xml file has to be in WEB-INF folder. Anything you need, to handle the exceptions, you have to put in the web.xml file. Here is the web.xml file.

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	id="WebApp_ID" version="4.0">
	<display-name>jspproject</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<error-page>
		<error-code>404</error-code>
		<location>/error/error404.jsp</location>
	</error-page>

	<error-page>
		<error-code>500</error-code>
		<location>/error/error500.jsp</location>
	</error-page>

	<error-page>
		<exception-type>java.lang.NullPointerException</exception-type>
		<location>/error/errorNullPointer.jsp</location>
	</error-page>

</web-app>

 

'Java > JSP' 카테고리의 다른 글

JSP) JavaBean  (0) 2022.08.31
JSP) Action tags - include  (0) 2022.08.31
JSP) Action tags - forward  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29
JSP) Session  (0) 2022.08.29

+ Recent posts