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>
public class Max {
public static void main(String[] args) {
// TODO Auto-generated method stub
int max = 0;
int[] array = { 1, 5, 6, 8, 2 };
for (int i = 0; i < array.length-1; i++) {
if (array[i] > array[i + 1]) {
max = array[i];
if( max > array[i + 1]) {
System.out.println(max);
}
}
}
}
}
public class DiceRandom {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 0;
int b = 0;
while (a + b != 5) {
a = (int) (Math.random() * 6) + 1;
b = (int) (Math.random() * 6) + 1;
System.out.println(a + "," + b);
}
}
}
2. Lottery
import java.util.Random;
public class LotteryRandom {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Making an Array
Random ran = new Random();
int[] Lottery = new int[6];
// Picking random numbers
int i;
for (i = 0; i < 6; i++) {
Lottery[i] = ran.nextInt(45) + 1;
for (int j = 0; j < i; j++) {
if (Lottery[i] == Lottery[j])
i--;
break;
}
System.out.println("Lottery number : " + Lottery[i]);
}
}
}
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");
Sometimes, you can build a UI using jQuery, many of which are already made for us for the efficiency of the work on jQuery. In this post, we will cover how we could build the UI with jQuery and also compare it to CSS.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Accordion - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
$( function() {
$( "#accordion" ).accordion();
} );
</script>
</head>
<body>
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>
Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
</p>
</div>
<h3>Section 2</h3>
<div>
<p>
Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
suscipit faucibus urna.
</p>
</div>
<h3>Section 3</h3>
<div>
<p>
Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
</p>
<ul>
<li>List item one</li>
<li>List item two</li>
<li>List item three</li>
</ul>
</div>
<h3>Section 4</h3>
<div>
<p>
Cras dictum. Pellentesque habitant morbi tristique senectus et netus
et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
mauris vel est.
</p>
<p>
Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
inceptos himenaeos.
</p>
</div>
</div>
</body>
</html>
To view the source, you can click view source.
Also, you can make them by using CSS/Bootstrap. Let me give you one example.
Accordion with Bootstrap
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Accordion Example</h2>
<p><strong>Note:</strong> The <strong>data-parent</strong> attribute makes sure that all collapsible elements under the specified parent will be closed when one of the collapsible item is shown.</p>
<div id="accordion">
<div class="card">
<div class="card-header">
<a class="card-link" data-toggle="collapse" href="#collapseOne">
Java
</a>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<a class="collapsed card-link" data-toggle="collapse" href="#collapseTwo">
Python
</a>
</div>
<div id="collapseTwo" class="collapse" data-parent="#accordion">
<div class="card-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<a class="collapsed card-link" data-toggle="collapse" href="#collapseThree">
Oracle
</a>
</div>
<div id="collapseThree" class="collapse" data-parent="#accordion">
<div class="card-body">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
</div>
</div>
</div>
</body>
</html>
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!
When you enter some websites, you will see locations like the followings :
Since Google offers Google maps, we can put the map on a browser of our websites. It used to be easier than now to use without any keys, but currently, to use it, you need to have the API Keys. Here is the link for the API Keys: https://developers.google.com/maps/documentation/embed/get-api-key
Since I already have the key, I will jump to the below codes to access Google maps on a browser.
<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(-33.8567844, 151.2152967),
zoom:18,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDEM3FEmY5ecJzAkXH9TDRAs1MaXpSWtME&callback=myMap"></script>
</body>
</html>
You can also make a button to load the center that you set. So, once users want to see your location, they can simply click the button.
To set the center, you need to know the longitude and the latitude. By copying and pasting them to the code, it can easily be set.
load event with DOM Level 2 method
Here, we used the addDomListener() and added a marker on the map.
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js">
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDEM3FEmY5ecJzAkXH9TDRAs1MaXpSWtME"
type="text/javascript"></script>
<script>
var myCenter=new google.maps.LatLng(62.4539464, -114.3704224);
function initialize(){
var mapProp = {
center:myCenter,
zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
To make a bouncy marker, edit the code as the following:
var marker=new google.maps.Marker({
position:myCenter,
animation:google.maps.Animation.BOUNCE
});
A marker with a title
You can see the title once you hover the mouse, and when you click the pin, it will zoom.
var marker = new google.maps.Marker({
position: myCenter,
title:'Click to zoom'
});
marker.setMap(map);
// Zoom to 9 when clicking on marker
google.maps.event.addListener(marker,'click',function() {
map.setZoom(20);
map.setCenter(marker.getPosition());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
// DAO(Data Access Object)
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class MemberDAOImpl {
Connection con=null;
PreparedStatement pstmt=null;
Statement stmt=null;
ResultSet rs=null;
DataSource ds=null;
String sql=null;
public int checkMemberId(String id){
int re=-1; // Available ID
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
try{
//
// con=ds.getConnection();
Class.forName(driver);//JDBC Driver Loading
con = DriverManager.getConnection(url, "scott", "tiger");
sql="select join_code from join_member where join_id=?";
pstmt=con.prepareStatement(sql);
pstmt.setString(1,id);
rs=pstmt.executeQuery();
if(rs.next()){
re=1; // Occupied ID
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(con != null) con.close();
}catch(Exception e){
e.printStackTrace();
}
}
return re;
}
member.js
function check(){
if($.trim($("#join_id").val())==""){
alert("Insert your ID");
$("#join_id").val("").focus();
return false;
}
if($.trim($("#join_pwd1").val())==""){
alert("Insert your password");
$("#join_pwd1").val("").focus();
return false;
}
if($.trim($("#join_pwd2").val())==""){
alert("Insert your password(again)");
$("#join_pwd2").val("").focus();
return false;
}
if($.trim($("#join_pwd1").val()) != $.trim($("#join_pwd2").val())){
alert("Please double-check your password");
$("#join_pwd1").val("");
$("#join_pwd2").val("");
$("#join_pwd1").focus();
return false;
}
if($.trim($("#join_name").val())==""){
alert("Insert your name");
$("#join_name").val("").focus();
return false;
}
if($.trim($("#join_zip1").val())==""){
alert("Insert your post code1");
$("#join_zip1").val("").focus();
return false;
}
if($.trim($("#join_zip2").val())==""){
alert("Insert your post code2");
$("#join_zip2").val("").focus();
return false;
}
if($.trim($("#join_addr1").val())==""){
alert("Insert your address1");
$("#join_addr1").val("").focus();
return false;
}
if($.trim($("#join_addr2").val())==""){
alert("Insert your address2");
$("#join_addr2").val("").focus();
return false;
}
if($.trim($("#join_tel2").val())==""){
alert("Insert your telephone number");
$("#join_tel2").val("").focus();
return false;
}
if($.trim($("#join_tel3").val())==""){
alert("Insert your mobile number1");
$("#join_tel3").val("").focus();
return false;
}
if($.trim($("#join_phone2").val())==""){
alert("Insert your mobile number2");
$("#join_phone2").val("").focus();
return false;
}
if($.trim($("#join_phone3").val())==""){
alert("Insert your mobile number3");
$("#join_phone3").val("").focus();
return false;
}
if($.trim($("#join_mailid").val())==""){
alert("Insert your email ID");
$("#join_mailid").val("").focus();
return false;
}
if($.trim($("#join_maildomain").val())==""){
alert("Insert the domain of your email");
$("#join_maildomain").val("").focus();
return false;
}
}
function post_search(){
alert("Click the search button");
}
function post_check(){
window.open("zipcode_find.nhn","Search",
"width=420,height=200,scrollbars=yes");
}
function id_check(){
$("#idcheck").hide();
var memid=$("#join_id").val();
if($.trim($("#join_id").val()).length < 4){
var newtext='<font color="red">Your ID must be at least 4 characters.</font>';
$("#idcheck").text('');
$("#idcheck").show();
$("#idcheck").append(newtext);
$("#join_id").val("").focus();
return false;
};
if($.trim($("#join_id").val()).length >12){
var newtext='<font color="red">Your ID must be less than 12 characters </font>';
$("#idcheck").text('');
$("#idcheck").show();
$("#idcheck").append(newtext);
$("#join_id").val("").focus();
return false;
};
if(!(validate_userid(memid))){
var newtext='<font color="red">Your ID must include lower case English and numbers</font>';
$("#idcheck").text('');
$("#idcheck").show();
$("#idcheck").append(newtext);
$("#join_id").val("").focus();
return false;
};
$.ajax({
type:"POST",
url:"member_idcheck.jsp",
data: {"memid":memid},
success: function (data) {
alert(data);
if(data==1){
var newtext='<font color="red">The ID already exists</font>';
$("#idcheck").text('');
$("#idcheck").show();
$("#idcheck").append(newtext);
$("#join_id").val('').focus();
return false;
}else{
var newtext='<font color="blue">Available ID</font>';
$("#idcheck").text('');
$("#idcheck").show();
$("#idcheck").append(newtext);
$("#join_pwd1").focus();
}
}
,
error:function(e){
alert("data error"+e);
}
}); //$.ajax() end
};
function validate_userid(memid){
var pattern= new RegExp(/^[a-z0-9_]+$/);
return pattern.test(memid);
};
function domain_list() {
var num=f.mail_list.selectedIndex;
if ( num == -1 ) {
return true;
}
if(f.mail_list.value=="0")
{
f.join_maildomain.value="";
f.join_maildomain.readOnly=false;
f.join_maildomain.focus();
}
else {
f.join_maildomain.value=f.mail_list.options[num].value;
f.join_maildomain.readOnly=true;
}
}