JAVA

Importing data into JSP, Java Collection Framework: Lists

mossybeach 2024. 7. 3. 17:51

Importing data into JSP using mariaDB and try/catch

 

Utilising what we learnt yesterday, we encorporated the try/catch method to import data onto an index.jsp page we have created and launched via Apache Tomcat.

 

Use the setting below to set up a dynamic web project after downloading Apache tomcat.

 

PROTIP: make sure to name the main jsp file as index as that will be the name Java will be searching in order to run (similar to running firebase)

 


 

1.) We created a similar try/catch phrase from yesterday to retrieve data from the DB

public class Data {

We CANNOT use main as this is a WEB PROJECT

public String[][] dbData() {

 

connection

Connection conn = null;

Statement

Statement stmt = null;

 

connection info

String url = "jdbc:mariadb://redacted/employees";

String user = "redacted";

String pw = "redacted";

 

 ResultSet that stores data that stmt brings

ResultSet rs = null;

database command

String sql = "SELECT * FROM employees LIMIT 100";

 

2D array to store data converted to string

String[][] result = new String[100][6];

 

putting together info to connect to DB

try {

Class.forName("org.mariadb.jdbc.Driver");

conn = DriverManager.getConnection(url, user, pw);

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

 

Storing data using nested loops (forEach and for loop) for 2D array

int index = 0;

while (rs.next()) {

for (int i = 0; i < 6; i++) {

result[index][i] = rs.getString(i + 1); //because DBs index start with 1

}

index++;

}

except of creating a seperate catch for ClassNotFound we use a general Exception clause = short code but bad accuracy for error

} catch (Exception e) {

 

e.printStackTrace();

}finally {

try {

rs.close();

stmt.close();

conn.close();

} catch (SQLException e) {

 

e.printStackTrace();

}

}

return result;

}

}

 

2. Then we created a jsp file named index and brought in the data we retrieved from the DB

<%@page import="data.Data"%>

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

pageEncoding="UTF-8"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

</head>

<body>

<h1>데이터베이스와 연결해보기</h1>

<h1>2024-07-03</h1>

<%

- create a new Data object

Data data = new Data();

 

-then get the array that has the db info stored by calling the dbdata() method we made in the java file above

String[][] result = data.dbData();

%>

we used this to check we're receiving our data okay

<%=result[0][2]%>

 

<table border="1">

<thead>

<tr>

<th>emp_no</th>

<th>birth_date</th>

<th>first_name</th>

<th>last_name</th>

<th>gender</th>

<th>hire_date</th>

</tr>

</thead>

<tbody align="center">

surround the html tag of where you want to add the DB info with <%><%> so Java knows where it starts and ends

<% for(int i = 0; i < result.length; i++){

%>

<tr>

<td><%=result[i][0] %></td>

<td><%=result[i][1] %></td>

<td><%=result[i][2] %></td>

<td><%=result[i][3] %></td>

<td><%=result[i][4] %></td>

<td><%=result[i][5] %></td>

</tr>

<%

}

%>

</tbody>

 

</table>

</body>

</html>

 


 

Java Collection Framework

https://www.tcpschool.com/java/java_collectionFramework_concept

 

Java's Collection:

  • It is a Java library designed to store multiple reference values of the same type
  • Similar to arrays but easier to use

Collection Framework = Data Structure

There are three types:

 

Interface Description Classes
List <E> similar to arrays, allows duplicate values, has an index Vector, ArrayList, LinkedList, Stack,
Queue
Set<E> we cannot store the same value, will automatically delete duplicate values, no index HashSet, TreeSet
Map<K,V> uses key:value, similar to Javascript's object, values can be duplicated, no index HashMap,TreeMap, Hashtable,
Properties

 

what is <E>?

It's called Generic and the E stands for Element, which means the type it's formed of, this we enter classes in <>, therefore we can only use reference types!

 

But what if I want to use primitive types?

We can!!! We just need to convert them to reference types! We use wrapper classes for this where we define it's type

 

default type wrapper class
byte Byte
char character
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

 

Example of converting into wrapper classes

public class Coll01 {

public static void main(String[] args) {

Integer i1 = new Integer(10);  <= When converting primitive types to references, we don't have to promote like this!

Integer i2 = 10;   <= instead Java automatically promotes it for you

int number = i2;  <= therefore this is also possible (because techincally they're the same)

 

we can also cast different p types by using methods like these because they are now classes!!

byte bNum = i2.byteValue(); 

short sNUm = i2.shortValue();

Byte b1 = 10;

Long l1 = 1000L;

Boolean bool2 =true;

}

}


 

 

Lists

When creating lists, we can write something like this! (this is for a list that will hold integer values.)

List<Integer> list = new ArrayList<Integer>();

 

When creating a new list instead of creating a new List object, we use ArrayList, this is because List is an interface and is abstract therefore we cannot create an instance therefore we use ArrayList that implements List.

 

Does this mean we can never create an instance using list?
We technically can but we need to override everything.

 


When using Lists or other Compilations, we need to make sure to import them onto our Java file.

import java.util.ArrayList;

import java.util.List;

 

we can type import.java.util.* to import everything needed for the file 

or press ctrl + shift+ O for auto import!

 


Methods we can use for List 

.add( ) : we use this to add a value to a list. If not specified it will input values starting from index 0, 1,2..

.get( ) : we use this to get the value of a list, we specify the index in the bracket.

.size( ): this works the same as length() for arrays

.remove( ): this removes a value from the index specified in the bracket.

.contains( ): this returns a boolean value to check if a list contains a value we specify in the bracket

.set( ) : this takes two parameters, an index and a new element to replace the one on the index aforementioned.

.isEmpty( ): this also returns a boolean value to confirm if the list is empty

.addAll( ): adds another list to a list, think of .concat() for javascript arrays

.indexOf( ): returns the index of the value in the bracket, returns -1 if it doesn't exist


Example 1: printing out numbers within a list in a set order

 

List<Integer> list03 = new ArrayList<>();

for (int i = 1; i < 11; i++) {

if (i % 2 == 0) {

list03.add(i);

} else {

list03.add(0, i);

}

}

System.out.println(list03); //[9, 7, 5, 3, 1, 2, 4, 6, 8, 10]

 

this code needs a bit of clever thinking. When we use add(), it starts adding value from index 0, 1,2.. So thats what we did by adding all the even numbers by ascending order. However to add the odd numbers in descending order. We had to plan the code by adding the i in the 0 index, so the smallest odd number gets pushed to the back and the largest in the front!


Example 2: printing numbers in a particular order

for (int i = 0; i < 10; i++) {

list03.add(i + 1);

}

System.out.println("list03 (i+1)")

System.out.println(list03); //  [1,2,3,4,5,6,7,8,9,10]

 

for (int i = 0; i < 5; i++) {

System.out.println(list03.remove(i + 1));

list03.add(list03.remove(i + 1));

}

System.out.println(list03); //[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

 

This is also a brain twister. First we generate the numbers from 1 to 10 and add to list03.

Then using a second for loop we remove the number at the index of (i +1). This will lead to all the even numbers being removed. Then this is added back to list03 which will result in the result above. 


Example 3: creating a method that will replace the number that is entered with another if it exists in a list.

//teacher code

public static List<Integer> res(List<Integer> list, int num, int num2) {

if(list.contains(num)) {

for (int i = 0; i < list.size(); i++) {

if(list.get(i) == num) {

list.set(i,num);

}

}

}

return list;

}

 

//my code

// public static List<Integer> res(List<Integer> list, int num, int num2) {

//

// for (int i = 0; i < list.size(); i++) {

// if (list.get(i) == num) {

// list.remove(i);

// list.add(i, num2);

// }

//

// }

// return list;

// }

 

public static void main(String[] args) {

List<Integer> list01 = new ArrayList<Integer>();

for (int i = 10; i > 0; i--) {

list01.add(i);

}

System.out.println(list01);

 

list01.set(0, 100); // replace what's at index 0 with 100

System.out.println(list01);

// List<Integer> list02 = Coll02.res(list01, 100);

// System.out.println(list02);

List<Integer> list03 = Coll02.res(list01, 100, 200);

System.out.println(list03);

}


Example 4: Lotto 

We learn some cool methods we can use when we call Collections.

List<Integer> list02 = new ArrayList<>();

 

for (int i = 0; i < 46; i++) {

list02.add(i);

}

//shuffle method

Collections.shuffle(list02); //this shuffles the list in a random order

for (int i = 0; i < 6; i++) {

System.out.print(list02.get(i) + ", ");

}

Collections.sort(list02); // this sorts the list in ascending order

Collections.sort(list02, Collections.reverseOrder()); //these two sorts it in descending order

Collections.reverse(list02);

 

 

 


2 Dimensional Lists

Like two dimensional arrays we can also create 2 dimensional lists by putting a list into another. 

Example 1: 

public static void main(String[] args) {

List<Integer> list01 = new ArrayList<Integer>();

list01.add(1000); there is 1000 in list01.

 

List<List<Integer>> list02 = new ArrayList<List<Integer>>();

list02.add(list01); list01 is added into list01.

 

System.out.println(list02.get(0).get(0)); // the 0 index of list 2 will have 1000.

System.out.println(list02); //and it will be printed like this [[1000]]

 

list01 = new ArrayList<Integer>(); list01 is reset

for (int i = 0; i < 5; i++) {

list01.add(i); and has 0,1,2,3,4 added to it.

}

list02.add(list01); then list01 is added back to list02

 

System.out.println(list02);// [[1000, 0, 1, 2, 3, 4], [1000, 0, 1, 2, 3, 4]] this leads to a duplication as there are now two list01s. Since there was already a list01 in list02

}

list01 =new ArrayList<Integer>();

list01.add(10);

list02.add(list01);

System.out.println(list02); //[[1000], [0, 1, 2, 3, 4], [10]]

 

 

public static void main(String[] args) {

List<DTO> list = new ArrayList<DTO>();

DTO d = new DTO();

d.number = 1;

list.add(d);

list.add(d);

 

d = new DTO();

d.number = 3;

list.add(d);

 

System.out.println(list); //[coll.DTO@1e6d1014, coll.DTO@1e6d1014, coll.DTO@76707e36]

 

}

public static void main(String[] args) {

List<DTO> list = new ArrayList<DTO>();

DTO d = new DTO();

d.number = 1;

list.add(d);

list.add(d);

 

d = new DTO();

d.number = 3;

list.add(d);

 

System.out.println(list); //[coll.DTO@1e6d1014, coll.DTO@1e6d1014, coll.DTO@76707e36]

list.get(0).number = 100;

 

System.out.println(list.get(0).number);//100

System.out.println(list.get(1).number);//100

System.out.println(list.get(2).number);//3

 

}