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

This is how to delete the files in the directory and the directories with or without files. 

import java.io.File;

public class FileTest {

	public static void main(String[] args) {

		try {
			File temp = new File("C:/java01", "temp");
			File tempFile = new File("test"); // Relative path
			temp.mkdirs();
			tempFile.mkdirs();

			File[] f = tempFile.listFiles();
			for (int i = 0; i < f.length; i++) {
				System.out.println(f[i].getName());
				f[i].delete(); // To delete all files in the directory
			}
			tempFile.delete(); // To delete the empty directory

//To delete a child directory
			temp.delete(); 

//To delete a parent directory
			temp.getParentFile().delete();

		} catch (Exception e) {
		}
	}
}

'Java' 카테고리의 다른 글

Java) Array  (0) 2022.09.04
Java) .length vs length()  (0) 2022.09.02
Java) Conditional statements and loops  (0) 2022.08.30
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26

An array is a static data structure storing data of the same type. There are three types of arrays, but a three-dimensional array is used for machine learning or deep learning, so in this post, we will cover one-dimensional array and two-dimensional array. 

 

One-dimensional array

One dimensional array is used primarily when no value is defined to be stored in the array. 

 

To make a new array : format 

Datatype [] = new Datatype[Size of Array]. Here, the size of the array[] means how many rooms this array has. 

int[] score = new int[3];

There are two formats of one-dimensional array. 

First format

		int[] score = new int[3]; 
		
		System.out.println(score[0]); 
		System.out.println(score[1]);
		System.out.println(score[2]);
		
		// To assign a new value
		score[0] = 80;
		score[1] = 90;
		score[2] = 100;
		
		System.out.println(score[0]); 
		System.out.println(score[1]);
		System.out.println(score[2]);
        //Initial value : 0
		
		//double
		double[] d = new double[3];
		System.out.println(d[0]);
		System.out.println(d[1]);
		System.out.println(d[2]); 
        // Initial value : 0.0
		
		//char
		char[] c = new char[3];
		System.out.println(c[0]);
		System.out.println(c[1]);
		System.out.println(c[2]);
        // There is no initial value
		
		//boolean형
		boolean[] b = new boolean[3]; 
		System.out.println(b[0]);
		System.out.println(b[1]);
		System.out.println(b[2]);
		// Initial value : false

		//Reference type : String
		String[] str = new String[3];
		System.out.println(str[0]);
		System.out.println(str[1]);
		System.out.println(str[2]);
		// Initial value : null
		
		str[0] = "Jave";
		str[1] = "Oracle";
		str[2] = "Spring";
		
		System.out.println(str[0]);
		System.out.println(str[1]);
		System.out.println(str[2]);

Second format

This format is used when the declaration of the array and the value's initialization happen simultaneously. When there are certain values that you want to assign first, you can use this. 

The most important thing to remember when it comes to arrays is that you can't put different datatypes in the same array.

		int[] s1 = {80, 90, 100}; 
		int[] s2 = new int[] {80, 90, 100};
		System.out.println(s1[0]);
		System.out.println(s2[2]);
		System.out.println(s1[2]); 

		
		//double
		double[] dd = {3.14, 10.5, 42.195, 50}; // 50 will be changed to 50.0
		for(int i=0; i<dd.length; i++)
		System.out.print(dd[i]+"\t");
		System.out.println();
		
		//char
		char[] cc = {'j','v','P','h'};
		for(int i=0; i<cc.length; i++)
			System.out.print(cc[i]+"\t");
		System.out.println();
		
		//boolean
		boolean[] bb = {true, false, true};
		for(int i=0; i<bb.length; i++)
			System.out.print(bb[i]+"\t");
		System.out.println();
		
		//String 
		String[] str1 = {"Java", "is", "sometimes", "annoying", "but"};
		String[] str2 = new String[]{"it", "is", "mostly", "fun", "!!!"};

		//to print out
		for(int i=0; i>str1.length; i++) 
			System.out.println(str1[i]+"\t"); 
		
		}
	}

To know the size of the array

The array size can be easily explained as the number of rooms in the house(array).


		System.out.println("Size:"+ s1.length); //3
		for(int i=0; i<s1.length; i++) 
			System.out.print(s1[i]+"\t");
		System.out.println();

 

Here, we used the length property, not the length method. You will see the brackets"()" with the method to distinguish.

Please refer to my last post to understand better of the difference of the two constructs.

2022.09.02 - [Java] - Java) .length vs length()

 

Java) .length vs length()

In Java, two different length constructs have different roles. ".length", the length property is used with the String and Array class. It returns the number of characters in a text String or the siz..

www.agilemeadow.com

Example : Average

As you can see, array is a very efficient way to write a simple and clean code.

import java.util.Scanner;

public class ArrayEx03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] s = new int[5];
		
		System.out.println("Enter your scores of the 5 subjects.");
		Scanner sc = new Scanner(System.in);
				
		int sum = 0;
		for(int i=0; i<s.length; i++) {
			s[i] = sc.nextInt();
			sum += s[i]; 	
		}
		double avg = sum / 5.0;
		System.out.println("Sum:"+ sum);
		System.out.println("Avg:"+ avg);
	}

}

Example : Max and Min number

public class ArrayEx04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		double[] data = {9.5, 7.0, 13.6, 7.5, 10.5};
		
		double max, min;
		
		max = data[0];  
		min = data[0];
		
		for(int i=1; i<data.length; i++) {
			if(data[i] > max) max = data[i];
			if(data[i] < min) min = data[i];
		}
		 
		System.out.println("max:"+max);
		System.out.println("min:"+min);
	

}
}

 

Two-dimensional array

Two-dimensional array sounds more difficult, but the basic is same as one dimensional array. 

Let's check out the codes first.

So, let's say there are three five students who took exams of three subjects and we are arranging the scores in the two-dimensional array. 

public class ArrEx {

  public static void main(String[] args) {
    int  [][]score=new int [5][3]; // datatype [row] [col]

    score[0][0]=10;  score[0][1]=90;  score[0][2]=70;
    score[1][0]=60;  score[1][1]=80;  score[1][2]=65;
    score[2][0]=55;  score[2][1]=60;  score[2][2]=85;
    score[3][0]=90;  score[3][1]=75;  score[3][2]=95;
    score[4][0]=60;  score[4][1]=30;  score[4][2]=80;

    //For loop
    for(row = 0; row < 5 ; row++){ 
      for(col = 0; col < 3 ; col++){  
         System.out.print(" " +score[row][col]);
	  }
      System.out.println("");
    }
  }
}

Compare to not using array, it will be still clean but this code looks a bit too much work. 

Let us elaborate this little bit better.

public class ArrEx01 {

  public static void main(String[] args) {
   
    int [][]score = { { 85,  60,  70},   //row no.0
				      { 90,  95,  80},   //1
				      { 75,  80, 100},   //2 
                      { 80,  70,  95},   //3 
				      {100,  65,  80}    //4 
					};
    int [] subject = new int[3]; 
    int [] student = new int[5]; 
    int  r, c;  
	    
    System.out.println("Sum by each subjects. ");
    for(c = 0; c < 3 ; c++){ // subjects      
      for(r = 0; r < 5 ; r++){ // students   
        subject[c] += score[r][c];   
      }
      System.out.println(subject[c]);  
    }

    System.out.println("Sum by each studetns");
    for(r = 0; r < 5 ; r++){    // studnets    
      for(c = 0; c < 3 ; c++){  // sujects
        student[r] += score[r][c];  
      }
      System.out.println(student[r]);
    }

  }//main() end
}// class end

Type Conversion in array

In Java, type conversion is a very important thing to remember because it happends a lot everytime. We will talk about this in the other posts, but now, just take a peek of how they look like. 

public class ArrayEx07 {
	
	//Absolute value
	static int abs(int data) {
		if(data < 0)
			data = -data; 
		return data;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// args[0] = " -10", args[1] = "-20" => char
		System.out.println("args[0]:"+args[0]);
		System.out.println("args[1]:"+args[1]);
		
		//args[0] = "-10" ---> -10 : Type conversion
		int num = Integer.parseInt(args[0]);
		///Integer.parseInt (char -> num) 
		System.out.println("Absolute Value:"+abs(num));

		int num1 = Integer.parseInt(args[1]);
		///Integer.parseInt (char -> num)
		System.out.println("Absolute Value:"+abs(num1));
		
		}
	}

Array Copy

You can also copy the array that you already have, by using for loop.

public class ArrayEx08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int[] oldArray = {10, 20, 30}; //Original array
		int[] newArray = new int[5]; //New array
		
		for(int i=0; i<oldArray.length; i++) {
			newArray[i] = oldArray[i]; //for loop
		}

		for(int i : newArray) { 
			System.out.println(i+"\t");
		}// Initial value : 0.0
		
		
	}

}

 

'Java' 카테고리의 다른 글

Deleting attached files  (0) 2022.09.14
Java) .length vs length()  (0) 2022.09.02
Java) Conditional statements and loops  (0) 2022.08.30
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26

In Java, two different length constructs have different roles. 

 

".length", the length property is used with the String and Array class. It returns the number of characters in a text String or the size of an array. The length method, "length" with brackets"()", is for data encapsulation. 

 

The biggest similarity between them is that they help to determine the number of elements an object contains. However, the method works with the String class, while the property works with arrays. 

Here are some examples of them. 

// length can be used for int[], double[], String[] 
// to know the length of the arrays.

// length() can be used for String, StringBuilder, etc 
// String class related Objects to know the length of the String

public class Test {
    public static void main(String[] args)
    {
        // Here array is the array name of int type
        int[] array = new int[4];
        System.out.println(array.length);  //4
 
        // Here str is a string object
        String str = "Meadow";
        System.out.println(str.length());  //6
    }
}

.length

public class Test {
    public static void main(String[] args)
    {
        // Here str is the array name of String type.
        String[] str = { "Java", "is", "easy", "and", "fun" };   //5
        System.out.println(str.length);
    }
}

length()

It will occur an error with this code.

public class Test {
    public static void main(String[] args)
    {
        String[] str = { "Meadow", "Min", "Young" };   //error
        System.out.println(str.length());
    }
}

 

'Java' 카테고리의 다른 글

Deleting attached files  (0) 2022.09.14
Java) Array  (0) 2022.09.04
Java) Conditional statements and loops  (0) 2022.08.30
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26

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

+ Recent posts