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

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>

 

본 내용은 아래 링크에 나온 Request Object Example1의 한글 인코딩과 관련된 포스팅입니다. 

This post is related to the Korean encoding of Request Object Sample1 shown in the link below.

https://agilemeadow.tistory.com/manage/newpost/?type=post&returnURL=%2Fmanage%2Fposts%2F# 

 

TISTORY

나를 표현하는 블로그를 만들어보세요.

www.tistory.com

<HTML>

<html>
<head>
	<meta charset="UTF-8">
	<title>request Example1</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
	$(document).ready(function(){
		$("form").submit(function(){
			if($("#name").val()==""){
				alert("Please insert your name.");
				$("#name").focus();
				return false;
			}
			if($("#studentNum").val()==""){
				alert("Please insert your student number.");
				$("#studentNum").focus();
				return false;
			}
			if($("#male").is(":checked")==false &&
			   $("#female").is(":checked")==false){
				alert("Please select your sex.");
				return false;
			}
			if($("#major").val()=="#"){
				alert("Please select your major.");
				$("#major").focus();
				return false;
			}
		});	
	});	
	</script>
</head>
<body>
<h1>Request Example1</h1>

<form name=myform method=post action="requestExample1.jsp">
 Name : <input type="text" name="name" id="name" autofocus="autofocus"><br>
 Student No. : <input type="text" name="studentNum" id="studentNum"><br>
 Sex : Male <input  type="radio" name="sex"  value="male" id="male">
      Female <input type="radio" name="sex" value="female" id="female"><br>
      Prefer not to say <input type="radio" name="sex" value="prefernottosay" id="prefernottosay"><br>
 Major : <select name="major" id="major">
			<option value="#">Select your major</option>
			<option value="CS">Computer Science</option>
			<option value="EL">English Literature</option>
			<option value="M">Mathmetics</option>
			<option value="PS">Political Science</option>
			<option value="BM">Business Management</option>
		</select><br>
<input type="submit" value="submit">
<input type="reset" value="cancel">
</form>

</body>
</html>

<JSP>

인코딩은 항상 위에서 먼저 해야 합니다. 그렇지 않으면 한글 값이 깨집니다.

Post 방식으로 값을 전달 할 때는 Tomcat이 자동으로 인코딩하지 않으므로 인코딩을 먼저 시킨다음 값을 받아야 합니다. 

대부분의 전송방식이 Post 방식이기 때문에 한글 인코딩은 항상 빠지지 않는 중요한 문제입니다. 

Encoding should always be done first above. Otherwise, the Korean value is broken.
Tomcat does not automatically encode the value when forwarding it in the Post method, so you must encode it first and then receive it. 
Since most transmission methods are Post, encoding Korean is always an important issue.

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

	
<%	
// 한글 인코딩
// 1. 폼 파일에서 한글값이 get방식으로 전송될 때는 tomcat이 자동으로 utf-8로 인코딩을 시켜준다. 
// 2. 폼 파일에서 한글값이 post 방식으로 전송될 때는 tomcat이 자동으로 인코딩을 시켜주지 않기 때문에 
//    아래의 코드로 직접 인코딩해야 한다. 
// 폼파일에서 한글값이 post방식으로 전송될때 utf-8로 인코딩을 시켜주는 역할

// Korean encoding
// 1. When the Korean value is transmitted in the form file by the get method, tomcat automatically encodes it to utf-8. 
// 2. Tomcat does not automatically encode the Korean value in the form file when it is sent in the post method 
//    It shall be encoded directly into the code below. 
// The role of encoding the Korean values in the form file to utf-8 when they are transmitted by post.

	request.setCharacterEncoding("utf-8");
%>

<html>
<h1>Request Example1</h1>

<%
	String name = request.getParameter("name");
	String studentNum = request.getParameter("studentNum");
	String sex = request.getParameter("sex");
	String major = request.getParameter("major");
/* 
	if(sex.equals("m")){
		sex = "male";
	}else{
		sex = "female";
	} */
%>

<body>
Name: <%=name%><p>
Student No.: <%=studentNum%><p>
Sex : <%=sex%><p>
Major : <%=major%>
</body>
</html>

get방식과 post 방식의 차이에 대해 궁금하시다면 이 상단의 링크를 참조해주세요. 

If you are curious about the difference between get method and post method, please refer to the link above/ or refer to my last post, <JSP) Implicit Objects 1>.

 

Please comment below if you have any issues or questions about this post. 

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

JSP) Session  (0) 2022.08.29
JSP) Cookies  (0) 2022.08.28
JSP) Implicit Objects 3 - Out Object  (0) 2022.08.27
HTML / JSP / Javascript) Implicit Objects 2 - Response Object and Page Link  (0) 2022.08.26
JSP) Implicit Objects 1 - Request Object  (0) 2022.08.26

An out object is an output stream that transmits the results generated by the JSP page to the web browser, and all information that the JSP page sends to the web browser is transmitted through the out object.  All information includes both script and non-script elements such as HTML and general text. Here are some examples of the out object.

 

You can check the size and the use of Buffer. 

outEx.jsp

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

<%
	int totalBuffer = out.getBufferSize();
	int remainBuffer = out.getRemaining();
	int useBuffer = totalBuffer - remainBuffer;
%>

<h1>Out Example</h1>
<b>Buffer status on current page</b><p>

Total Buffer Size : <%=totalBuffer%>byte<p>
Current Use of Buffer : <%=useBuffer%>byte<p>
Remain Buffer Size : <%=remainBuffer%>byte<p>

useOut.jsp

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

<html>
<head><title>out Object2</title></head>
<body>

<%
    out.println("What's up?");
%>
<br>

This is the result of
<%
    out.println("the basic out object.");
%>

</body>
</html>

 

 

println in JSP does not change the line.

To change the line, you need to put the <br> tag like this :

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

<html>
<head><title>out Object2</title></head>
<body>

<%
    out.println("What's up?<br>");
    out.println("Let's change the line.<br>");
%>
<br>

This is the result of
<%
    out.println("<br>the basic out object.");
%>

</body>
</html>

<br> tags are used.

 

Response Object is the object of  HttpServletResponse class associated with the response to the client. It is different from the request object since the request is the object of HttpServletRequest class associated with the request.

 

We will cover three ways to link pages with HTML, Javascript, and JSP. It is the same function, but each language has different codes to link the page. first.jsp is the file that we will link in each files. 

 

first.jsp

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

<%

String str = request.getParameter("name");

%>

name : <%=str%>

 

meta.html

The good thing when you use the meta tag in HTML is that you can set the time.

<html>
	<head>

	<!-- mata tag -->
	<meta http-equiv="refresh" content="0;
		url=first.jsp?name=test">

	</head>
	<body>
	</body>
</html>

The url will link to the first.jsp file. This is a get method. If you are using a form, you can choose either get method or post method, but in this case, you cannot. 

 

With Javascript, you can use the alert() and location property.

location.html

<html>
	<head>
	<meta charset="utf-8">
	</head>
	<body>

	<script language="javascript">
		alert("Page link");
		location.href='first.jsp?name=test';
	</script>

	</body>
</html>

With JSP, you can use a response object. 

responseEx.jsp

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

<h1>Response Example</h1>
This page is from responseEx.jsp file.


<%	//Page link from JSP
     response.sendRedirect("first.jsp?name=test");
%>

 

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

JSP) Encoding Korean 한글 인코딩  (0) 2022.08.27
JSP) Implicit Objects 3 - Out Object  (0) 2022.08.27
JSP) Implicit Objects 1 - Request Object  (0) 2022.08.26
JSP) Scopes - Basics / Application  (0) 2022.08.26
JSP) Comment  (0) 2022.08.26

Implicit Objects are the Java objects that the JSP Container makes available to the developers on each page, and we can call them directly without being explicitly declared. They are also called pre-defined variables. It can be new because there is no implicit objects in Java. There are nine implicit objects in JSP that you will see below : 

Object Actual Type Description
request java.servlet.http.HttpServletRequest/ 
javax.servlet.ServletRequest
Request information like a parameter, header information, server name, etc.
response javax.servlet.http.HttpServletResponse/ 
javax.servlet.ServletResponse
to content type, add cookie and redirect to response page
pageContext javax.servlet.jsp.PageContext to get, set and remove the attributes from a particular scope
session javax.servlet.http.HttpSession to get, set and remove attributes to session scope and also used to get session information
application javax.servlet.ServletContext to interact with the servlet container
out javax.servlet.jsp.jspWriter to access the servlet’s output stream
config java.servlet.servletConfig to get the initialization parameter in web.xml
page java.lang.Object Page implicit variable holds the currently executed servlet object for the corresponding jsp.
exception java.lang.Throwable It is used for exception handling in JSP.

These methods are available to the JSP implicit request object. In Model1, we don't use String getRequestURI() and String getContextPath() as much as in Model2.

Method Description
setCharacterEncoding(String env) processes encoding Korean.
Object getAttribute(String name) returns the value of the attribute named name.
Enumeration getAttributeNames() returns the name of all attributes in an HTTP request.
String getParameter() returns the value of request parameter as String or null if the parameter doesn't exist.
Enumeration getParameterNames() returns the names of all parameters in request.
String getContentType() returns the MIME type of the request or null for an unknown type.
String getProtocol() returns the name of the protocol and its version used by the request.
String getRemoteAddr() returns the IP address that the request came from.
String getServerName() returns the name of Server that received the request.
int getServerPort() returns Server port at which the request is received.
boolean isSecure() returns true if the request came from HTTPS protocol and false if it didn't.
Cookies getCookies() returns an array of Cookie objects that came along with this request.
String getMethod() returns the name of the method(GET, PUT, POST) using which the request was made.
String getRequestURI() returns the URI of the page that initiated the request.
String getContextPath() returns the context path(project name).

Let's see if we can find the methods on Java EE Api.

https://docs.oracle.com/javaee/7/api/toc.htm

 

Java(TM) EE 7 Specification APIs

 

docs.oracle.com

For example, you will click the package and the interface to find the methods in the request object. 

 

Request Example1 

<HTML>

<html>
<head>
	<meta charset="UTF-8">
	<title>request Example1</title>
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
	$(document).ready(function(){
		$("form").submit(function(){
			if($("#name").val()==""){
				alert("Please insert your name.");
				$("#name").focus();
				return false;
			}
			if($("#studentNum").val()==""){
				alert("Please insert your student number.");
				$("#studentNum").focus();
				return false;
			}
			if($("#male").is(":checked")==false &&
			   $("#female").is(":checked")==false){
				alert("Please select your sex.");
				return false;
			}
			if($("#major").val()=="#"){
				alert("Please select your major.");
				$("#major").focus();
				return false;
			}
		});	
	});	
	</script>
</head>
<body>
<h1>Request Example1</h1>

<form name=myform method=post action="requestExample1.jsp">
 Name : <input type="text" name="name" id="name" autofocus="autofocus"><br>
 Student No. : <input type="text" name="studentNum" id="studentNum"><br>
 Sex : Male <input  type="radio" name="sex"  value="male" id="male">
      Female <input type="radio" name="sex" value="female" id="female"><br>
      Prefer not to say <input type="radio" name="sex" value="prefernottosay" id="prefernottosay"><br>
 Major : <select name="major" id="major">
			<option value="#">Select your major</option>
			<option value="CS">Computer Science</option>
			<option value="EL">English Literature</option>
			<option value="M">Mathmetics</option>
			<option value="PS">Political Science</option>
			<option value="BM">Business Management</option>
		</select><br>
<input type="submit" value="submit">
<input type="reset" value="cancel">
</form>

</body>
</html>

<JSP>

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

<%	
	request.setCharacterEncoding("utf-8");
%>

<html>
<h1>Request Example1</h1>

<%
	String name = request.getParameter("name");
	String studentNum = request.getParameter("studentNum");
	String sex = request.getParameter("sex");
	String major = request.getParameter("major");
/* 
	if(sex.equals("m")){
		sex = "male";
	}else{
		sex = "female";
	} */
%>

<body>
Name: <%=name%><p>
Student No.: <%=studentNum%><p>
Sex : <%=sex%><p>
Major : <%=major%>
</body>
</html>

When you click submit, you will see this.

There is a difference between the two methods: get and post. If you use the post method, you will not see anything on the URL; with the get method, you will see the input data on the URL. Because of security reasons, we usually use the post method. 

 

Request Example2

<HTML>

<html>
	<head><title>Your hobbies</title>	
	<meta charset="utf-8">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
	$(document).ready(function(){
//		$("form").submit(function(){
		$("#myform").submit(function(){
			/* var cnt=0;
			if($("#h1").is(":checked"))	cnt++;
			if($("#h2").is(":checked"))	cnt++;
			if($("#h3").is(":checked"))	cnt++;
			if($("#h4").is(":checked"))	cnt++;
			if($("#h5").is(":checked"))	cnt++;
			if($("#h6").is(":checked"))	cnt++;
			if($("#h7").is(":checked"))	cnt++;
			
			if(cnt < 2){
				alert("Select more than one.");
				return false;
			} */
			
			if($("input:checkbox[name='site']:checked").length < 2){
				alert("Select more than one.");
				return false;
			}			
			
		});
	});	
	</script>
	</head>
<body>

<form id="myform" name=myform  method=post action="check.jsp"> 

	Select your hobbies.<br><br> 
	<input type="checkbox" id="h1" name="site" value="Walking">Walking<br>
	<input type="checkbox" id="h2" name="site" value="Swimming">Swimming<br>
	<input type="checkbox" id="h3" name="site" value="Reading">Reading<br>
	<input type="checkbox" id="h4" name="site" value="Programming">Programming<br>
	<input type="checkbox" id="h5" name="site" value="Watching Movies">Watching Movies<br>
	<input type="checkbox" id="h6" name="site" value="Climbing">Climbing<br>
	<input type="checkbox" id="h7" name="site" value="Running">Running<br><br>

	<input type="submit" value="Submit">
	<input type="reset" value="Cancel">

</form> 

</body>
</html>

<JSP>

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

<html>
<body>

	<%
		request.setCharacterEncoding("utf-8");

		String[] choice = request.getParameterValues("site");
		String result = "";

		for (int i = 0; i < choice.length; i++) {
			result = result + choice[i] + " ";
		}
	%>

	<center>
		You like <font color=blue><%=result%></font>!
	</center>

</body>
</html>

Request Example3

<HTML>

<html>
	<head><title>radio button</title>
	<meta charset="utf-8">
	<script src="http://code.jquery.com/jquery-latest.js"></script>
	<script>
	$(function(){
		$("form").submit(function(){
			/* if($("#s1").is(":checked")==false &&
			   $("#s2").is(":checked")==false &&
			   $("#s3").is(":checked")==false &&
			   $("#s4").is(":checked")==false ){
				alert("Choose your favorite season.");
				return false;
			} */

				if($("input:radio[name='season']:checked").length<1){
					alert("Choose your favorite season.");
					return false;
				}
		});
	});	
	</script>
	</head>
	<body>
	Choose your favorite season.
	<p>

	<form name=syberpoll method=post action=result.jsp>
		<input type=radio id="s1" name=season value=Spring>Spring<br>
		<input type=radio id="s2" name=season value=Summer>Summer<br>
		<input type=radio id="s3" name=season value=Fall>Fall<br>
		<input type=radio id="s4" name=season value=Winter>Winter<br>
		<input type=submit value="투표">
	</form>

	</body>
</html>

<JSP>

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

<html>
	<head><title>Survey</title>
	</head>
	<body>

	<%
		request.setCharacterEncoding("utf-8");
	
		String choiceseason = request.getParameter("season");
		String result = "";

		/* if(choiceseason.equals("spring")){
			result = "Spring";
		} else if(choiceseason.equals("summer")){
			result = "Summer";
		} else if(choiceseason.equals("autumn")){
			result = "Fall";
		} else if(choiceseason.equals("winter")){
			result = "Winter";
		} */
	%>

		Your favorite season is <%=choiceseason%> !
	</body>
</html>

Request Example4

This example is to know the basic information of the client and server. Amongst them, we use getRemoteAddr(), getRequestURI(), getContextPath() the most. 

<JSP>

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

<html>
<head><title>Client/ Server Information</title>
<meta charset="utf-8">
</head>
<body>

Client IP = <%= request.getRemoteAddr() %> <br>
Requested get content length = <%= request.getContentLength() %> <br>
Requested data Encoding = <%= request.getCharacterEncoding() %> <br>
Requested data content type = <%= request.getContentType() %> <br>
Requested data Protocol = <%= request.getProtocol() %> <br>
Reqeusted data transition method = <%= request.getMethod() %> <br>
Requested URI = <%= request.getRequestURI() %> <br>
Path of Context = <%= request.getContextPath() %> <br>
Server name= <%= request.getServerName() %> <br>
Server port = <%= request.getServerPort() %> <br>

</body>
</html>

Instead of localhost, insert your IP address to see the information. To find your IP address, in the command prompt, insert ipconfig.

Request Example5

<makeTestForm.jsp>

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

<html>
<head>
<title>Form</title>
</head>
<body>

	Please fill out the form and submit.
	<form method="post" action="viewParameter.jsp">
		Name: <input type="text" name="name" size="10"> <br>
		Address: <input type="text" name="address" size="30"> <br>
		Favorite Animal: <input type="checkbox" name="pet" value="dog">Dog
		<input type="checkbox" name="pet" value="cat">Cat <input
			type="checkbox" name="pet" value="pig">Pig <br> <input
			type="submit" value="Submit">
	</form>
</body>
</html>

<viewParameter.jsp>

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

<%
	request.setCharacterEncoding("utf-8");
%>

<html>
<head>
<title>Printing out request method</title>
</head>
<body>

	<b>request.getParameter() Method</b>
	<br> name Parameter =
	<%=request.getParameter("name")%>
	<br> address Parameter =
	<%=request.getParameter("address")%>
	<p>

		<b>request.getParameterValues() Method</b><br>
		<%
			String[] values = request.getParameterValues("pet");
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
		%>
		<%=values[i]%>
		<%
			}
		}
		%>
	
	<p>

		<b>request.getParameterNames() Method</b><br>
		<%
			Enumeration num = request.getParameterNames();
		while (num.hasMoreElements()) {
			String name = (String) num.nextElement();
		%>
		<%=name%>
		<%
			}
		%>
	
	<p>

		<b>request.getParameterMap() Method</b><br>
		<%
			Map parameterMap = request.getParameterMap();
		String[] nameParam = (String[]) parameterMap.get("name");
		if (nameParam != null) {
		%>
		name =
		<%=nameParam[0]%>
		<%
			}
		%>
	
</body>
</html>

 

I would be happy to receive your comment. Please comment below:)

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

JSP) Implicit Objects 3 - Out Object  (0) 2022.08.27
HTML / JSP / Javascript) Implicit Objects 2 - Response Object and Page Link  (0) 2022.08.26
JSP) Scopes - Basics / Application  (0) 2022.08.26
JSP) Comment  (0) 2022.08.26
JSP) Importing / Classes  (0) 2022.08.25

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 Shares information related to a user.
Application Stores information to be shared with all users.

For your better understanding, please refer to this picture. Page is the narrowest scope, and the application is the widest scope. 

The basic objects related to JSP's scopes are pageContext, request, session, and application.

 

Here are some examples of scopes. With them, you will have a better understanding of which data will be saved in which scope. 

AtrributeTest1_Form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
<head>
<title>Attribute Test Form</title>
</head>
<body>
<h2>Scopes and properties</h2>
<form action="attributeTest1.jsp" method="post">
<table border="1">
	<tr><td colspan="2">Contents for Application</td></tr>
	<tr>
		<td>Name</td>
		<td><input type="text" name="name"></td>
	</tr>
	<tr>
		<td>ID</td>
		<td><input type="text" name="id"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="전송"></td>
	</tr>
</table>
</form>
</body>
</html>

AttributeTest1.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>Scopes and properties</h2>
<%
request.setCharacterEncoding("euc-kr");
String name=request.getParameter("name");
String id=request.getParameter("id");
if(name!=null&&id!=null){
	application.setAttribute("name",name);
	application.setAttribute("id",id);
}
%>
<h3>Welcome, <%=name %>.<br><%=name %>'s ID is <%=id %>.</h3>
<form action="attributeTest2.jsp" method="post">
<table border="1">
	<tr><td colspan="2">Contents for Session</td></tr>
	<tr>
		<td>E-mail</td>
		<td><input type="text" name="email"></td>
	</tr>
	<tr>
		<td>Address</td>
		<td><input type="text" name="address"></td>
	</tr>
	<tr>
		<td>전화번호</td>
		<td><input type="text" name="tel"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="전송"></td>
	</tr>
</table>
</form>
</body>
</html>

AttributeTest2.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>Scopes and properties</h2>
<%
request.setCharacterEncoding("euc-kr");
String email=request.getParameter("email");
String address=request.getParameter("address");
String tel=request.getParameter("tel");
session.setAttribute("email",email);
session.setAttribute("address",address);
session.setAttribute("tel",tel);

String name=(String)application.getAttribute("name");
%>
<h3><%=name %>'s data is successfully saved.</h3>
<a href="attributeTest3.jsp">Click to check</a>
</body>
</html>

 

AttributeTest3.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@page import="java.util.Enumeration"%>
<html>
<head>
<title>Attribute Test</title>
</head>
<body>
<h2>Scopes and properties</h2>
<table border="1">
	<tr><td colspan="2">Content for Application</td></tr>
	<tr>
		<td>Name</td>
		<td><%=application.getAttribute("name") %></td>
	</tr>
	<tr>
		<td>ID</td>
		<td><%=application.getAttribute("id") %></td>
	</tr>
</table>
<br>
<table border="1">
	<tr><td colspan="2">Content for Session</td></tr>
<%-- <%
Enumeration e=session.getAttributeNames();
while(e.hasMoreElements()){
	String attributeName=(String)e.nextElement();
	String attributeValue=(String)session.getAttribute(attributeName);
	%>
	<tr>
		<td><%=attributeName %></td>
		<td><%=attributeValue %></td>
	</tr>
	<%
}
%> -->

		<tr>
			<td>Email</td>
			<td><%=session.getAttribute("email")%></td>
		</tr>
		<tr>
			<td>Tel</td>
			<td><%=session.getAttribute("tel")%></td>
		</tr>
		<tr>
			<td>Address</td>
			<td><%=session.getAttribute("address")%></td>
		</tr>
</table>
</body>
</html>

Since the Name and the ID are shared by the application object, you can use that data in other scopse too, because the application object is the broadest scope. 

 

To set application Attribute

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>
My first JSP program <br>

Value shared by application object : 
<%=application.getAttribute("test")%>

</body>
</html>

setApplicationAttribute.jsp

<%@ page contentType = "text/html; charset=euc-kr" %>
<%
   // String name = request.getParameter("name");
   // String value = request.getParameter("value");
    
    String name = "test";
    String value = "1234";
    
    if (name != null && value != null) {
        application.setAttribute(name, value);
      //application.setAttribute("test", "1234");
    }
%>

<html>
<head><title>Set application attribute</title></head>
<body>
<%
    if (name != null && value != null) {
%>
Set attribute of application basic objects:
 <%= name %>  = <%= value %>
<%
    } else {
%>
Application basic objects attribute is not set.
<%
    }
%>
</body>
</html>

These examples are focused on the application scope. If you want to see other examples of the session scope, please refer to this post of mine: 2022.08.29 - [JSP] - JSP) Session

 

JSP) Session

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, m..

www.agilemeadow.com

 

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

HTML / JSP / Javascript) Implicit Objects 2 - Response Object and Page Link  (0) 2022.08.26
JSP) Implicit Objects 1 - Request Object  (0) 2022.08.26
JSP) Comment  (0) 2022.08.26
JSP) Importing / Classes  (0) 2022.08.25
JSP Tags  (0) 2022.08.25

Hey there! In this post, we are going to cover commenting in JSP. 

 

There are two types of commenting in JSP: JSP Script Comments and JSP Script Comments. 

In terms of JSP Comments, you can comment in anywhere in the JSP file. Whereas, you will only write the JSP Script Comments inside of the tags. 

Here are some examples of them. Let's compare the comment tags with HTML too. 

<!-- HTML COMMENT -->
<%-- JSP COMMENT --%>
<% // ONE LINE COMMENT IN SCRIPTLET %>
<% /* MULTI 
		LINE 
          COMMENTS IN SCRIPTLET */ %>
<%=NAME /* EXPRESSION TAG COMMENT */ %>

COMMENT IN HTML

If the JSP tags are covered by the HTML comment tag, it won't show up on a browser, but you will see it in the source code.

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

<html>
<head><title>COMMENT IN HTML</title></head>
<body>

<!-- PROCESS TIME: <%= new Date() %> -->
HTML COMMENT

</body>
</html>

COMMENT IN JSP

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

<html>
<head><title>COMMENTS ON JSP</title></head>

<body>

	<%-- JSP COMMENT --%>
	JSP JSP JSP 

</body>

</html>

You will not see the JSP comment in the source code.

COMMENT IN JAVA

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

<%!
	public int add(int a, int b) {
		return a + b;
	}
%>

<html>
<head><title>COMMENT IN JAVA</title></head>

<body>

<%
	int val1 = 10; 
	int val2 = 20; 
	
	int result = add(val1, val2);
%>

<%= val1 %> + <%= val2 %> = <%= result %>

</body>
</html>

Again, you will not see the comment in the source code. 

 

So, If you want to show your comment on the source code, you have to use the html comment tag not the jsp, but if you don't want to show the comment, you have to use the jsp comment tag.

Here are some examples for your better understanding.

Example1

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

<html>

<!-- HTML COMMENT-->

The result is : <br>

<%-- JSP COMMENT --%>

<body>

<%

int i=1;
int j=2;
i=i+j;

out.println("i+j = " + i); 
%>

</body>
</html>

Example2

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

<html>
	<body>


<h1>Comment Example</h1>

<%
   String name = "You are my ";
%>

<!-- HTML COMMENT IS SHOWED IN THE SOURCE CODE. -->

<%-- 
This comment is not sent to the client web brower.
--%>

<!-- <%=name%> You will see this in the source code. -->

<%-- <%=name%> JSP COMMENT --%>

<%=name /* Expression tag comment*/ %> universe.

	</body>
</html>

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

JSP) Implicit Objects 1 - Request Object  (0) 2022.08.26
JSP) Scopes - Basics / Application  (0) 2022.08.26
JSP) Importing / Classes  (0) 2022.08.25
JSP Tags  (0) 2022.08.25
JSP  (0) 2022.08.25

+ Recent posts