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.
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.
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?
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.
<%@ 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.
<%@ 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.
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.
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).
<%@ 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;
}
}
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.
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: OracleSource: 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.
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) {
}
}
}
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.
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
}
}
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());
}
}
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.
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;