Response Object is the object of HttpServletResponseclass associated with the response to the client. It is different from the request object since the request is the object ofHttpServletRequest 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.
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.
<%@ 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");
%>
Operators are used to performing operations on variables and values.
There are six types of operators, and it will be good for you once you understand how they work in Java because it will be very similar to other languages.
Arithmetic Operators
+, -, *, /, % (remaining)
Comparison operators (=relational operator)
>=, <=, == (same), != (same)
ex) if(a == b){} // if a and b are equal
if(a!=b){} // if a and b are not equal
Condition operators = (conditional expression)
? Value1: Value2; If the conditional expression is true, assign the value 1 to the variable If the conditional expression is false, assign the value 2 to the variable.
Logical operators
||, &&,!
Extended substitution operators
+=, -=, *=, /=, %=
ex) a+=b; // a = a + b; a-=b; // a = a - b; a*=b; // a = a * b; a/=b; // a = a / b; a%=b; // a = a % b;
import java.util.Scanner;
public class Oper6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Condition Operator
// Variable = (Conditional statement) ? Value1 : Value2;
// True -> Value1 / False -> Value2
// Maximum and minimum values out of the two integers entered on the keyboard.
int n1, n2, max, min;
System.out.println("Enter two integers");
Scanner sc = new Scanner(System.in);
n1 = sc.nextInt();
n2 = sc.nextInt();
max = (n1 > n2) ? n1 : n2;
min = (n1 < n2) ? n1 : n2;
System.out.println("max="+max);
System.out.println("min="+min);
}
}
Logical Operators
The results are treated as int-type if you perform arithmetic operations on the int-type and int-type variables. If the double and double types are performed, the result is treated as a double type. The results are treated as double types if you perform arithmetic operations of int and double types.
import java.util.Scanner;
public class Oper07 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Write a program that determines whether you pass or fail 5 subjects when you enter them on the keyboard
// Each subject's class is 40 points, and an average of 60 points or more is required to pass.
int n1, n2, n3, n4, n5, total;
double avg;
System.out.println("Enter the scores of 5 subjects.");
Scanner sc = new Scanner(System.in);
n1 = sc.nextInt();
n2 = sc.nextInt();
n3 = sc.nextInt();
n4 = sc.nextInt();
n5 = sc.nextInt();
total = n1 + n2 + n3 + n4 + n5;
avg = (double)total / (double)5;
System.out.println("avg="+avg);
if(n1>=40 && n2>=40 && n3>=40 && n4>=40 && n5>=50 && avg>= 60) {
System.out.println("Success");
}else {
System.out.println("Fail");
}
}
}
public class Oper08 {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean b1 = true;
boolean b2 = false;
System.out.println(!b1);
//false !not operator changes to the opposite
System.out.println(!b2);
System.out.println(!true);
System.out.println(!false);
}
}
Extended substitution operators
public class Oper09 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 10, b = 3;
System.out.println(a+=b);
// a=a+b
System.out.println(a-=b);
System.out.println(a*=b);
System.out.println(a/=b);
System.out.println(a%=b);
}
}
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 calledpre-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 :
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 implicitrequest object. In Model1, we don't use StringgetRequestURI() and StringgetContextPath() as much as in Model2.
Method
Description
setCharacterEncoding(String env)
processes encoding Korean.
ObjectgetAttribute(String name)
returns the value of the attribute namedname.
EnumerationgetAttributeNames()
returns the name of all attributes in an HTTP request.
StringgetParameter()
returns the value of request parameter asStringornullif the parameter doesn't exist.
EnumerationgetParameterNames()
returns the names of all parameters in request.
StringgetContentType()
returns the MIME type of the request ornullfor an unknown type.
StringgetProtocol()
returns the name of the protocol and its version used by the request.
StringgetRemoteAddr()
returns the IP address that the request came from.
StringgetServerName()
returns the name of Server that received the request.
intgetServerPort()
returns Server port at which the request is received.
booleanisSecure()
returnstrueif the request came from HTTPS protocol andfalseif it didn't.
CookiesgetCookies()
returns an array of Cookie objects that came along with this request.
StringgetMethod()
returns the name of the method(GET, PUT, POST) using which the request was made.
StringgetRequestURI()
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.
<%@ 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>
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.
<%@ 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.
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
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>
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>
There are several ways to Import in JSP, you can directly write page tags or Ctrl + Space bar to import automatically.
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<!-- To import all in java.util package, you can use this code below -->
<%@ page import= "java.util.*" %>
Here are some classes that you need to import.
1. Date / Timestamp Class
<%@page import="java.sql.Timestamp"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
// java.util.Date d = new java.util.Date();
Date d = new Date(); // Ctrl + Space bar to Import
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEEEEE");
Timestamp ts = new Timestamp(System.currentTimeMillis());
%>
Time :
<%=d%>
<br>
Time_Korean_Version :
<%=sd.format(d)%>
<br>
Time :
<%=ts%>
<br>
2. Calendar Class
<%@page import="java.util.Calendar"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR); // YEAR
int m = c.get(Calendar.MONTH) + 1; // MONTH(0~ 11)
int d = c.get(Calendar.DATE); // DATE
// 12-hour format
int h1 = c.get(Calendar.HOUR);
// 24-hour format
int h2 = c.get(Calendar.HOUR_OF_DAY);
String h = "";
if (c.get(Calendar.AM_PM) == 0) { // AM_PM : 0 (AM)
h = "AM"; // AM_PM : 1 (PM)
} else {
h = "PM";
}
int mm = c.get(Calendar.MINUTE);
int s = c.get(Calendar.SECOND);
// Array : Sun = 1 , Mon = 2.... Sat = 7
int week = c.get(Calendar.DAY_OF_WEEK); // Day of week(1 ~7)
String[] weekend = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri"};
%>
<%=week %> <br> <!-- 5 : Thursday -->
<!-- 12-hour format -->
<%=m%>-<%=d%>-<%=y%><%=weekend[week-1] %>
<%=h1%>:<%=mm%>:<%=s%><%=h%><br>
<!-- 24 hour format -->
<%=m%>-<%=d%>-<%=y%><%=weekend[week-1] %>
<%=h2%>:<%=mm%>:<%=s%><br>
3. Random Class
<%@page import="java.util.Random"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
// Random Class
Random r = new Random();
int r1 = r.nextInt(10); // 0 ~ 9
// Random number between 1 and 45
int r2 = r.nextInt(45) + 1;
%>
Your lucky number of today :
<%=r1%>
<br>
As in other languages, there are a few main tags in JSP.
Scriptlet tag
A scriptlet tag is used to execute java source code in JSP.
<!-- Scriptlet Tag -->
<%
// Basic variables
int i = 30;
double d = 3.14;
char c1 = 'A';
char c2 = '자';
boolean b1 = true;
boolean b2 = false;
// Reference variables
// 1. Class
String str1 = "JSP";
String str2 = new String("JSP");
// 2. Array
String[] str = { "Java", "JSP", "Oracle", "HTML", "Python" };
for (int j = 0; j < str.length; j++) {
out.println(str[j] + "\t"); // println doesn't have a function of printing out in a new line.
}
out.println("<br>");
%>
<%
for (String s : str) {
%>
<%=s%>
<br>
<%
}
%>
<%
// 3. Interface : List
List list = new ArrayList(); // Upcasting
// You need to import with the page tag.
list.add(50);
list.add(50.33);
list.add('A');
list.add(true);
list.add("JSP");
for (int j = 0; j < list.size(); j++){
out.println(list.get(j)+"\t");
}
%>
<br>
Declaration tag
Itis usedto declare fields and methods.
The code written inside the JSP declaration tag is placed outside the service() method of the auto-generated Servlet.
<!-- Declaration tag -->
<!-- To declare methods -->
<%!
public int add(int a, int b){
int c = a + b;
return c;
}
public int subtract(int a, int b){
int c = a - b;
return c;
}
public int multiply(int a, int b){
int c = a * b;
return c;
}
%>
<%
int result1 = add(3, 9); // To call add method
int result2 = subtract(3, 9); // To call add method
int result3 = multiply(3, 9); // To call add method
%>
3 + 9 = <%=result1 %> <br>
3 - 9 = <%=result2 %> <br>
10 * 25 = <%=result3 %> <br>
10 * 25 = <%=multiply(10, 25) %> <br>
Wait, what is the Servlet?
According to Oracle, "Aservletis a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes."
The main difference between Servlet and JSP is that Servlet is java based, whereas JSP is HTML based.
Directive tag gives special instruction to Web Container at page translation time. There are three types of directive tags :page,includeandtaglib.
Page tag, is what you always see on the top of every JSP file, also to import, we use the page tags.
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<!-- To import all in java.util package, you can use this code below -->
<%@ page import= "java.util.*" %>
We will study more about import in the next post.
Directive tag
Description
<%@ page ... %>
defines page dependent properties such as language, session, errorPage etc.
<%@ include ... %>
defines file to be included.
<%@ taglib ... %>
declares tag library used in the page
Action tag
Action tags are used to control the flow between pages and to use Java Bean. The JSP action tags are given below.
Action tag
Description
jsp:forward
forwards the request and response to another resource.
jsp:include
includes another resource.
jsp:useBean
creates or locates bean object.
jsp:setProperty
sets the value of property in bean object.
jsp:getProperty
prints the value of property of the bean.
jsp:plugin
embeds another components such as applet.
jsp:param
sets the parameter value. It is used in forward and include mostly.
jsp:fallback
can be used to print the message if plugin is working. It is used in jsp:plugin.
Data type conversion using a wrapper (basic data type <---> reference type) ex) int <---> String Wrapper Class (Boxing and Unboxing) int n = Integer.parseInt("20");
JSP stands for Java Server Pages, which creates dynamic web pages by inserting JAVA code into HTML code It's a web application program. When JSP runs, it is converted to a Java servlet and runs on the web application server. Perform the necessary functions and respond to the client with the web page with the generated data.
The following is the basic structure of JSP.
There are two models in JSP: model 1 and model2, and the structures are slightly different.
To configure JSP, we will download the free source, Apache Tomcat. Please refer to the link below to download it.
Once downloaded, Apache Tomcat has to be stopped running because Eclipse has to dominate the control.
First, create a dynamic web project and name it jspproject.
Next, create a new JSP file in the WebContent folder. Since they all have different usages, it is important to save the file in the WebContent folder, not in META-INF or WEB-INF.
JSP file will be looking like this:
<%@ 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
</body>
</html>
In the next post, we will discuss JSP's main tags, so don't worry if you can't understand the syntax above!