JAVA

Creating JSP: using lists and getter/setter & Collections continued

mossybeach 2024. 7. 4. 17:52

Creating a web page using Lists

Today we decided to use the List interface we learnt while studying about Collections and incorporate it into pulling data from a database and creating a functioning web page.

 

One of the problems we ran into last time was that the user id and password that was needed was unprotected.

So this time we:

  • stored the sensitive info in a seperate class so it can store the information under private
  • created a method that will help with retrieving the needed information to access the DB. => encapsulation

DTO, DAO, VO

https://velog.io/@leesomyoung/Java-DAO-DTO-VO%EC%9D%98-%EA%B0%9C%EB%85%90

 

We also briefly touched on the concept of DTO, DAO and VO. 

 

  •  Data Transfer Object: object that transfers information from a DB
    has and uses getter/setter, there are no other logic than this: mainly used to get private info
  • Value Object: elements defined solely by their attributes( email addresses, phone numbers, dates)
  • Data Access Object: object that connects to a DB (url, id, pw -> DAO)

CRUD: Create, Read, Update and Delete

the four essential operations for creating and managing persistent data elements


class EmployeeDTO: 

to retrieve private info stored in a simple use of private fields and getter/setter methods. 

public class EmployeeDTO {

 

private int emp_no;

private String birth_date;

private String first_name;

private String last_name;

private char gender;

private String hire_date;

 

public int getEmp_no() {

return emp_no;

}

public void setEmp_no(int emp_no) {

this.emp_no = emp_no;

}

public String getBirth_date() {

return birth_date;

}

public void setBirth_date(String birth_date) {

this.birth_date = birth_date;

}

public String getFirst_name() {

return first_name;

}

public void setFirst_name(String first_name) {

this.first_name = first_name;

}

public String getLast_name() {

return last_name;

}

public void setLast_name(String last_name) {

this.last_name = last_name;

}

public char getGender() {

return gender;

}

public void setGender(char gender) {

this.gender = gender;

}

public String getHire_date() {

return hire_date;

}

public void setHire_date(String hire_date) {

this.hire_date = hire_date;

}

}


class DBConnection:

where we created method getConnection to put together info needed to access the DB.

This should be converted as a singleton method so only one DBConnection method can be called: security

import java.sql.Connection;

 

public class DBConnection {

public Connection getConnection() { //created a method called getConnection()

 

Connection conn = null;

 

try {

Class.forName("org.mariadb.jdbc.Driver"); //searches for Driver in our mariadb jar file

// url, user, pw

String url = "jdbc:mariadb://redacted/employees"; //stores the url to access the server

conn = DriverManager.getConnection(url, "redacted", "redacted"); //and creates a keycard that will let stmt access the DB.

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

}

return conn;

}

}


DBData class and getEmployees method:

where we use the EmployeeDTO and DBConnection method to access the data and store it in rs.

This is important as we need to create a list that is able to store the exact type of data that EmployeeDTO is giving.

public class DBData {

 

public List<EmployeeDTO> getEmployees() {

 

Connection conn = null;

Statement stmt = null;

ResultSet rs = null;

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

 

We use List here to create a EmployeeDTO class list that will store the results.

List<EmployeeDTO> result = new ArrayList<EmployeeDTO>()

 

DBConnection dbConnection = new DBConnection();  

conn = dbConnection.getConnection(); //calling getConnection method here to retrieve the keycard 

 

try {

stmt = conn.createStatement();//DAO form

rs = stmt.executeQuery(sql);

 

//using the getter/setter method within a while loop from EmployeeDTO to store the different rs values retrived from the DB

while(rs.next()) {

EmployeeDTO dto = new EmployeeDTO();

 

new dto class created above > uses the method to receive the parameters set (int in this case) which is stored in rs > using the getInt method, searching for the columnlabel from the DB.

dto.setEmp_no(rs.getInt("emp_no"));  

 

dto.setBirth_date(rs.getString("birth_date"));

dto.setFirst_name(rs.getString("first_name"));

dto.setLast_name(rs.getString("last_name"));

dto.setGender(rs.getString("gender").charAt(0));

dto.setHire_date(rs.getString("hire_date"));

 

result.add(dto); //using the add() method for lists.

}

} catch (SQLException e) {

e.printStackTrace();

 

} finally {

if(rs != null) {

 

try {

rs.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if(stmt != null) {

 

try {

stmt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

if(conn != null) {

 

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

return result;

}

}


index.jsp: printing the info on the web page

We input the data retrieved by using a foreach loop and assigning each dto.method() to a td.

<%@page import="web.EmployeeDTO"%>

<%@page import="java.util.List"%>

<%@page import="web.DBData"%>

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

pageEncoding="UTF-8"%>

 

<%

//java

DBData dbData = new DBData();

List<EmployeeDTO> data = dbData.getEmployees();

%>

 

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Index</title>

</head>

 

<body>

<h1>Company Info<3</h1>

<hr />

<table align="center">

<thead>

<tr>

<th>회원번호</th>

<th>생년월일</th>

<th>이름</th>

<th></th>

<th>성별</th>

<th>입사일</th>

</tr>

</thead>

 

<tbody align="center">

<%

for (EmployeeDTO dto : data) {

%>

<tr>

<td><%=dto.getEmp_no()%></td>

<td><%=dto.getBirth_date()%></td>

<td><%=dto.getFirst_name()%></td>

<td><%=dto.getLast_name()%></td>

<td><%=dto.getGender()%></td>

<td><%=dto.getHire_date()%></td>

</tr>

<%

}

%>

</tbody>

</table>

<a href="main.jsp">main.jsp로 이동</a>

<a href="static.html">정적페이지로 이동</a>

</body>

</html>

 


Sets

After learning about Collections, mainly lists yesterday. Today we looked at sets.

 

Sets, to recap, are a type of interface of Collections that can store value:

  • however they can't store duplicated info and will automatically delete it
  • doesn't use an index so there is no order.

This is what they look like:

Set<String> set = new HashSet<String>()                                                                                                                              ;

 

 

Example 1: using Set

public static void main(String[] args) {

Set<String> set = new HashSet<String>();

set.add("홍길동");

set.add("이길동");

set.add("정길동");

set.add("김길동");

set.add("이길동");

 

System.out.println(set); //[정길동, 김길동, 홍길동, 이길동]

}

Unfortunately with sets, we cannot print them out one by one using a for loop, we can only print out the entire thing. Either we need to convert them to an Array or assign it to something else: like the example below, where we turn it into a list.

 

 

Example 2: converting a Set into a List

List<String> list = new ArrayList<String>(set); //assign set into the brackets of the new List

for (String string : list) { //then use a forEach loop to print out one by one

System.out.println(string);

/*정길동

김길동

홍길동

이길동*/

}

//we can also store this in another list

List<String> linkedList01 = new ArrayList<String>(set);

System.out.println(linkedList01);

 

 

Example 3: creating a lotto with Set

public static void main(String[] args) {

 

Set<Integer> lotto = new HashSet<Integer>();

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

// int num = (int) (Math.random()* 45) + 1);

// System.out.println(num);

//

// lotto.add(num);

// }

System.out.println(lotto);

lotto.clear(); //You can do it this way

 

while(lotto.size() < 6) {

lotto.add((int) (Math.random()* 45) + 1);

} //but you can also just use three lines to print the same out using a while loop

System.out.println(lotto);

}


Map

Finally we look at Maps, they take two generic types: <K> and <V> (key and value). Maps can't store duplicate keys but can store the same values.

 

Example:

public static void main(String[] args) {

Map<String, String> map = new HashMap<String, String>();

//since maps can't store duplicate keys, it will save the last duplicate key entered = 귀여운 = 루피

map.put("우왕", "뽀로로다");

map.put("잔망", "루피");

map.put("똑쟁이", "에디");

map.put("귀여운", "루피");

map.put("똑쟁이", "패티");

 

System.out.println(map); //{똑쟁이=패티, 잔망=루피, 귀여운=루피, 우왕=뽀로로다}

 

String str = map.get("귀여운");  for get() instead of using index we use key to fetch the value it stores.

System.out.println(str); //루피

 

Set<String> set = map.keySet(); // retrieves all the keys stored in the map

System.out.println(set); //[똑쟁이, 잔망, 귀여운, 우왕]

}

More methods for Map:

containsKey() : returns boolean value with string entered in bracket to check if there is a key that matches.

containsValue(): returns boolean value when string is entered in bracket to check if there's a value that matches.

System.out.println(map.containsKey("가나다"));//false

System.out.println(map.containsKey("똑쟁이"));//true

System.out.println(map.containsValue("크롱"));//false

 


Auto-boxing / Auto-unboxing: wrapper classes

Collections can only contain Reference types, primitives can't.

Therefore, we need wrapper classes to convert p types to r types and there are wrapper classes for every p.

This works by storing the p types into a member's field value and surrounding it with a method that returns this value.

Auto-boxing: when Java recognises that a p type is assigned to a wrapper class and needs conversion.

Integer integer1 = 3000;

// translates it to Integer integer1 =  new Integer(3000); so java can understand

 

Auto-unboxing: when the value exits the wrapper class to be applied to a p type:

int number = integer1;

'JAVA' 카테고리의 다른 글

Java GUI: AWT & Swing  (0) 2024.07.10
Threads: an intro  (0) 2024.07.09
Importing data into JSP, Java Collection Framework: Lists  (0) 2024.07.03
Interface and Exceptions  (0) 2024.07.02
Recap of Access Modifiers and deep dive into 4 pillars of OOP  (0) 2024.07.01