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>

 

The <jsp:include>action tag includes other pages along with (<%@include file=heheader.jsp" %>).
While the include directive simply contains text from a specific source, the <jsp:include> action tag includes the processing results of the page. You can include HTML, JSP, Servlet, and etc.

Let us look at the examples for a better understanding.

 

<Example 1>

incldeForm.jsp

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

<html>
	<body>

	<h1>include Example</h1>

	<form method=post action="includeMain.jsp">
	Name : <input type="text" name="name"><p>
	<input type="submit" value="Submit">
	</form>	

	</body>
</html>

includeMain.jsp

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

<html>
	<body>

	<h1>includeMain.jsp</h1>

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

	<hr>

	<jsp:include page="includeSub.jsp" flush="false"/>
	includeMain.jsp's content

	</body>
</html>

includeSub.jsp

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

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

 includeSub.jsp<p>
<b>Hey, <%=name%>!</b>
<hr>

So, in the browser, you will see includeMain.jsp page including includeSub.jsp page.

 

<Example 2>

incldeForm2.jsp

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

<html>
	<body>

	<h2>include Example2</h2>

	<form method=post action="includeMain2.jsp">
	Site Name : <input type="text" name="siteName1"><p>
				<input type="submit" value="Submit">
	</form>

	</body>
</html>

includeMain2.jsp

Here, <jsp:param> convey the "siteName" to this file from includeForm2.jsp.

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

<html>
	<body>
	
	<h2>includeMain2.jsp Page</h2>

	<%
		request.setCharacterEncoding("euc-kr");
		String siteName1 = request.getParameter("siteName1");
	%>

	<hr>
	<jsp:include page="includeSub2.jsp">
		<jsp:param name="siteName" value="<%=siteName1%>"/>
	</jsp:include>

	includeMain2.jsp Page Content<p>

	</body>
</html>

includeSub2.jsp

With the request object, the siteName is conveyed to the includeSub2.jsp.

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

<html>
	<body>

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

	includeSub2.jsp Page<p>

	<b><%=siteName%></b>
	<hr>

	</body>
</html>

Both include directive tag and include action tag are similar in that they all include other pages, but the include directive tag contains only the text, whereas the include action tag contains the results of the page's processing.

 

Here is another example. 

 

<Example 3>

includer.jsp

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

<html>
	<head><title>include Directive</title></head>
	<body>

<%
    int number = 10;
%>

<%@ include file="includee.jspf" %>

Common Variable DATAFOLDER = "<%= dataFolder %>"

	</body>
</html>

includee.jspf

The 'f' in jspf means 'fraction'.

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

Number saved in includer.jsp page: <%= number %>

<p>

<%
    String dataFolder = "c:\\data";
%>

 

'Java > JSP' 카테고리의 다른 글

JSP) JSP and Oracle  (0) 2022.08.31
JSP) JavaBean  (0) 2022.08.31
JSP) Handling Exceptions  (0) 2022.08.30
JSP) Action tags - forward  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29

There are two ways to handle exceptions in JSP: by errorPage and isErrorPage attributes of page directive and by <error-page> element in web.xml file. 

Let's first get to know about the formal way. 

 

Handling Exception using page directive attributes

Two attributes can be used in JSP: errorPage and isErrorPage.

 

errorPage 

 <%@page errorPage="url of the error page"%>

isErrorPage 

 <%@page isErrorPage="true"%>

If the attribute of isErrorPage is true, it is designated as an error page. 

 

Let's discuss it more with some examples. 

In this code, there is no value in the name parameter; yet, we didn't handle the exception, so you will encounter the HTTP status code 500.

<%@ page contentType = "text/html; charset=utf-8" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

Parameter value of name: <%= request.getParameter("name").toUpperCase() %>

</body>
</html>

with errorPage attribute

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page errorPage = "/error/viewErrorMessage.jsp" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

Parameter value of name: <%= request.getParameter("name").toUpperCase() %>

</body>
</html>

vieErrorMessage.JSP

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page isErrorPage = "true" %>
<html>
<head><title>Error</title></head>
<body>

Sorry, an error occurred while processing your request.<br>
<p>
Error type: <%= exception.getClass().getName() %> <br>
Error message: <b><%= exception.getMessage() %></b>
</body>
</html>

You can also use try ~ catch like Java.

<%@ page contentType = "text/html; charset=utf-8" %>
<html>
<head><title>Print out Parameter</title></head>
<body>

name parameter value: 
<% try { %>
<%= request.getParameter("name").toUpperCase() %>
<% } catch(Exception ex) { %>
Wrong name parameter.
<% } %>
</body>
</html>

 

The error data should exceed 512 bytes. If the length of the error page is less than 512 bytes, Internet Explorer does not print the error page that this page prints It outputs its own 'HTTP error message' screen. To print the contents of an error page correctly in Internet Explorer, you need to include the same in responding to this comment. 

 

errorPage 02

<%@ page contentType = "text/html; charset=utf-8" %>
<%@ page buffer="1kb" %>
<%@ page errorPage = "/error/viewErrorMessage.jsp" %>
<html>
<head><title>Buffer flush Exception</title></head>
<body>

<%  for (int i = 0 ; i < 300 ; i++) { out.println(i); }  %>

<%= 1 / 0 %>

</body>
</html>

So far, we have discussed the formal way of handling exceptions, but unless you have just several pages, you will need to use the latter way to handle exceptions using error-page element en web.xml file.

Instead of the errorPage directive, the error page can be specified in the web.xml file of <error-page> tags.

The web.xml file has to be in WEB-INF folder. Anything you need, to handle the exceptions, you have to put in the web.xml file. Here is the web.xml file.

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
	id="WebApp_ID" version="4.0">
	<display-name>jspproject</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<error-page>
		<error-code>404</error-code>
		<location>/error/error404.jsp</location>
	</error-page>

	<error-page>
		<error-code>500</error-code>
		<location>/error/error500.jsp</location>
	</error-page>

	<error-page>
		<exception-type>java.lang.NullPointerException</exception-type>
		<location>/error/errorNullPointer.jsp</location>
	</error-page>

</web-app>

 

'Java > JSP' 카테고리의 다른 글

JSP) JavaBean  (0) 2022.08.31
JSP) Action tags - include  (0) 2022.08.31
JSP) Action tags - forward  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29
JSP) Session  (0) 2022.08.29

<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

Conditional statements and loops are used in Java and other languages since they simplify the codes. 

Conditional statements, also called Selection statements, consist of two big statements: If statements and Switch ~ case statements. 

Here are some examples for your better understanding. 

 

if

public class If01 {

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

		if(10>5) {
			System.out.println("Executed 1");
		}
		
        // {} can be omitted if it is a single line.
		if(10>5) System.out.println("Executed 2");
		
		if(true) {
			System.out.println("Execute unconditionally");
		}
		
		if(false) {
			System.out.println("Execution failed");
		}
		
		if(10 > 30)
			System.out.println("Failed to print out");
			System.out.println("Condition isn't applied on this execution");

	}

}

if ~ else ( Even? or Odd? )

import java.util.Scanner;

public class If02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		System.out.println("Insert one integer.");
		
		Scanner sc = new Scanner(System.in);
		
		int n1 = sc.nextInt();
		
		if (n1 % 2 == 0) {
			System.out.println(n1+" is even.");			
		}else {
			System.out.println(n1+" is odd.");
		}
	}

}
// 0 is considered as even number.

if ~ else if ~ else (Maximum and Minimum)

import java.util.Scanner;

public class If03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int n1, n2, max, min; 
		
		System.out.println("Insert two integers.");
		
		Scanner sc = new Scanner(System.in);
		
		n1 = sc.nextInt();
		n2 = sc.nextInt();
		
		if (n1 > n2) {
			max = n1;
			min = n2;
			
		}else {
			max = n2;
			min = n1;
		}	
			System.out.println(max + " is the maximum.");
			System.out.println(min +" is the mininum.");
		
		
	}

}

Random number(Dice)

public class If06 {

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

		// Random numbers 
		// 	0.0 <= Math.random() < 1.0
		//   1                      6
		System.out.println("E="+Math.E);	
		System.out.println("PI="+Math.PI);	
		System.out.println(Math.random()); 
		
		int num = (int)(Math.random()*6) + 1;
		System.out.println("num=" +num);
		
		if(num == 1) {
			System.out.println("1");			
		}else if(num == 2){
			System.out.println("2");
		}else if(num == 3){
			System.out.println("3");
		}else if(num == 4){
			System.out.println("4");
		}else if(num == 5){
			System.out.println("5");
		}else {
			System.out.println("6");
		}
	}

}

Score 

import java.util.Scanner;

public class If05 {

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

		System.out.println("Insert your score.");
		
		Scanner sc = new Scanner(System.in);
		
		n1 = sc.nextInt();

		if(n1 >= 90) {
			System.out.println("A");
		}else if(n1 >= 80) {
			System.out.println("B");
		}else if(n1 >= 70) {
			System.out.println("C");
		}else if(n1 >=60) {
			System.out.println("D");
		}else {
			System.out.println("F");
		}
	
	}

}

This can also be written with Switch ~ case like below. Switch ~ case and If ~ else if ~ else statements do the same role, but the syntax is slightly different. 

 

Switch ~ case (Score)

package p2022_06_23;

import java.util.Scanner;

public class Switch01 {

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

		System.out.println("Insert your score (0 ~ 100).");
		Scanner sc = new Scanner(System.in);
		
		int s = sc.nextInt();  // s = 95
		s = s / 10;            // s /= 10
		switch (s) {
			case 10 :
			case 9: System.out.println("A");
			     	 break;
			case 8: System.out.println("B");
				 	 break;
			case 7: System.out.println("C");
				 	 break;
			case 6: System.out.println("D");
				 	 break;
			default:System.out.println("F");
		}

	}

}

While these conditional statements above are runned once, there are loops if you want to write repetitive statements. There are three types of loops : For, While, and Do ~ while. 

 

For01.java

public class For01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
        
		int i; 
		for(i=1; i<=10; i++) { 
			System.out.println(i+"This is a for loop.");
		}
}
}

For02.java

public class For02 {

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

		// Sum of 1 ~ 10
		int sum = 0;  //Local Variable
		for(int i=1; i<=10; i++) { 
			sum = sum + i; 
		}
		// System.out.println("sum="+sum);
//		System.out.println("1~"+i+"="+sum);
		System.out.println("Sum="+sum);
	}
	
}

For03.java

public class For03 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		int odd = 0;
		int even = 0;

		for(int i=1; i<=100; i+=2)
			odd += i;

		for(int i=0; i<=100; i+=2)
		even += i;
		System.out.println("Sum of all odd numbers from 1 to 100: "+odd);
		System.out.println("Sum of all even numbers from 1 to 100: "+even);
		
	}
}

For04.java (Multiplication Table)

import java.util.Scanner;

public class For04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		System.out.println("Insert one integer for a multiplication table.");
		Scanner sc = new Scanner(System.in);
		int dan = sc.nextInt();    // dan = 5
		
		System.out.println("["+dan+"]");
		for(int i=1; i<=9; i++)
			System.out.println(dan+"*"+i+"="+dan*i);
				
		
	}

}

Multiplication Table 

public class Multiplication Table {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		for(int i=2; i<10; i++) {
			System.out.print("["+i+"]"+"\t");
		}
		System.out.println();
		
		for(int j=1; j<10; j++) {
			for(int k=2; k<10; k++) {
				System.out.print(k+"*"+j+"="+k*j+"\t");
				
			}
			System.out.println();
		}
	}

}

While01.java

This is the same as For03.java, so you can choose one that makes your code more efficient. 

public class While01 {

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

		
		int i=1, odd=0, even=0;		
		while(i<=100) {				
			if(i%2 == 1) {		
				odd += i;
			}else {					
				even += i;
			}		
			i++;				
		}
		System.out.println("Sum of all odd numbers from 1 to 100: "+odd);
		System.out.println("Sum of all even numbers from 1 to 100: "+even);
	}

}

The output will be the same.

Dowhile01.java 

This is also the same as While01.java and For03.java.

public class DoWhile01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
				
		int i=1, odd=0, even=0;			
		do {
			if(i%2 == 1) {		
				odd += i;
			}else {				
				even += i;
			}
			i++;					
		}while(i<=100);				
		System.out.println("Sum of all odd numbers from 1 to 100: "+odd);
		System.out.println("Sum of all even numbers from 1 to 100: "+even);
	}

}

The result is also the same. 

As you can see, the conditional statements and the loops have multiple options for you to choose from when you make your program, but the first thing you need to consider is "Efficiency." When we code, we need to consider the processing time and the length of the codes

'Java' 카테고리의 다른 글

Java) Array  (0) 2022.09.04
Java) .length vs length()  (0) 2022.09.02
Java) Data Types  (0) 2022.08.27
Java) Operators  (0) 2022.08.26
Java (Must know)  (0) 2022.08.25

Action tags are one of the factors in JSP pages, along with scripts, comments, and directives. 

In JSP, action tags are implemented to perform some precise tasks. 

Here are some most used action tags :

 

<jsp:forward> : to forward the request and response to other resources.

<jsp:forward page = "URL of another static, JSP, OR Servlet page" />

<jsp:include> : to include another resource.

<jsp:include page = "Page URL"  flush = "Boolean Value" />

<jsp:param> : to set the parameter for (forward or include) value.

<jsp: param name = "param_name" value = "value_of_parameter" />

<jsp:usebean> : to create or locate bean objects.

<jsp: useBean id="unique_name_to_identify_bean" class="package_name.class_name" />

and so on. 

 

Here, let us take a peek at some examples of these action tags. 

 

<Forward Action Tag Example 1>

 

forwardForm1.jsp

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

<html>
	<body>
	<h1>Forward Example</h1>

	<form method=post action="forwardFrom1.jsp">
	ID : <input type="text" name="id"><p>
	Password : <INPUT TYPE="password" NAME="password"><p>
			   <input type="submit" value="Submit">
	</form>

	</body>
</html>

forwardFrom.jsp

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

<html>
<body>
	<h2>Page forwarding: forwardFrom1.jsp</h2>

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

	forwardFrom1.jsp content
	<br> You will not see this on a browser.

	<%
		// request object
	request.setAttribute("name", "Meadow");
	%>

	<jsp:forward page="forwardTo1.jsp" />

</body>
</html>

forwardTo1.jsp

You will not see the forwarded data on the browser.

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

<html>
	<body>
	<h2>Page forwarding: forwardTo1.jsp</h2>

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

	<b><%=id%></b>'s<p>
	password is <b><%=password%></b>.

	<jsp:forward page="forwardTo2.jsp"/>  

	</body>
</html>

forwardTo2.jsp

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

    
    ID : <%=request.getParameter("id")%> <br>
    password : <%=request.getParameter("password")%> <br>
    
    Print out the value shared by the request object.<br>
    <%=request.getAttribute("name")%>

<Forward Action Tag Example 2>

 

forwardForm2.jsp

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

<html>
	<head>
	<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
	<script>
	
	$(document).ready(function(){
		
		$(":submit").click(function(){
			
			if($("#name").val() == ""){
				alert("Insert your name.");
				$("#name").focus();
				return false;
			}
			
			if($("#a").is(":checked") == false &&
			   $("#b").is(":checked") == false &&	
			   $("#o").is(":checked") == false &&
			   $("#ab").is(":checked") == false){
				alert("Choose your bloodtype.");
				return false;
			}		
			
		});
		
	});	
	
	</script>
	</head>
	<body>

	<h1>Forwarding parameter value to next page</h1>

	<form method=post action="forwardFrom2.jsp">
	Name : <input type=text id="name" name="name"> <br><br>
	
	What is your bloodtype?<p> 
	
	<input type="radio" id="a" name="bloodType" value="a">A<br>
	<input type="radio" id="b" name="bloodType" value="b">B<br>
	<input type="radio" id="o" name="bloodType" value="o">O<br>
	<input type="radio" id="ab" name="bloodType" value="ab">AB<p>
	<input type="submit" value="Submit">
	</form>

	</body>
</html>

forwardFrom2.jsp

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

<html>
	<body>

	<h1>Page forwarding: forwardFrom2.jsp</h1>

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

		String bloodType = request.getParameter("bloodType") + ".jsp";
	
	%>

	<jsp:forward page="<%=bloodType%>"/>

a.jsp

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

<html>
	<body>

	<h1>Page forwarding(a.jsp)</h1>

	<%
		String name = request.getParameter("name");
		String bloodType = request.getParameter("bloodType");
	%>

	<b><%=name%></b>'s bloodtype is 
	<b><%=bloodType%></b> and did you know that <p>
	people with type B blood are more susceptible to gastroenteric cancers?

	</body>
</html>

b.jsp

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

<html>
	<body>

	<h1>Page forwarding(b.jsp)</h1>

	<%
		String name = request.getParameter("name");
		String bloodType = request.getParameter("bloodType");
	%>

	<b><%=name%></b>'s bloodtype is 
	<b><%=bloodType%></b> and did you know that <p>
	people of this blood type have a strong immune system and stable nervous system?

	</body>
</html>

ab.jsp

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

<html>
	<body>

	<h1>Page forwarding(ab.jsp)</h1>

	<%
		String name = request.getParameter("name");
		String bloodType = request.getParameter("bloodType");
	%>

	<b><%=name%></b>'s bloodtype is
	<b><%=bloodType%></b> and did you know that <p>
	type AB- is the rarest of all the blood types, with just 1% of the population having it?

	</body>
</html>

o.jsp

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

<html>
	<body>

	<h1>Page forwarding(o.jsp)</h1>

	<%
		String name = request.getParameter("name");
		String bloodType = request.getParameter("bloodType");
	%>

	<b><%=name%></b>'s bloodtype is
	<b><%=bloodType%></b>, and did you know that <p>
	people with the bloodtype O are less susceptible to malaria?

	</body>
</html>

<Forward Action Tag Example 3>

 

forwardForm3.jsp

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

<html>
	<body>

	<h2>Forward Example 3</h2>

	<form method="post" action="forwardFrom3.jsp">
	Name : <input type="text" name="name"><br><br>
	Your color : <br>
	<input type="radio" name="color" value="yellow">Yellow<br>
	<input type="radio" name="color" value="green">Green<br>
	<input type="radio" name="color" value="blue">Blue<br>
	<input type="radio" name="color" value="red">Red<p>
	<input type="submit" value="Confirm">
	</form>

	</body>
</html>

forwardFrom.jsp

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

<html>
	<body>

	<h2>Page forwarding: forwardTagFrom2.jsp</h2>

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

   String name = request.getParameter("name");
   String selectedColor = request.getParameter("color");
%>

<jsp:forward page="<%=selectedColor+\".jsp\"%>">
    <jsp:param name="selectedColor" value="<%=selectedColor%>"/>
	<jsp:param name="name" value="<%=name%>"/>
</jsp:forward>

blue.jsp

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

<%
   String name = request.getParameter("name");
   String selectedColor = request.getParameter("selectedColor");
%>

<h2>Blue - <%=selectedColor+".jsp"%></h2>

<b><%=name%></b>'s color is "<%=selectedColor%>" and
it represents calmness and responsibility.<br><br>

<img src="<%=selectedColor+".jpg"%>" border="0" width="70" height="30">

green.jsp

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

<%
   String name = request.getParameter("name");
   String selectedColor = request.getParameter("selectedColor");
%>

<h2>Green - <%=selectedColor+".jsp"%></h2>

<b><%=name%></b>'s color is "<%=selectedColor%>" and
it represents growth and renewal, being the color of spring and rebirth.<br><br>

<img src="<%=selectedColor+".jpg"%>" border="0" width="70" height="30">

red.jsp

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

<%
   String name = request.getParameter("name");
   String selectedColor = request.getParameter("selectedColor");
%>

<h2>Red - <%=selectedColor+".jsp"%></h2>

<b><%=name%></b>'s color is "<%=selectedColor%>" and
it represents life, health, vigor, war, courage, anger, love and religious fervor.<br><br>

<img src="<%=selectedColor+".jpg"%>" border="0" width="70" height="30">

yellow.jsp

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

<%
   String name = request.getParameter("name");
   String selectedColor = request.getParameter("selectedColor");
%>

<h2>Yellow- <%=selectedColor+".jsp"%></h2>

<b><%=name%></b>'s color is "<%=selectedColor%>" and
it symbolizes happiness, warmth and sunshine.<br><br>

<img src="<%=selectedColor+".jpg"%>" border="0" width="70" height="30">

By designating the name of the jpg files to the selectedColor, you can directly load them to the forward pages.

'Java > JSP' 카테고리의 다른 글

JSP) Action tags - include  (0) 2022.08.31
JSP) Handling Exceptions  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29
JSP) Session  (0) 2022.08.29
JSP) Cookies  (0) 2022.08.28

The last post of mine was about the basics of the scopes and focused on the application and the session among four scopes: Page, Request, Session, and Application.

2022.08.26 - [JSP] - JSP) Scopes - Basics / Application

 

JSP) Scopes - Basics / Application

There are four scopes in JSP. Scope Description Page Stores a value to be shared within one JSP page. Request Stores values to be shared on all JSP pages used to process a single request. Session Sh..

www.agilemeadow.com

 

In this post, we will cover the page and the request scopes. 

Page and Request

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("pageScope", "pageValue");
request.setAttribute("requestScope", "requestValue");
%>

pageValue = <%=pageContext.getAttribute("pageScope") %><br>
requestValue = <%=request.getAttribute("requestScope") %>
</body>
</html>

With a forward action tag

With the forward action tag, you will not see anything on a browser, but it will still forward the data to the designated page.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
pageContext.setAttribute("pageScope", "pageValue");
request.setAttribute("requestScope", "requestValue");
%>
<jsp:forward page="requestTest5Result.jsp"></jsp:forward>
</body>
</html>

Result page

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
pageValue = <%=pageContext.getAttribute("pageScope") %><br>
requestValue = <%=request.getAttribute("requestScope") %>
</body>
</html>

You cannot use the page scope anymore so it will turn out null.

 

'Java > JSP' 카테고리의 다른 글

JSP) Handling Exceptions  (0) 2022.08.30
JSP) Action tags - forward  (0) 2022.08.30
JSP) Session  (0) 2022.08.29
JSP) Cookies  (0) 2022.08.28
JSP) Encoding Korean 한글 인코딩  (0) 2022.08.27

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>

 

A session is a concept used by servers and clients to maintain a connection state. Usually, if the login is successful, it is connected to the client as a session on the server side. At this time, member information is shared through the client's web browser connecting the session. Unlike cookies, the session does not store member information on the client's computer. Using a session, you don't have to take your membership information with you as you move the page. It is easier and safer to use than cookies.

 

Here are some basics about sessions. 

To set session

session.setAttribute ( java.lang.String name, java.lang.Object value);

To use session

session.getAttribute ( java.lang.String  name)

To set the expired time

session.setMaxInactiveInterval();

To delete session

session.removeAttribute ( java.lang.String  name );

To delete all current sessions

session.invalidate();

 

Let's see the examples of session objects and compare them to the cookies.

The examples of cookies are here: 2022.08.28 - [JSP] - JSP) Cookies

 

JSP) Cookies

Cookies are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer or other devices by the user's web browser. Cookies are placed on the de..

www.agilemeadow.com

To set session

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

<html>
	<head><title>Session Example</title>
	</head>
	<body>

<%
	String id = "guardian23";
	String passwd = "1234";

	session.setAttribute("id", id);
	session.setAttribute("passwd", passwd);
%>
   The id and passwd property in the session are set.<br><br>

	<input type="button" value="Check properties in the session" onclick="javascript:window.location='viewSession.jsp'">
	</body>
</html>

To view session

You will see the id and the password with the enumeration type. This example is for when you don't know about the session name.

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

<html>
	<head><title>Session Example</title></head>
	<body>

<%
	Enumeration attr = session.getAttributeNames();

	while(	attr.hasMoreElements()	){
		String attrName = (String)attr.nextElement();
		String attrValue = (String)session.getAttribute(attrName);
		out.println("The name of the session is " + attrName + ", and  ");
		out.println("the value of the session is " + attrValue + ".<br><br>");
	}
%>

	</body>
</html>

If you know the session name, you will use it this way.

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

<html>
	<head><title>Session Example</title></head>
	<body>

<%
String id = (String)session.getAttribute("id"); //Downcast to String class
String passwd = (String)session.getAttribute("passwd");
%>

ID : <%=id %> <br>
Password : <%=passwd %> <br>


	</body>
</html>

The URL of the session is shared with the same browser. 

 

When you log out or delete your account, you need to delete the session on the browser. 

To close session

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

<%
	session.invalidate();
%>

<html>
<head>
<title>Closing Session</title>
</head>
<body>
	<script>
		alert("Log out");
		location.href = "../session/viewSession.jsp";
	</script>
</body>
</html>

After deleting the session

Now, let's make a log in program with session. 

sessionLoginForm.jsp

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

<html>
	<head><title>Log in</title></head>
	<body>

	<form action="<%= request.getContextPath() %>/sessionLogin.jsp" method="post">
		ID <input type="text" name="id" size="10">
		PASSWORD <input type="password" name="password" size="10">
			<input type="submit" value="Log in">
	</form>

	</body>
</html>

sessionLoginCheck.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    String memberId = (String)session.getAttribute("MEMBERID");

	//Ternary Operator 
	// (Statement) ? a : b
	// if the statement is true -> a 
    // if the statement is false -> b

    boolean login = (memberId == null) ? false : true;
%>

<html>
	<head><title>Log in Check</title></head>
	<body>

<%
    if (login) {
%>
		Hello, "<%= memberId %>"!
		
		<a href="sessionLogout.jsp">Log out</a><br>
<%
    } else {
%>
		<a href="sessionLoginForm.jsp">Log in</a><br>
		
		<a href="../../request/member/memberform.html">Sign up</a> <br>
<%
    }
%>

	</body>
</html>

sessionLogin.jsp

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

<%
    String id = request.getParameter("id");
    String password = request.getParameter("password");
    
    if (id.equals(password)) {
        session.setAttribute("MEMBERID", id);
%>

		<html>
			<head><title>Success</title></head>
			<body>
			<script>
				alert("Log in success.")
				location.href="sessionLoginCheck.jsp"
			</script>

			</body>
		</html>

<%
    } else { // log in failed
%>

		<script>
			alert("Failed to log in.");
	//		history.go(-1);
			history.back();
		</script>
<%
    }
%>

Once you link the log in to the log in form and the signup to the sign up form, it will load to the page.

sessionLogout.jsp

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

<%
    session.invalidate();
%>

<html>
	<head><title>Log out</title></head>
	<body>
	<script>
		alert("Log out");
		location.hret="sessionLoginForm.jsp"
	</script>
	</body>
</html>

If you want to know more about the sign up program, please refer to this post of mine :

2022.08.24 - [Codes & Projects] - jQuery/ JSP) Sign up Form

 

jQuery/ JSP) Sign up Form

Sign up Form member_join.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PU..

www.agilemeadow.com

 

'Java > JSP' 카테고리의 다른 글

JSP) Action tags - forward  (0) 2022.08.30
JSP) Scopes - Page / Request Scopes  (0) 2022.08.29
JSP) Cookies  (0) 2022.08.28
JSP) Encoding Korean 한글 인코딩  (0) 2022.08.27
JSP) Implicit Objects 3 - Out Object  (0) 2022.08.27

Cookies are small blocks of data created by a web server while a user is browsing a website and placed on the user's computer or other devices by the user's web browser. Cookies are placed on the device used to access a website, and more than one cookie may be placed on a user's device during a session.

The term "cookie" was coined by web-browser programmer Lou Montulli. It was derived from the term "magic cookie", a packet of data a program receives and sends back unchanged, used by Unix programmers. The term magic cookie derives from the fortune cookie, a cookie with an embedded message.(Wikipedia)

 

Usually, cookies are issued to connect the server and the client. The picture following is how the cookies work. 

Source:&nbsp;blog.csdn.net

The cookie is a concept used by servers and clients to maintain a connection state (login). Usually, if the login is successful, the server issues cookies and the cookies are issued by the client. The file is created in the temporary folder. On the server side, as you navigate the page, you can refer to the cookie information issued to the client's temporary folder. It is to maintain the connection status (login) between the server and the client. You don't have to take your membership information while moving the page with cookies.

 

Here are some basics of cookies in JSP.

To create cookies

Cookie cook = new Cookie (String name, String value);
Cookie cook = new Cookie ("id", "test");

To add cookies

response.addCookie(cook);

To edit the value of cookies

cook.setValue(newValue);

To set expired time

cook.setMaxAge(int expiry); // seconds
cook.setMaxAge(60*60); // an hour

To read cookies

Cookie[] cook = request.getCookie();

Name : cook.getNmae()
Value : cook.getValue()

If you feel you are more familiar with cookies, check out an example!

 

makeCookie.jsp

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

<html>
	<head>
		<title>To create cookies</title>
	</head>

<%
   String cookieName = "id";
   Cookie cookie = new Cookie(cookieName, "sheriff");
   cookie.setMaxAge(60*2); 
   cookie.setValue("guardian");
   response.addCookie(cookie);
%>

	<body>
	<h2>Cookie example</h2>
	<P>

"<%=cookieName%>" Cookie has been created.<br>

		<input type="button" value="Check Cookies" onclick="javascript:window.location='useCookie.jsp'">
	</P>
	</body>
</html>

useCookie.jsp

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

<html>
	<head>
		<title>Brining cookies from a browser</title>
	</head>
	<body>
	<h2>Brining cookies from a browser</h2>

<%
	Cookie[] cook = request.getCookies();

	if( cook != null ){
		for(int i=0; i<cook.length;++i){
			if(cook[i].getName().equals("id")){
%>

		Name of the cookie is "<%=cook[i].getName()%>" and 
		the value is "<%=cook[i].getValue()%>" .

<%
			}
		}
	}
%>

	</body>
</html>

To check the cookies that are created, on the browser that you want to check the cookies, enter F12 and see the cookies in the Application tap. The cookies will be there until the expired time you set. 

Cookies track your behavior on websites and browsers, and they can target with ever more personalized content based on users’ engagement on web pages. Cookies can also be used to identify unique and returning visitors to a website. When a user visits a website, the site creates a cookie that stores data that identifies that user. If the user leaves the website and visits again, the website will recognize the user as a returning user. A good example of why this can be a huge help would be an e-commerce website that remembers the products you added to your cart the last time you visited, even though you didn't complete the purchase. However, when you let people use your browser account, they can see what kinds of sites you visit by peeking at your browser file — unless you get rid of them.(AVG)

 

Here are some more examples of cookies. 

To create cookies

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

<% 
    Cookie cookie = new Cookie("name", URLEncoder.encode("Meadow"));
    response.addCookie(cookie); // To create cookies
%>

<html>
	<head><title>Creating Cookies</title></head>
	<body>

<%= cookie.getName() %> Value = "<%= cookie.getValue() %>"

	</body>
</html>

To view the cookies list

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

<html>
	<head><title>Cookies List</title></head>
	<body>
	Cookies List<br>

<%
    Cookie[] cookies = request.getCookies();

    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {
%>

			<%= cookies[i].getName() %> = 
			<%= URLDecoder.decode(cookies[i].getValue()) %><br>

<%
        }//for end

    } else {
%>

		There is no cookies.
<%
    }
%>

	</body>
</html>

If you didn't set the expired time, the cookies will be deleted once you close the window. So, it would help if you opened the window to see the cookies. 

There are two ways to modify the values of the cookies.

To modify value1

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

<%
    Cookie[] cookies = request.getCookies();

    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {

            if (cookies[i].getName().equals("name")) {
                Cookie cookie = new Cookie("name", URLEncoder.encode("JSP Programming"));
                response.addCookie(cookie);

            }// if end

        }//for end
    }
%>

<html>
	<head><title>Modifying Cookies</title></head>
	<body>
		Change the value of cookie "name".
	</body>
</html>

To modify value2

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

<%
    Cookie[] cookies = request.getCookies();

    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {

            if (cookies[i].getName().equals("name")) {
                cookies[i].setValue(URLEncoder.encode("Java and JSP"));
                response.addCookie(cookies[i]);
            }// if end

        }//for end
    }
%>

<html>
	<head><title>Modifying Cookies</title></head>
	<body>
		Change the value of cookie "name".
	</body>
</html>

Unlike creating cookies, there is no function to delete cookies. However, there is another way to delete them.

You will create a cookie with the name with a null value. Set the expired time '0' and use the response object.

To delete cookies

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

<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0 ; i < cookies.length ; i++) {

            if (cookies[i].getName().equals("name")) {
                Cookie cookie = new Cookie("name", "");
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }//if end

        }//for end
    }
%>

<html>
	<head><title>Delete Cookies</title></head>
	<body>
		Delete cookie "name".
	</body>
</html>

 

No cookies in the list.

To set the expired time.

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

<%
    Cookie cookie = new Cookie("oneh", "1time");
    cookie.setMaxAge(60 * 60); // 60sec * 60 = 1 hour
    response.addCookie(cookie);
%>

<html>
	<head><title>Cookie's expired time</title></head>
	<body>

	In one hour, this cookie will be deleted.

	</body>
</html>

 

+ Recent posts