multi.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mutiplication Table</title>
<script>
	function check(){
		var num = document.getElementById("num");
		if(num.value == ""){
			alert("Choose one table.");
			return false;
		}
	}
</script>
</head>
<body>
	<h2>Choose one table from the box. </h2>
	<form method=post  action="gugu.jsp" onSubmit="return check()">
		<select name="num" id="num">
			<option value="">Select</option>
			<option value="2">2</option>
			<option value="3">3</option>
			<option value="4">4</option>
			<option value="5">5</option>
			<option value="6">6</option>
			<option value="7">7</option>
			<option value="8">8</option>
			<option value="9">9</option>
		</select>
		<p>
			<input type="submit" value="Click to view">
	</form>
</body>
</html>

gugu.jsp

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

<%
        int num = Integer.parseInt(request.getParameter("num"));

	out.println("<h2>"+num+" Times table</h2>");
	for (int i = 1; i <= 9; i++) {
		out.println(num+" * "+i+" = "+num*i+"<br>");
    }  
%>

 

'Codes & Projects' 카테고리의 다른 글

JSP) Model2 - Java Servlet 2  (0) 2022.09.16
Java) Temperature Converter  (0) 2022.09.10
Java) ATM - While loops / If statements  (0) 2022.09.03
JSP / CSS) Log In - JavaBean, Action tags  (0) 2022.09.02
JSP/ Oracle) Members list  (0) 2022.08.31

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

What is Structured Query Language (SQL)?
As a DB standard language (specified by ISO) with its syntax, most databases use SQL to query, enter, modify, and delete data.

 

Types of SQL

  • Data Definition Word (DDL): A database administrator or application programmer is stored in a data dictionary as the language for defining the logical structure of the database.
  • Data manipulation words (DML): As the language used to manipulate data stored in the database, perform data retrieval (Retrieval), addition (Insert), deletion, and update operations.
  • Data Control Language (DCL): Language used to manage transactions on database systems, such as granting access to data

SQL Statements

Type Statement Use
DQL(Data Query Language) SELECT To search the data
DML(Data Manipulation Language) INSERT
UPDATE
DELETE
To change the data
DDL(Data Definition Language) CREATE
ALTER
DROP
RENAME
TRUNCATE
To create and change objects
TCL(Transaction Control Language) COMMIT
ROLLBACK
SAVEPOINT
To process transaction
DCL(Data Control Language) GRANT
REVOKE
To control the data

*CRUD

In computer programming, create, read, update, and delete(CRUD) are the four basic operations of persistent storage. They correspond to 'insert', 'select', 'update', and 'delete' in SQL so it is vital to remember the statements.

 

<DDL>

o Create a table

create table table-name (
				column name data type,
				Column name data type, ……….);

create table member01(
				id varchar2(20),
				name varchar2(20),
				address varchar2(50),
				phone varchar2(20));

o Table list output

select * from tab;

o Table structure output

describe member01;

o Rename the table

alter table old table name rename to new table name;
alter table member01 rename to member02;


The table name can also be changed.

 rename member01 to member02;

o Add a new column to the table (add operator)

alter table member01 add (password varchar2(30));

o Modify the column of the table (modify operator)

 alter table member01 modify (password varchar2(50) not null);

Other data types if the column already has data cannot be changed too.

o Delete columns in the table (drop operator)

alter table member01 drop column column_name;
alter table member01 drop column password;

o Delete Constraints

 alter table member01 drop primary key;

o Deleting a table

drop table member01;

How do I delete this temporary table parmanently?

purge recyclebin;

How do I delete a table completely from scratch?

 drop table member01 purge;

 

<DML>

 

1. INSERT(Data Input)
Format: insert into tablename (column1, column2,...) values (data1, data2,...);
insert into table name values (data1, data2,...);

insert into dept01(deptno, dname, loc)
			values(10,'ACCOUNTING', 'NEW_YORK');
            
insert into dept01(dname, loc, deptno)
			values('RESEARCH', 'DALLAS', 20);
            
insert into dept01 values(30, 'SALES', 'CHICAGO');
insert into dept01 values(40, 'OPERATIONS','BOSTON');

Following is an example of creating a row by using 'insert'. It has to be '' not "" when we insert the values. SQL is not sensitive with Uppercase/Lowercase, but it has to be distinguished in terms of values. As you see below, here are 2 ways to insert the values. Depending on the situation, one can be chosen.

2. UPDATE (Data Modification)
Format: update table name set column 1 = Value to modify 1,
Column 2 = Value to modify 2,...
where conditional;

If you don't use 'where', the address of the whole table will be changed, so be careful!

After being updated, the address value of table 'test2' is changed.

3. DELETE (Data Deletion)
format: delete from table name where conditional;

To delete it is relatively easy. After deleting from the table, you can see no rows selected.

'DB > Oracle' 카테고리의 다른 글

Oracle) Reserved words  (0) 2022.10.25
Java-Oracle Interworking Configuration  (0) 2022.09.11
Oracle) Setting up  (0) 2022.09.01
import java.util.Scanner;

public class Bank {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		boolean run = true;

		int balance = 0;

		Scanner sc = new Scanner(System.in);

		while (run) {
			System.out.println("-------------------");
			System.out.println("1.Savings | 2. Withdrawl | 3. Balance | 4. Finish  ");
			System.out.println("-------------------");
			System.out.println("Select>");

			int num = sc.nextInt();

			if (num == 1) {
				System.out.println("Savings : 10000won");
			} else if (num == 2) {
				System.out.println("Withdrawl : 2000won");
			} else if (num == 3) {
				System.out.println("Balance : 8000won");
			} else if (num == 4) {
				run = false;
			}

		}
		System.out.println("Finish.Goodbye");
	}
}

Please check out my video on Youtube to know how I wrote the codes. 

https://youtu.be/u0bFgQZt8Co

 

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

login_form.html

<html>
	<head><title>JSP Bean example</title>

	<script>

	</script>
	</head>

<body bgcolor="#FFFFFF" onLoad="document.myform.userid.focus()">
<center>
<H2>Log in</H2>
<HR>

<form method="post" action="login.jsp" name="myform">
  <table width="250" border="1" align="center" bordercolordark="#FF0033" cellspacing="0" cellpadding="5">
    <tr bgcolor="#FF6666"> 
    <td colspan="2" height="21"> 
      <div align="center"><b><font size="2">Log in</font></b></div>
    </td>
  </tr>
  <tr bgcolor="#FFCCCC"> 
      <td> ID</td>
      <td> <b> 
        <input type="text" name="userid" size=10>
        </b> </td>
  </tr>
  <tr bgcolor="#FFCCCC"> 
      <td> Password</td>
      <td> 
        <input type="password" name="passwd" size=10>
      </td>
  </tr>
  <tr bgcolor="#FFCCCC"> 
    <td height="42" colspan="2"> 
      <div align="center">
        <input type="submit" value="Log in" onClick="check()">
      </div>
    </td>
  </tr>
</table>
</form>
<p>

</body>
</html>

LoginBean.java 

This file has to be in a package in the src folder.

package beans;


public class LoginBean {	
	
    // Fields to save the values that user inserted
	private String userid;
	private String passwd;

	private String _userid;
	private String _passwd;
	
    //Initial ID and password
	public LoginBean() {
		_userid = "myuser";
		_passwd = "1234";
	}
	// To check if the IDs and the passwords match
    public boolean checkUser() {
		if(userid.equals(_userid) && passwd.equals(_passwd))
			return true;
		else
			return false;
	}		
	
	public void setUserid(String userid) {
		this.userid = userid;
	}
	
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}	
	
	public String getUserid() {
		return userid;
	}
	
	public String getPasswd() {
		return passwd;
	}
}

login.jsp

<%@ page contentType="text/html;charset=euc-kr"%>
<jsp:useBean id="login" class="beans.LoginBean" />
<jsp:setProperty name="login" property="*" />

<HTML>
<HEAD>
<TITLE>Log in Example</TITLE>
</HEAD>
<BODY>
	<center>
		<H2>Log in Example</H2>
		<HR>

		<%
			if (!login.checkUser()) {
			out.println("Failed to log in.");
		} else {
			out.println("Successfully logged in.");
		}
		%>

		<HR>
		User ID :
		<jsp:getProperty name="login" property="userid" /><BR> 
        User password :
		<jsp:getProperty name="login" property="passwd" />
</BODY>
</HTML>

Initial values

Setting up

The new version of Oracle takes up a lot of memory and RAM, so I downloaded the XE11 version. OracleXETNSListener and OracleServiceXE have to be constantly running on your computer, so once you download the app, you will find that turning on/off takes more time. Therefore, when you don't use it, you would better set the Startup type "Manual" instead of "Automatic."

Connecting to Client

Open the command prompt and enter 'sqlplus name of the account/password. to show the user's name, enter 'show user'.

You could also enter 'sqlplus,' and the prompt will ask for your user name and password.

To change the account, you could use 'connect account name/password as sysdba'

To be safe from the mistakes you will make with the system account, Oracle offers an account named 'scott' for demonstration purposes. According to legend, this account was named after Bruce Scott, co-author and co-architect of Oracle v1 to v3, and the password was the name of his daughter's cat, Tiger. (What a monument!)

To set your account's password, you can use 'alter user account name identified by password'. To see the list of the table, insert 'select*from tab;' and you will see 4 tables on the list.

To exit, you can either insert 'exit' or 'quit', and you will see this :

*When you forget the password of DBA and USER

It is impossible to know your previous password but you can reset your password. Enter 'sqlplus /"as sysdba"' and check 'show user' first, and enter 'alter user ID identified by yournewpassword;'

 

'DB > Oracle' 카테고리의 다른 글

Oracle) Reserved words  (0) 2022.10.25
Java-Oracle Interworking Configuration  (0) 2022.09.11
Oracle) Structured Query Language(SQL)  (0) 2022.09.03

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

Create a table first to store data in Oracle or Eclipse. 

 

myoracle.sql

select * from tab;
select * from member1;

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

insertTestForm.jsp

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

<html>
<head>
<title>Insert record</title>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
	$(document).ready(function() {
		$("form").submit(function() {
			if ($("#id").val() == "") {
				alert("Insert your ID.");
				$("#id").focus();
				return false;
			}
			if ($("#passwd").val() == "") {
				alert("Insert your password.");
				$("#passwd").focus();
				return false;
			}
			if ($("#name").val() == "") {
				alert("Insert your name.");
				$("#name").focus();
				return false;
			}
		});

	});
</script>
</head>

<body>
	<h2>Insert record on member1 table</h2>

	<FORM METHOD="post" ACTION="insertTest.jsp">
		ID : <INPUT TYPE="text" NAME="id" id="id">
		<p>
			Password : <INPUT TYPE="password" NAME="passwd" id="passwd">
		<p>
			Name :<INPUT TYPE="text" NAME="name" id="name">
		<p>
			<INPUT TYPE="submit" VALUE="Submit">
	</FORM>

</body>
</html>

insertTest.jsp

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

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

  String id= request.getParameter("id");
  String passwd= request.getParameter("passwd");
  String name= request.getParameter("name");
  Timestamp register=new Timestamp(System.currentTimeMillis());

  Connection conn=null;
  PreparedStatement pstmt=null;
  int result = 0;
  
  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	// JDBC
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	String sql= "insert into member1 values (?,?,?,sysdate)";
	pstmt=conn.prepareStatement(sql);
	pstmt.setString(1,id);
    pstmt.setString(2,passwd);
	pstmt.setString(3,name);
//	pstmt.setTimestamp(4,register);
	result = pstmt.executeUpdate();

	}catch(Exception e){ 
		e.printStackTrace();
	}finally{
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
	}
%>

<html>
<head><title>Member List</title></head>
<body>
  
<%
	if(result == 1){
%>    
  		<script>
  			alert("Successfully joined.");
  			location.href="selectTest.jsp";
  		</script>
<% 	}else{%>
   		<script>
			alert("Failed to join.");
			history.go(-1);
   		</script>
<% 	} %>   
</body>
</html>

seleteTest.jsp

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

<html>
<head><title>Display records</title></head>
<body>
  <h2>Member1 Table</h2>
  
  <a href="insertTestForm.jsp">Sign Up</a>
  <TABLE width="550" border="1">
  <TR>
  	<TD width="100">ID</TD>
  	<TD width="100">Password</TD>
  	<TD width="100">Name</TD>
  	<TD width="250">Joined Date</TD>
  	<TD width="100">Edit</TD>
  	<TD width="100">Delete</TD>
  </TR>

<%
  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rs=null;
  ResultSet rs01=null;
  int cnt=0;
  
  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );

	pstmt=conn.prepareStatement("select count(*) from member1");
	rs01=pstmt.executeQuery();
	if(rs01.next()){
		cnt = rs01.getInt(1);
//		cnt = rs01.getInt("count(*)");
	}	
	
	String sql= "select * from member1";
	pstmt=conn.prepareStatement(sql);
	rs=pstmt.executeQuery();

	while(rs.next()){
	  String id= rs.getString("id");
      String passwd= rs.getString("passwd");
      String name= rs.getString("name");
      Timestamp register=rs.getTimestamp("reg_date");

%>
     <TR>
  	   <TD width="100"><%=id%></TD>
  	   <TD width="100"><%=passwd%></TD>
  	   <TD width="100"><%=name%></TD>
  	   <TD width="250"><%=register.toString()%></TD>
  	   <TD width="100">
  	   		<a href="updateTestForm.jsp?id=<%=id%>">
  	  		 Edit
  	   		</a>  	   
  	   </TD>
  	   <TD width="100">
  	   		<a href="deleteTestForm.jsp?id=<%=id %>">
  	   		 Delete
  	   		</a>
  	   </TD>
    </TR>
<%  } 
  }catch(Exception e){ 
		e.printStackTrace();
  }finally{
	    if(rs != null) try{rs.close();}catch(SQLException sqle){}
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
  }
%>
</TABLE>

Total members :<%=cnt %>


</body>
</html>

updateTestForm.jsp

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

<%
	String uid = request.getParameter("id");

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

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

	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn = DriverManager.getConnection(jdbcUrl, dbId, dbPass);

	String sql = "select * from member1 where id=?";
	pstmt = conn.prepareStatement(sql);
	pstmt.setString(1, uid);
	rs = pstmt.executeQuery();

	if (rs.next()) {
		String id = rs.getString("id");
		String passwd = rs.getString("passwd");
		String name = rs.getString("name");
		Timestamp register = rs.getTimestamp("reg_date");
%>
<html>
<head>
<title>Update record</title>
</head>

<body>
	<h2>Update record on member1 table</h2>

	<FORM METHOD="post" ACTION="updateTest.jsp">
		<input type=hidden name="id" value="<%=id%>"> ID :
		<%=id%><p>
			Password : <INPUT TYPE="password" NAME="passwd">
		<p>
			Name to edit:<INPUT TYPE="text" NAME="name" value="<%=name%>">
		<p>
			<INPUT TYPE="submit" VALUE="Submit">
	</FORM>

</body>
</html>

<%
	} // if end
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null)
try {
	rs.close();
} catch (SQLException sqle) {
}
if (pstmt != null)
try {
	pstmt.close();
} catch (SQLException sqle) {
}
if (conn != null)
try {
	conn.close();
} catch (SQLException sqle) {
}
}
%>

Click to update

updateTest.jsp

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

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

  String id= request.getParameter("id");
  String passwd= request.getParameter("passwd");
  String name= request.getParameter("name");

  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rs=null;

  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	String sql= "select id, passwd from member1 where id= ?";
	pstmt=conn.prepareStatement(sql);
    pstmt.setString(1,id);
	rs=pstmt.executeQuery();
    
	if(rs.next()){ // if the ID is already occupied
		String rId=rs.getString("id");
		String rPasswd=rs.getString("passwd");
      if(id.equals(rId) && passwd.equals(rPasswd)){
	    sql= "update member1 set name= ?, reg_date=sysdate  where id= ? ";
	    pstmt=conn.prepareStatement(sql);
	    pstmt.setString(1,name);
	    pstmt.setString(2,id);
	    pstmt.executeUpdate();
	   
%>
		<script>
			alert("Successfully updated.");
			location.href="selectTest.jsp";
		</script>	
<%
       }else{
 %>
	 <script>
	 	alert("Wrong password.");
	 	history.go(-1);
	 </script>
	 	
<% 	 
		}
	 }else{
%>
		<script>
			alert("Wrong ID.");
			history.go(-1);
		</script>
<%
	 }

	}catch(Exception e){ 
		e.printStackTrace();
	}finally{
		if(rs != null) try{rs.close();}catch(SQLException sqle){}
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
	}
%>

deleteTestForm.jsp

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

<%
  String uid=request.getParameter("id");

  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rs=null; 
  
  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	String sql= "select * from member1 where id=?";
	pstmt=conn.prepareStatement(sql);
	pstmt.setString(1, uid);
	rs=pstmt.executeQuery();

	if(rs.next()){
	  String id= rs.getString("id");
      String passwd= rs.getString("passwd");
      String name= rs.getString("name");
      Timestamp register=rs.getTimestamp("reg_date");

%>
<html>
<head><title>Delete record</title></head>

<body>
  <h2>Delete record on member1 table</h2>

  <FORM METHOD="post" ACTION="deleteTest.jsp">
  <input type=hidden name="id" value="<%=id %>">
  <%--   ID : <%=id %><p> --%>
    Password: <INPUT TYPE="password" NAME="passwd"><p>
   <%--  Name:<%=name%><p> --%>
    <INPUT TYPE="submit" VALUE="Delete">
  </FORM>

</body>
</html>

<%  } // if end
  }catch(Exception e){ 
		e.printStackTrace();
  }finally{
	    if(rs != null) try{rs.close();}catch(SQLException sqle){}
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
  }
%>

Click to delete

deleteTest.jsp

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

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

  String id= request.getParameter("id");
  String passwd= request.getParameter("passwd");

  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rs=null;

  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );
	
	String sql= "select id, passwd from member1 where id= ?";
	pstmt=conn.prepareStatement(sql);
    pstmt.setString(1,id);
	rs=pstmt.executeQuery();
    
	if(rs.next()){ 
		String rId=rs.getString("id");
		String rPasswd=rs.getString("passwd");
      if(id.equals(rId) && passwd.equals(rPasswd)){
	    sql= "delete from member1 where id= ? ";
	    pstmt=conn.prepareStatement(sql);
	    pstmt.setString(1,id);
	    pstmt.executeUpdate();
%>
			<script>
				alert("Successfully deleted.");
				location.href="selectTest.jsp";
	    	</script>
<%	    
	   }else{
%>
		  <script>
		  	alert("Wrong password.");
		  	history.go(-1);
		  </script>
<%	   }%>


<% }else{ %>

		<script>
			alert("Wrong ID.");
			history.go(-1);
		</script>
		
<%	
	 } 

	}catch(Exception e){ 
		e.printStackTrace();
	}finally{
		if(rs != null) try{rs.close();}catch(SQLException sqle){}
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
	}
%>

 

++ SimpleDateFormat in selectTest.jsp

You must import the SimpleDateFormat.

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

<html>
<head><title>Display records</title></head>
<body>
  <h2>Member1 Table</h2>
  
  <a href="insertTestForm.jsp">Sign Up</a>
  <TABLE width="550" border="1">
  <TR>
  	<TD width="100">ID</TD>
  	<TD width="100">Password</TD>
  	<TD width="100">Name</TD>
  	<TD width="250">Joined Date</TD>
  	<TD width="100">Edit</TD>
  	<TD width="100">Delete</TD>
  </TR>

<%
  Connection conn=null;
  PreparedStatement pstmt=null;
  ResultSet rs=null;
  ResultSet rs01=null;
  int cnt=0;
  
  try{
	String jdbcUrl="jdbc:oracle:thin:@localhost:1521:xe";
    String dbId="scott";
    String dbPass="tiger";
	 
	Class.forName("oracle.jdbc.driver.OracleDriver");
	conn=DriverManager.getConnection(jdbcUrl,dbId ,dbPass );

	pstmt=conn.prepareStatement("select count(*) from member1");
	rs01=pstmt.executeQuery();
	if(rs01.next()){
		cnt = rs01.getInt(1);
//		cnt = rs01.getInt("count(*)");
	}	
	
	String sql= "select * from member1";
	pstmt=conn.prepareStatement(sql);
	rs=pstmt.executeQuery();
	
	SimpleDateFormat sd = new SimpleDateFormat("MM.dd.yyyy HH:mm:ss");

	while(rs.next()){
	  String id= rs.getString("id");
      String passwd= rs.getString("passwd");
      String name= rs.getString("name");
      Timestamp register=rs.getTimestamp("reg_date");

%>
     <TR>
  	   <TD width="100"><%=id%></TD>
  	   <TD width="100"><%=passwd%></TD>
  	   <TD width="100"><%=name%></TD>
  	   <TD width="250"><%=sd.format(register)%></TD>
  	   <TD width="100">
  	   		<a href="updateTestForm.jsp?id=<%=id%>">
  	  		 Edit
  	   		</a>  	   
  	   </TD>
  	   <TD width="100">
  	   		<a href="deleteTestForm.jsp?id=<%=id %>">
  	   		 Delete
  	   		</a>
  	   </TD>
    </TR>
<%  } 
  }catch(Exception e){ 
		e.printStackTrace();
  }finally{
	    if(rs != null) try{rs.close();}catch(SQLException sqle){}
		if(pstmt != null) try{pstmt.close();}catch(SQLException sqle){}
		if(conn != null) try{conn.close();}catch(SQLException sqle){}
  }
%>
</TABLE>

Total members :<%=cnt %>


</body>
</html>

 

+ Recent posts