Main funtions 

1. Connection Pool

2.  Action tags : <jsp:useBean...> / <jsp:setProperty...>

3. DTO, DAO class 

4. Paging ( inline view)

5. Uploading files ( using cos.jar library)

 

dbcpAPITest.jsp 

To check the connection

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
 	Connection conn = null; 
	
	try {
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		conn = ds.getConnection();
  		
  		out.println("<h3>Connected.</h3>");
	}catch(Exception e){
		out.println("<h3>Failed to connect.</h3>");
		e.printStackTrace();
 	}
%>

Create a SQL file and create a table and sequence. 

BoardDatabean.java(DTO)

package upload;

import java.sql.Timestamp;

public class BoardDatabean {
	private int num;
	private String writer;
	private String email;
	private String subject;
	private String passwd;
	private Timestamp reg_date;
	private int readcount;
	private String content;
	private String ip;
	private String upload;
	public int getNum() {
		return num;
	}
	public String getWriter() {
		return writer;
	}
	public String getEmail() {
		return email;
	}
	public String getSubject() {
		return subject;
	}
	public String getPasswd() {
		return passwd;
	}
	public Timestamp getReg_date() {
		return reg_date;
	}
	public int getReadcount() {
		return readcount;
	}
	public String getContent() {
		return content;
	}
	public String getIp() {
		return ip;
	}
	public String getUpload() {
		return upload;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public void setReg_date(Timestamp reg_date) {
		this.reg_date = reg_date;
	}
	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public void setUpload(String upload) {
		this.upload = upload;
	}	
}

BoardDBBean.java(DAO)

This is the basics of DAO class, and we will keep adding more codes. 

package upload;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BoardDBBean {
	// Singleton
	private static BoardDBBean instance = new BoardDBBean(); 
	public static BoardDBBean getInstance(){ // static field
	return instance;
	}

	// Method that gets connection from the Connection Pool
	private Connection getConnection() throws Exception{
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		return ds.getConnection();
	}
}

writeForm.jsp

<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Your Post</b>
<br>
<form method="post" name="writeform" action="writePro.jsp"
	  enctype="multipart/form-data">  

<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp"> Posts</a> 
   </td>
   </tr>
   <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Name</td>
    <td  width="330">
       <input autofocus type="text" size="10" maxlength="10" id="writer" name="writer"></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Title</td>
    <td  width="330">    
       <input type="text" size="40" maxlength="50" id="subject" name="subject"></td>	
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Email</td>
    <td  width="330">
       <input type="text" size="40" maxlength="30" id="email" name="email" ></td>
  </tr>
  <tr>
    <td  width="70"  bgcolor="<%=value_c%>" align="center">Attach File</td>
    <td  width="330">
       <input type="file" size="40"  name="upload" ></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Content</td>
    <td  width="330" >
     <textarea id="content" name="content" rows="13" cols="40"></textarea> </td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Post" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp'">
</td></tr></table>    
   
</form>      
</body>
</html>

 

writePro.jsp

<%@page import="upload.BoardDBBean"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	// Location of Directory
String path = request.getRealPath("upload");
System.out.println("path: " + path);

// Size of the files : 1MB
int size = 1024 * 1024;

// To upload files -> MultipartRequest object
MultipartRequest multi = new MultipartRequest(request, 
		path, // Location of Directory 
		size, // Size 
		"utf-8", // Encoding type
		new DefaultFileRenamePolicy()); // Overlapped files

String writer = multi.getParameter("writer");
String subject = multi.getParameter("subject");
String email = multi.getParameter("email");
String content = multi.getParameter("content");
String passwd = multi.getParameter("passwd");

// Original file name: file name uploaded by the client
String upload0 = multi.getOriginalFileName("upload");

// Save file name 
String upload = multi.getFilesystemName("upload");

BoardDataBean board = new BoardDataBean();
board.setWriter(writer);
board.setEmail(email);
board.setSubject(subject);
board.setContent(content);
board.setPasswd(passwd);
board.setIp(request.getRemoteAddr()); // Client's IP address
board.setUpload(upload); // Saved file's name

BoardDBBean dao = BoardDBBean.getInstance();
int result = dao.insert(board);

if (result == 1) {
%>

<script>
	alert("Posted successfully.");
	location.href = "list.jsp";
</script>
<%
	} else {
%>
<script>
	alert("Failed to post.");
	history.go(-1);
</script>

<%
	}
%>

list.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="java.util.List"%>
<%@page import="upload.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%

	int page_size = 10;

	String pageNum = request.getParameter("page");
	if(pageNum == null){
		pageNum = "1";		
	}
	
	int currentPage = Integer.parseInt(pageNum);
	
	int startRow = (currentPage - 1) * page_size + 1;
	int endRow = currentPage * page_size;
	
    // Total data 
	int count = 0;
	
	BoardDBBean dao = BoardDBBean.getInstance();
	count = dao.getCount();
	System.out.println("count:"+count);
	
	List<BoardDataBean> list = null;
	if(count > 0){
		list = dao.getList(startRow, endRow);
	}
	System.out.println("list:"+list);
%>      
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
	if(count == 0){
%>
		No posts yet.
<%	}else{ %>
	
		<a href="writeForm.jsp">Write</a> Total posts : <%=count %>
		<table border=1 width=700 align=center>
			<caption>List</caption>
			<tr>
				<th>No.</th>
				<th>Title</th>
				<th>Writer</th>
				<th>Date</th>
				<th>View</th>
				<th>IP Address</th>
			</tr>
<%
			// start number
			int number = count - (currentPage-1) * page_size;

			SimpleDateFormat sd = 
					new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			for(int i=0; i<list.size(); i++){
				BoardDataBean board = list.get(i);
%>				
			<tr>
				<td><%=number-- %></td>
				<td>
				
<a href="content.jsp?num=<%=board.getNum()%>&page=<%=currentPage%>">				
				<%=board.getSubject() %>
</a>	
			
				</td>
				<td><%=board.getWriter() %></td>
				<td><%=sd.format(board.getReg_date()) %></td>
				<td><%=board.getReadcount() %></td>
				<td><%=board.getIp() %></td>
			</tr>			
				
<%			} // for end
%>
			
		</table>	
		
<%	} // else end
%>

<!-- Page Link -->
<center>
<%
if(count > 0){
	
	int pageCount=count/page_size + ((count%page_size==0) ? 0:1);
	System.out.println("pageCount:"+pageCount);

	// startRow & endRow
	// 1 page : startRow=1,  endRow=10
	// 2 page : startRow=11, endRow=20
	// 3 page : startRow=21, endRow=30
	int startPage = ((currentPage-1)/10) * 10 + 1;
	int block = 10;	
	int endPage = startPage + block - 1;
	
	if(endPage > pageCount){
		endPage = pageCount;
	}
%>	
	<!-- Move to page 1 -->
	<a href="list.jsp?page=1" style="text-decoration:none"> << </a>

<%
	// Previous block
	if(startPage > 10){
%>	
		<a href="list.jsp?page=<%=startPage-10%>">[Prev]</a>	
<%	}	


	for(int i=startPage; i<=endPage; i++){
		if(i==currentPage){ 		 %>
				[<%=i%>]
<% 		}else{ %>
				<a href="list.jsp?page=<%=i%>">[<%=i%>]</a>
<% 		}	
	} // for end

	// Next block
	if(endPage < pageCount){ %>
			<a href="list.jsp?page=<%=startPage+10%>">[Next]</a>		
<%	}  %>
	
	<!-- Move to the last page -->
		<a href="list.jsp?page=<%=pageCount%>"
			style="text-decoration:none"> >> </a>			
<%	
}
%>
</center>

</body>
</html>

content.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

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

BoardDBBean dao = BoardDBBean.getInstance();

// view count +1 & get detail 
BoardDataBean board = dao.updateContent(num);

SimpleDateFormat sd = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

String content = board.getContent().replace("\n", "<br>");
%>


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Detail</title>
</head>
<body>
	<table border=1 width=500 align=center>
		<caption>Detail</caption>
		<tr>
			<td>No.</td>
			<td><%=board.getNum()%></td>
			<td>View</td>
			<td><%=board.getReadcount()%></td>
		</tr>
		<tr>
			<td>Writer</td>
			<td><%=board.getWriter()%></td>
			<td>Date</td>
			<td><%=sd.format(board.getReg_date())%></td>
		</tr>
		<tr>
			<td>Title</td>
			<td colspan=3><%=board.getSubject()%></td>
		</tr>
		<tr>
			<td>Content</td>
			<td colspan=3><%=board.getContent()%> <%=content%></td>
		</tr>
		<tr>
			<td>Attached File</td>
			<td colspan=3>
				<!-- If there is files to attach --> <%
 	if (board.getUpload() != null) {
 %> <a href="file_down.jsp?file_name=<%=board.getUpload()%>"> <%=board.getUpload()%>
			</a> <%
 	}
 %>
			</td>
		</tr>
		<tr>
			<td colspan=4 align=center><input type="button" value="Edit"
				onClick="location.href='updateForm.jsp?num=<%=num%>&page=<%=nowpage%>'">
				<input type="button" value="Delete"
				onClick="location.href='deleteForm.jsp?num=<%=num%>&page=<%=nowpage%>'">
				<input type="button" value="Go back to List"
				onClick="location.href='list.jsp?page=<%=nowpage%>'"></td>
		</tr>
	</table>

</body>
</html>

updateForm.jsp

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<%
	int num = Integer.parseInt(request.getParameter("num"));
	String nowpage = request.getParameter("page");
	
	BoardDBBean dao = BoardDBBean.getInstance();
	
	// To get detail 
	BoardDataBean board = dao.getContent(num);
%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Your Post</b>
<br>
<form method="post" name="writeform" action="updatePro.jsp"
	  enctype="multipart/form-data">  
<input type="hidden" name="num" value="<%=num %>">
<input type="hidden" name="page" value="<%=nowpage %>">


<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp?page=<%=nowpage%>"> Posts</a> 
   </td>
   </tr>
   <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Name</td>
    <td  width="330">
       <input autofocus type="text" size="10" maxlength="10" id="writer" name="writer" 
       value="<%=board.getWriter()%>"></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Title</td>
    <td  width="330">    
       <input type="text" size="40" maxlength="50" id="subject" name="subject" value="<%=board.getSubject()%>"></td>	
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center">Email</td>
    <td  width="330">
       <input type="text" size="40" maxlength="30" id="email" name="email" value="<%=board.getEmail()%>" ></td>
  </tr>
  <tr>
    <td  width="70"  bgcolor="<%=value_c%>" align="center">Attach File</td>
    <td  width="330">
       <input type="file" size="40"  name="upload" ><%=board.getUpload() %></td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Content</td>
    <td  width="330" >
     <textarea id="content" name="content" rows="13" cols="40"><%=board.getContent() %></textarea> </td>
  </tr>
  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Post" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp?page=<%=nowpage%>'">
</td></tr></table>    
   
</form>      
</body>
</html>

updatePro.jsp

<%@page import="upload.BoardDBBean"%>
<%@page import="upload.BoardDataBean"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>

<%
	// Location of Directory
String path = request.getRealPath("upload");
System.out.println("path: " + path);

// Size of the files : 1MB
int size = 1024 * 1024;

// To upload files -> MultipartRequest object
MultipartRequest multi = new MultipartRequest(request, 
		path, // Location of Directory 
		size, // Size 
		"utf-8", // Encoding type
		new DefaultFileRenamePolicy()); // Overlapped files
		
int num = Integer.parseInt(multi.getParameter("num"));
String nowpage = multi.getParameter("page");

String writer = multi.getParameter("writer");
String subject = multi.getParameter("subject");
String email = multi.getParameter("email");
String content = multi.getParameter("content");
String passwd = multi.getParameter("passwd");

// Original file name: file name uploaded by the client
String upload0 = multi.getOriginalFileName("upload");

// Save file name 
String upload = multi.getFilesystemName("upload");

BoardDataBean board = new BoardDataBean();
board.setNum(num);
board.setWriter(writer);
board.setEmail(email);
board.setSubject(subject);
board.setContent(content);
board.setPasswd(passwd);
board.setIp(request.getRemoteAddr()); // Client's IP address
// board.setUpload(upload); // Saved file's name

BoardDBBean dao = BoardDBBean.getInstance();
BoardDataBean old = dao.getContent(num);

if(upload != null){ //If the attached file is edited
	board.setUpload(upload);
}else{					// If the attached file is not edited
	board.setUpload(old.getUpload());
}

System.out.println(old.getPasswd());
System.out.println(passwd);

// To compare passwords
if(old.getPasswd().equals(passwd)) {
	int result = dao.update(board);
	
	if(result ==1){
	%>
<script>
	alert("Posted successfully.");
	location.href="list.jsp?page=<%=nowpage%>";
</script>

<% } 
	}else{ // Incorrect Password %>
<script>
	alert("Incorrect password.");
	history.go(-1);
</script>

<%
	}
%>

deleteForm.jsp

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ include file="color.jsp"%>

<%
	int num = Integer.parseInt(request.getParameter("num"));
	String nowpage = request.getParameter("page");
%>

<html>
<head>
	<title>Your Post</title>
	<link href="style.css" rel="stylesheet" type="text/css">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script src="check.js"></script>
</head>   

<body bgcolor="<%=bodyback_c%>">  
<center><b>Please enter your password to delete your post.</b>
<br>
<form method="post" name="writeform" action="deletePro.jsp"> 
<input type="hidden" name="num" value="<%=num %>">
<input type="hidden" name="page" value="<%=nowpage %>">


<table width="430" border="1" cellspacing="0" cellpadding="0"  bgcolor="<%=bodyback_c%>" align="center">
   <tr>
    <td align="right" colspan="2" bgcolor="<%=value_c%>">
	    <a href="list.jsp?page=<%=nowpage%>"> Posts</a> 
   </td>
   </tr>

  <tr>
    <td  width="100"  bgcolor="<%=value_c%>" align="center" >Password</td>
    <td  width="330" >
     <input type="password" size="8" maxlength="12" id="passwd" name="passwd"> 
	 </td>
  </tr>
<tr>      
 <td colspan=2 bgcolor="<%=value_c%>" align="center"> 
  <input type="submit" value="Delete" >  
  <input type="reset" value="Reset">
  <input type="button" value="List" OnClick="location.href='list.jsp?page=<%=nowpage%>'">
</td></tr></table>    
   
</form>      
</body>
</html>

deletePro.jsp

When it comes to deletion, the attached files have to be deleted along with the posts that are being deleted.

<%@page import="upload.BoardDataBean"%>
<%@page import="upload.BoardDBBean"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("utf-8");
%>

<jsp:useBean id="board" class="upload.BoardDataBean"/>
<jsp:setProperty property="*" name="board"/>

<%
	String nowpage = request.getParameter("page");

	String path = request.getRealPath("upload");
	System.out.println("Path: "+ path);
	
	BoardDBBean dao = BoardDBBean.getInstance();
	BoardDataBean old = dao.getContent(board.getNum());
	
	// To compare the passwords
	if(old.getPasswd().equals(board.getPasswd())){ 	// Correct password
		int result = dao.delete(old, path);
	if(result == 1) {
%>	
		<script>
			alert("Successfully deleted.");
			location.href="list.jsp?page=<%=nowpage%>";
		</script>
		<% } %>
<% 	}else { %> 							// Incorrect password
	<script>
		alert("Incorrect password.");
		history.go(-1);
	</script>
<% } %>

 

Please refer to my last post about deleting the attached file : 

2022.09.14 - [Java] - Deleting attached files

BoardDBBean.java

// DAO(Data Access Object)
package upload;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;


public class BoardDBBean {
	// Singleton
	private static BoardDBBean instance = new BoardDBBean(); 
	public static BoardDBBean getInstance(){ // static field
	return instance;
	}

	// Method that gets connection from the Connection Pool
	private Connection getConnection() throws Exception{
  		Context init = new InitialContext();
  		DataSource ds = (DataSource) init.lookup("java:comp/env/jdbc/orcl");
  		return ds.getConnection();
	}
	
	// insert method 
	public int insert(BoardDataBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			String sql="insert into upload values(upload_seq.nextval,?,?,?,?,";
				   sql+="sysdate,?,?,?,?)";
				   
				   pstmt = con.prepareStatement(sql);
				   pstmt.setString(1, board.getWriter());
				   pstmt.setString(2, board.getEmail());
				   pstmt.setString(3, board.getSubject());
				   pstmt.setString(4, board.getPasswd());
				   pstmt.setInt(5, board.getReadcount());    // view count
				   pstmt.setString(6, board.getContent());
				   pstmt.setString(7, board.getIp());
				   pstmt.setString(8, board.getUpload());
				   
				   result = pstmt.executeUpdate();  		// To execute the SQL 
				   
				   
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		return result;
	}
	
	// getCount Method
	public int getCount() {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select count(*) from upload";
			
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				result = rs.getInt(1);
				result = rs.getInt("count(*)");
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	// List : Extract 10 data
	public List<BoardDataBean> getList(int start, int end){
		List<BoardDataBean> list = new ArrayList<BoardDataBean>();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="select * from (select rownum rnum, upload.* from ";
				   sql+=" (select * from upload order by num desc) upload) ";
				   sql+=" where rnum >=? and rnum <=?";
				   
				   pstmt = con.prepareStatement(sql);
				   pstmt.setInt(1, start);
				   pstmt.setInt(2, end);
				   rs = pstmt.executeQuery();
				   
				   while(rs.next()) {
					   BoardDataBean board = new BoardDataBean();
					   
					   board.setNum(rs.getInt("num"));
					   board.setWriter(rs.getString("writer"));
					   board.setEmail(rs.getString("email"));
					   board.setSubject(rs.getString("subject"));
					   board.setSubject(rs.getString("subject"));
					   board.setPasswd(rs.getString("passwd"));
					   board.setReg_date(rs.getTimestamp("reg_date"));
					   board.setReadcount(rs.getInt("readcount"));
					   board.setContent(rs.getString("content"));
					   board.setIp(rs.getString("ip"));
					   board.setUpload(rs.getString("upload"));
					   
					   list.add(board);
				   }
			
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}
		return list;
	}
	
	// Detail page : view count +1 & detail information
	public BoardDataBean updateContent(int num) {
		BoardDataBean board = new BoardDataBean();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set readcount = readcount + 1 ";
				   sql+=" where num = ?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();	//To execute SQL
			
			sql="select * from upload where num = ?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				   board.setNum(rs.getInt("num"));
				   board.setWriter(rs.getString("writer"));
				   board.setEmail(rs.getString("email"));
				   board.setSubject(rs.getString("subject"));
				   board.setSubject(rs.getString("subject"));
				   board.setPasswd(rs.getString("passwd"));
				   board.setReg_date(rs.getTimestamp("reg_date"));
				   board.setReadcount(rs.getInt("readcount"));
				   board.setContent(rs.getString("content"));
				   board.setIp(rs.getString("ip"));
				   board.setUpload(rs.getString("upload"));
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}

		return board;
	}
	// Update : to get detail
	public BoardDataBean getContent(int num) {
		BoardDataBean board = new BoardDataBean();
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set readcount = readcount + 1 ";
				   sql+=" where num = ?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();	//To execute SQL
			
			sql="select * from upload where num = ?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				   board.setNum(rs.getInt("num"));
				   board.setWriter(rs.getString("writer"));
				   board.setEmail(rs.getString("email"));
				   board.setSubject(rs.getString("subject"));
				   board.setSubject(rs.getString("subject"));
				   board.setPasswd(rs.getString("passwd"));
				   board.setReg_date(rs.getTimestamp("reg_date"));
				   board.setReadcount(rs.getInt("readcount"));
				   board.setContent(rs.getString("content"));
				   board.setIp(rs.getString("ip"));
				   board.setUpload(rs.getString("upload"));
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
			if(rs != null) try { rs.close();} catch(Exception e) {}
		}

		return board;
	}
	
	// Update method
	public int update(BoardDataBean board) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="update upload set writer=?,email=?,subject=?,";
				   sql+="content=?,ip=?,upload=? where num=?";
				   
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, board.getWriter());
			pstmt.setString(2, board.getEmail());
			pstmt.setString(3, board.getSubject());
			pstmt.setString(4, board.getContent());
			pstmt.setString(5, board.getIp());
			pstmt.setString(6, board.getUpload());
			pstmt.setInt(7, board.getNum());
			
			result = pstmt.executeUpdate();   // To execute SQL 
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	// Delete the post & attached file
	public int delete(BoardDataBean board, String path) {
		int result = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		
		try {
			con = getConnection();
			
			String sql="delete from upload where num=?";
			
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, board.getNum());
			result = pstmt.executeUpdate();			// To execute SQL 
			
			if(board.getUpload() != null) { // if there is any file attached
				
				File file = new File(path);
				
				// To read all files in the upload directory
				File[] f = file.listFiles();
				
				for(int i=0; i<f.length; i++) {
					
					if(f[i].getName().equals(board.getUpload())) {
						f[i].delete(); 		// To delete the attached file
					}
				}
			}
			
		}catch(Exception e) {
			
		}finally {
			if(pstmt != null) try { pstmt.close();} catch(Exception e) {}
			if(con != null) try { con.close();} catch(Exception e) {}
		}
		
		return result;
	}
	
	
}

index.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>

	<script>
		location.href = "upload1/list.jsp";
	</script>

</body>
</html>

In the last posts, we covered the basic concepts of Model2 and Java Servlet class. 

This post will explore more ways and functions to build programs. 

If you want to refer to my last post, please click the link below : 

2022.09.15 - [JSP] - JSP) Model1 vs Model2

2022.09.15 - [JSP] - JSP) Model2 - Java Servlet 1

 

Example 1 : Log in

LoginServlet.java

This program is processed only with the post method, so we don't need to fill out the doGet method.

There are two ways to forward the Java Servlet class to the JSP page:  Dispatcher method and Redirect method. 

1. Dispatcher method

RequestDispatcher dispatcher = request.getRequestDispatcher("dispatcher.jsp"); dispatcher.forward(request, response);

2. Redirect method

response.sendRedirect("redirect.jsp");

In this code, we will use the dispatcher method, which will also work with the redirect method. In the Example 2, we will discuss more about these methods.

package login;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();  // PrintWriter object

		String id = request.getParameter("id");
		String passwd = request.getParameter("passwd");
		if (id.equals("java") && passwd.equals("java")) {
			// Session object
			HttpSession session = request.getSession();
			session.setAttribute("id", id);		
			// 1. Dispatcher method 
			RequestDispatcher dispatcher = request.getRequestDispatcher("./servlet/ex666/loginSuccess.jsp");
			dispatcher.forward(request, response);
			
			// 2. Redirect method
//			response.sendRedirect("./servlet/ex666/loginSuccess.jsp");
		} else { 
			out.println("<script>");
			out.println("alert('Incorrect ID or password.')");
			out.println("history.back()");
			out.println("</script>");
		}
	}

}

index.html

With the <frameset> and <frame> tag, we can split the browser into two parts. 

<html>
<head>
<meta charset="utf-8">
<title>Index</title>
</head>
<frameset cols="30%,*">
	<frame src="/jsppro/servlet/ex666/menu.jsp" name="leftFrame" />
	<frame src="/jsppro/servlet/ex666/login.jsp" name="rightFrame" />
</frameset>
<body>

</body>
</html>

menu.jsp

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

<html>
	<head>
	<meta charset="utf-8">
	<title>Menu</title>
	</head>
<%
	String id = (String)session.getAttribute("id");
%>
<body>
<%
	if(id == null){
%>
   <a href="login.jsp" target="rightFrame" />Log in</a>
<% 
	}
	else{
%>
	Welcome, <%=id %>!
<%
	}
%>

</body>
</html>

login.jsp

The action is connected to the annotation in LoginServlet.java.

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

<html>
	<head>
	<meta charset="utf-8">
	<title>Log in</title>
	</head>
	<body>
	<form action="/jsppro/login" method="post">
		ID : <input type="text" name="id"/>
		Password : <input type="password" name="passwd"/><br>
		<input type="submit" value="login"/>
	</form>
</body>
</html>

loginSuccess.jsp

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

<html>
	<head>
	<meta charset="utf-8">
	<title>Log in success</title>
	<script>
	top.leftFrame.location.href="/jsppro/servlet/ex666/menu.jsp";
	</script>
	</head>
	<body>
		Successfully logged in.
	</body>
</html>

You will see this result if you insert ID- java / Password-java. 

Example 2

In this example, we will learn more specifically about two methods for forwarding: Dispatcher method and Redirect method. With these example codes, compare each method.

redirect.jsp

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

<html>
	<head>
	<meta charset="utf-8">
	<title>Insert title here</title>
	</head>
	<body>
	request Attribute value : <%=request.getAttribute("request") %>
	</body>
</html>

RedirectServlet.java

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 RedirectServlet
 */
@WebServlet("/RedirectServlet")
public class RedirectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RedirectServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

		request.setAttribute("request", "requestValue");
		response.sendRedirect("./servlet/ex777/redirect.jsp"); // forwarding 
	}

}

dispatcher.jsp

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

<html>
	<head>
	<meta charset="utf-8">
	<title>Insert title here</title>
	</head>
	<body>
	request Attribute value : <%=request.getAttribute("request") %>
	</body>
</html>

DispatcherServlet.java

package send;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
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 DispatcherServlet
 */
@WebServlet("/DispatcherServlet")
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DispatcherServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub 
		
		request.setAttribute("request","requestValue"); 
		
		RequestDispatcher dispatcher = 
				request.getRequestDispatcher("./servlet/ex777/dispatcher.jsp");
		dispatcher.forward(request, response);
	}

}

 

First flowchart

Second Flowchart

It looks very complicated and lacks visual attraction, but I tried and learned at least!

Third Flowchart after Feedback

Help: Omar Shalaby

 

After realizing "Think twice, Code once" is important, these are my first flow charts. I thought three times and coded twice, but it helped me to understand how my algorithms have to be.

 

First Code

import java.util.Scanner;

//Temperature Converter Far -> Cel / Cel -> Far
public class TempConverter {

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

		String num1;
		int tem, press;
		double num2, num3;
		// boolean tof = false;
		Scanner sc = new Scanner(System.in);

		System.out.println("Press 1 to convert Fahrenheit to Celsius, Press 2 to convert from Celsius to Fahrenheit. ");
		press = sc.nextInt();
		// while (true) {
		try {

			while (true) {
				if (press == 1) {
					System.out.println("Enter Fahrenheit.");
					sc.nextLine();// The "Enter" key after inputting the number is considered as one input.
					// By inserting this line, you can avoid the output of "Not a number" right
					// away.
					num1 = sc.nextLine();

					// while (true) {
					try {
						num2 = Double.parseDouble(num1);
						// To check if int is inserted or not.

						// formula: (32°F − 32) × 5/9 = 0°C
						num3 = ((((num2 - 32.0) * 5.0) / 9.0));
						System.out.printf("%.2f", num3);
						System.out.println();
						return;

					} catch (NumberFormatException n) {
						System.out.println("Not a number. Please enter again.");
						sc.nextLine();
					}
				} else if (press == 2) {
					System.out.println("Enter Celsius.");
					sc.nextLine();
					num1 = sc.nextLine();

					try {
						num2 = Double.parseDouble(num1);
						// To check if int is inserted or not.

						// (0°C × 9/5) + 32 = 32°F
						num3 = (((num2 * 9) / 5) + 32);
						System.out.printf("%.2f", num3);
						System.out.println();

					} catch (NumberFormatException nn) {
						System.out.println("Not a number.");

					}
				}
			}
		} catch (Exception e) {
			System.out.println("Invalid Access. Please enter again.");

		}

		// }

	}
}

Second Code(Final)

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class TempConverter2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			System.out.println("From Fahrenheit to Celsius press 1, vice versa, press 2.");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String inputString = br.readLine();
			int num = Integer.parseInt(inputString);

			if (num == 1) {
				farToCel();
			} else if (num == 2) {
				celToFar();
			} else {
				System.out.println("Not a valid access.");
			} 

		} catch (Exception eo) {
			System.out.println("Not a number.");
		}
	}

	public static void farToCel() {
		while (true) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				System.out.println("Please enter number.");
				String inputString = br.readLine();
				double far = Double.parseDouble(inputString);
				double result1 = ((((far - 32.0) * 5.0) / 9.0));

				System.out.printf("%.2f", result1);
				System.out.println();
				System.out.println("To repeat press anything, to finish, press F or f.");
				String inputString2 = br.readLine();
				if (inputString2.equals("F") || inputString2.equals("f")) {
					System.out.println("Finish the program.");
					break; // to go back to the main menu
				} else {
					continue;
				}
			} catch (Exception e) {
				System.out.println("Not a number.");
			}

		}
	}

	public static void celToFar() {
		while (true) {
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
				System.out.println("Please enter number.");
				String inputString = br.readLine();
				double cel = Double.parseDouble(inputString);
				double result2 = (((cel * 9) / 5) + 32);

				System.out.printf("%.2f", result2);
				System.out.println();
				System.out.println("To go repeat press anything, to finish, press F or f.");
				String inputString3 = br.readLine();
				if (inputString3.equals("F") || inputString3.equals("f")) {
					System.out.println("Finish the program.");
					break;
				} else {
					continue;
				}
			} catch (Exception ei) {
				System.out.println("Not a number.");
			}

		}
	}
}

 

 

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
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

 

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

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>

 

joinForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<head>
<title>Sign up</title>
</head>
<body>
	<!-- <h2><th><center>Sign Up</center></th></h2>-->
	<center>
		<form action="joinChk.jsp" method="post">
			<table border=0>
				<caption>
					<b>Sign Up</b>
				</caption>
				<tr>
					<td align=right bgcolor="green"><font size=2 color="white">ID
							: </font></td>
					<td bgcolor="green"><input type="text" name="id"></td>
				</tr>
				<tr>
					<td align=right bgcolor="blue"><font size=2 color="white">Password
							: </font></td>
					<td bgcolor="blue"><input type="password" name="pass"></td>
				</tr>
				<tr>
					<td align=right bgcolor="red"><font size=2>Name : </font></td>
					<td bgcolor="red"><input type="text" name="name"></td>
				</tr>
				<tr>
					<td align=right bgcolor="purple"><font size=2 color="white">Sex
							: </font></td>
					<td bgcolor="purple"><input type="radio" name="sex"
						value="Male" checked><font size=2 color="white">Male</font>
						<input type="radio" name="sex" value="Female"><font size=2
						color="white">Female</font> <input type="radio" name="sex"
						value="Prefer not to say"><font size=2 color="white">Prefer
							not to say</font></td>
				</tr>
				<tr>
					<td align=right bgcolor="yellow"><font size=2>Age : </font></td>
					<td bgcolor="yellow"><input type="text" name="age"></td>
				</tr>
				<tr>
					<td align=right bgcolor="orange"><font size=2>Email : </font></td>
					<td bgcolor="orange"><input type="text" name="email"></td>
				</tr>
				<tr>
					<td align=center bgcolor="gray" colspan=2><input type="submit"
						value="Join"> <input type="reset" value="Reset"></td>
				</tr>
			</table>
		</form>
	</center>
</body>
</html>

JoinBean.java

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

package join;

public class JoinBean {
	private String id;
	private String pass;
	private String name;
	private String sex;
	private int age;
	private String email;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

joinChk.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<%request.setCharacterEncoding("euc-kr");%>
<jsp:useBean id="join" class="join.JoinBean"/>
<jsp:setProperty name="join" property="*"/>

<html>
<head>
<title>Please Double-Check your information.</title>
</head>
<body>
<center>
<table border=1>
	<tr>
		<td bgcolor="yellow"><font size=2>ID : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="id"/></td>
	</tr>
	<tr>
		<td bgcolor="yellow"><font size=2>Password : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="pass"/></td>
	</tr>
	<tr>
		<td bgcolor="yellow"><font size=2>Name : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="name"/></td>
	</tr>
	<tr>
		<td bgcolor="yellow"><font size=2>Sex : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="sex"/></td>
	</tr>
	<tr>
		<td bgcolor="yellow"><font size=2>Age : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="age"/></td>
	</tr>
	<tr>
		<td bgcolor="yellow"><font size=2>Email : </td>
		<td bgcolor="yellow"><jsp:getProperty name="join" property="email"/></td>
	</tr>
</table>
</center>
</body>
</html>

 

<Template1>

main.jsp

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

<jsp:forward page="templateTest.jsp" >
  <jsp:param name="CONTENTPAGE" value="content.jsp"/>
</jsp:forward>

top.jsp

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

Top Menu:
<a href="#">About us</a>
<a href="#">Our products</a>

left.jsp

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

Left Menu: <br>
<a href="#">About us</a><br>
<a href="#">Our products</a>

bottom.jsp

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

Bottom Menu : Location | Privacy policy | Help | Contact

templateTest.jsp

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

<%
   String contentPage = request.getParameter("CONTENTPAGE");
%>

<html>
	<head><title>Template Page</title></head>

	<body>

	<table width="600" border="1" cellpadding="2" cellspacing="0" align=center>
		<tr height=80>
			<td colspan="2">
                <!-- Top -->
				<jsp:include page="top.jsp" flush="false" />

			</td>
		</tr>
		<tr height=300>
			<td width="150" valign="top">
				<!-- Left -->
				<jsp:include page="left.jsp" flush="false" />

			</td>
			<td width="350" valign="top">
				<!-- Body -->
				<jsp:include page="<%= contentPage %>" flush="false" />

			</td>
		</tr>
		<tr height=80>
			<td colspan="2">
				<!-- Bottom -->
				<jsp:include page="bottom.jsp" flush="false" />

		    </td>
		</tr>
	</body>
</html>

To load the menus in the content area, we need to set a link. To load, you need to make 2 more files, one to load the link, the other one, to bring the value.

top.jsp (Edited)

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

Top Menu:
<a href="main.jsp">HOME</a>
<a href="comp_forward.jsp">About us</a>
<a href="goods_forward.jsp">Our products</a>

comp_forward.jsp

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

<jsp:forward page="templateTest.jsp" >
  <jsp:param name="CONTENTPAGE" value="comp.jsp"/>
</jsp:forward>

comp.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>About us</title>
</head>
<body>
About us page
</body>
</html>

goods_forward.jsp

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

<jsp:forward page="templateTest.jsp" >
  <jsp:param name="CONTENTPAGE" value="goods.jsp"/>
</jsp:forward>

goods.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Products</title>
</head>
<body>
Products Page
</body>
</html>

Output

 

 

<Template2>

 

template.jsp

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

<%
	String pagefile = request.getParameter("page");
if (pagefile == null) {
	pagefile = "bestitem";
}
%>

<html>
<head>
<title>Template Test</title>
</head>
<body>
	<table width=960 height=500 border=1 color=gray align=center>
		<tr>
			<td height=43 colspan=3 align=left><jsp:include page="top.jsp" />
			</td>
		</tr>
		<tr>
			<td width=15% align=right valign=top><jsp:include
					page="left.jsp" /></td>
			<td colspan=2 align=center><jsp:include
					page='<%=pagefile + ".jsp"%>' /></td>
		</tr>
		<tr>
			<td width=100% height=40 colspan=3><jsp:include
					page="bottom.jsp" /></td>
		</tr>
	</table>
</body>
</html>

top.jsp

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

<a href="template.jsp?page=login">Login</a>
<a href="template.jsp?page=join">Join</a>

left.jsp

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

<center>
<a href="template.jsp?page=newitem">New</a><br><br>
<a href="template.jsp?page=bestitem">Best seller</a><br><br>
</center>

bottom.jsp

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

<center>Since 2018</center>

join.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
	<head><title>Sign up</title>
	<script>
	 function idcheck(){
		if(document.myform.id.value == ""){
			alert("Insert your ID");
			document.myform.id.focus();
			return false;
		}else{
			window.open("http://www.naver.com", "check", 
				"width=100, height=150, menubar=yes");
		}
	 }

	 function postcode(){
		window.open("http://www.daum.net","win1",
						"width=100,height=150");
	 }

	 function move(){
		if(document.myform.jumin1.value.length == 6)
			document.myform.jumin2.focus();
	 }

	 function check(){
		if(document.myform.id.value == ""){
			alert("Insert your ID.");
			document.myform.id.focus();
			return false;
		}
		if(document.myform.irum.value == ""){
			alert("Insert your name.");
			document.myform.irum.focus();
			return false;
		}
		if(document.myform.pass.value == ""){
			alert("Insert your password.");
			document.myform.pass.focus();
			return false;
		}
		if(document.myform.jumin1.value == ""){
			alert("Insert your ID number1.");
			document.myform.jumin1.focus();
			return false;
		}
		if(document.myform.jumin1.value.length != 6){
			alert("Invalid ID number1.");
			document.myform.jumin1.value="";
			document.myform.jumin1.focus();
			return false;
		}
		if(document.myform.jumin2.value == ""){
			alert("Insert your ID number2.");
			document.myform.jumin2.focus();
			return false;
		}
		if(document.myform.jumin2.value.length != 7){
			alert("Invalid ID number2.");
			document.myform.jumin2.value="";
			document.myform.jumin2.focus();
			return false;
		}
		if(!juminCheck(myform.jumin1.value +										myform.jumin2.value)) {
			alert("Invalid ID number.");
			document.myform.jumin1.value="";
			document.myform.jumin2.value="";
			myform.jumin1.focus();
			return false;
		}	
		if(document.myform.post1.value == ""){
			alert("Insert your postcode1.");
			document.myform.post1.focus();
			return false;
		}
		if(document.myform.post2.value == ""){
			alert("Insert your postcode2.");
			document.myform.post2.focus();
			return false;
		}
		if(document.myform.address.value == ""){
			alert("Insert your address.");
			document.myform.address.focus();
			return false;
		}
		if(document.myform.gender[0].checked ==  false &&
		   document.myform.gender[1].checked ==  false){
			alert("Select your sex.");
			return false;
		}
	
		cnt=0;
		n1 = myform.hobby.length; 
		for(i=0; i<n1; i++){
			if(myform.hobby[i].checked == true)
				cnt++;
		}
		if(cnt < 2){
			alert("Choose more than one hobby.");
			return false;
		}
		if(document.myform.intro.value == ""){
			alert("Fill out about me session");
			document.myform.intro.focus();
			return false;
		}		
		if(myform.job.options[1].selected == false &&
		   myform.job.options[2].selected == false &&
		   myform.job.options[3].selected == false ){	  
			alert("Select your profession.");
			return false;
		}
	 }// check() end

// ID check
function juminCheck(jumin) { //jumin ="8001011234567";
    var total = 0;
    var total2;
    total += parseInt(jumin.substr(0,1)) * 2;
    total += parseInt(jumin.substr(1,1)) * 3;
    total += parseInt(jumin.substr(2,1)) * 4;
    total += parseInt(jumin.substr(3,1)) * 5;
    total += parseInt(jumin.substr(4,1)) * 6;
    total += parseInt(jumin.substr(5,1)) * 7;
    total += parseInt(jumin.substr(6,1)) * 8;
    total += parseInt(jumin.substr(7,1)) * 9;
    total += parseInt(jumin.substr(8,1)) * 2;
    total += parseInt(jumin.substr(9,1)) * 3;
    total += parseInt(jumin.substr(10,1)) * 4;
    total += parseInt(jumin.substr(11,1)) * 5;

    total %= 11;// total = total % 11;
    total2 = 11 - total;
    if(total2 > 9)
        total2 = total2 % 10;

    if(total2 != parseInt(jumin.substr(12,1))) {
        return (false);
    }else{
        return (true);
	}
}
	</script>
	</head>
	<body onLoad="document.myform.id.focus()">
	<form name=myform method=get action=send.jsp 
		  onSubmit="return check()">
	ID : <input type=text size=15 name=id>
		 <input type=button value="IDcheck" onclick="idcheck()"><br>
	Name : <input type=text name=irum><br>
	Password : <input type=password name=pass><br>
	ID No. : <input type=text size=6 maxlength=6						      name=jumin1	onKeyup="move()">-
			   <input type=text size=7 maxlength=7		            name=jumin2><br>
	Postcode : <input type=text size=3 maxlength=3							  name=post1>-
			   <input type=text size=3 maxlength=3                  name=post2>
			   <input type=button value="Search"
					   onClick="postcode()"><br>
	Address : <input type=text size=50 name=address> <br>	
	Sex : <input type=radio name=gender value=m>Male
		   <input type=radio name=gender value=f>Female <br>
	Hobby : <input type=checkbox name=hobby value="Studying"> Studying
		   <input type=checkbox name=hobby value="Reading"> Reading
		   <input type=checkbox name=hobby value="Hiking"> Hiking
		   <input type=checkbox name=hobby value="Fishing"> Fishing <br>
	About me :<textarea rows=10 cols=30 name=intro>Please write about you.</textarea> <br>
	Profession : <select name=job>
				<option>--Select--</option>
				<option value="Professor">Professor</option>
				<option value="Student">Student</option>
				<option value="Programmer">Programmer</option>
		   </select> <br>
	Attach File : <input type=file name=myfile> <br>	
	
	<input type=submit value="Join">
	<input type=reset value="Cancel">
	</form>

	</body>
</html>

login.jsp

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

<html>
	<head><title>Log in</title>
	<script>
	function check(){
		if(document.myform.id.value == ""){
			alert("Insert your ID.");
			document.myform.id.focus();
			return false;
		}
		if(document.myform.pass.value == ""){
			alert("Insert your password.");
			document.myform.pass.focus();
			return false;
		}		
	}	
	</script>
	</head>
	<body>
	<form onSubmit="return check()" name=myform 
			action=send.jsp method=post>
		<table border=1 width=300 align=center>
			<tr><td>ID</td>
				<td><input type=text name=id></td>
			</tr>
			<tr><td>Password</td>
				<td><input type=text name=pass></td>
			</tr>
			<tr><td colspan=2 align=center>
					<input type=submit value="Log in">
					<input type=reset value="Cancel">
				</td>
			</tr>
		</table>
	</form>
	</body>	
</html>

bestitem.jsp

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

<b>Best seller list</b>

newitem.jsp

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

<b>New products</b>

 

 

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

JSP/ Oracle) Members list  (0) 2022.08.31
JSP / CSS ) Sign up - JavaBean, Action tags  (0) 2022.08.31
JSP) Log in / Shopping cart  (0) 2022.08.29
HTML / Javascript / JSP ) Sign up Form2  (0) 2022.08.28
HTML / Javascript /JSP ) Bulletin Board  (0) 2022.08.28

Login.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>login.jsp</title>
</head>
<body>
<center>
	<H2>Log In</H2>
	<form name="form1" method="POST" action="selProduct.jsp">
		<input type="text" name="username"/>
		<input type="submit" value="Log In"/>
	</form>
</center>
</body>
</html>

cart.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>selProduct.jsp</title>
</head>
<%
	request.setCharacterEncoding("euc-kr");
	session.setAttribute("username",request.getParameter("username"));
%>
<body>
<center>
	<H2>Select</H2>
	<HR>
	<%=session.getAttribute("username") %>is logged in.

	${username}
	<HR>
	<form name="form1" method="POST" action="add.jsp">
		<SELECT name="product">
			<option>Appple</option>
			<option>Orange</option>
			<option>Pineapple</option>
			<option>Grapes</option>
			<option>Lemon</option>
		</SELECT>
		<input type="submit" value="Add"/>
	</form>
	<a href="checkOut.jsp">Check out</a>
</center>
</body>
</html>

add.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.ArrayList"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%	

	request.setCharacterEncoding("euc-kr");

	// To read parameters
	String productname = request.getParameter("product");

	// To bring the productlist
	ArrayList list = (ArrayList)session.getAttribute("productlist");

	if(list == null) {
		list = new ArrayList();
	}

	// Add data in the list
	list.add(productname);
	session.setAttribute("productlist",list);
%>

	<script>
		alert("<%=productname %> is added in your cart.");
		history.go(-1);
	</script>
</body>
</html>

 

checkOut.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" import="java.util.ArrayList"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center>
<H2>Check out</H2>
Your cart
<HR>
<%

	ArrayList list = (ArrayList)session.getAttribute("productlist");

	// No product is selected
	if(list == null) {
		out.println("No product is selected");
	}
	else {

		// To print out the list
		for(Object productname:list) {
			out.println(productname+"<BR>");
		}
	}
%>
</center>
</body>
</html>

 

+ Recent posts