Best JSP Tutorial for Beginners [ 2020 Updated ] - onlyxcodes

Saturday, 16 December 2017

Best JSP Tutorial for Beginners [ 2020 Updated ]

You learning JSP well. But don’t forget your aim in learning the JSP tutorial. I have explained 15 best JSP amazing features you don’t know yet.

Let’s dive into it,

Best JSP Tutorial for Beginners 2020 Updated



Table Content

1. What is JSP ?

2. Why Choose JSP

3. Advantages of JSP

4. JSP Compare over Servlet

5. Basic Fundamentals of JSP

    5.1 Scripting Element of JSP

    5.2 JSP implicit object

6. Create JSP Project in XAMPP Server

    6.1 JSP project directory structure

    6.2 Simple JSP Program Hello World

7. Reading Web form Data using JSP

      7.1 Get method

      7.2 POST method

8. Call Java class on JSP using JavaBean

9. JSP MVC Architecture

10. JSP Directive Component

11. Web Template Dividing

12. JSTL

13. Session Management with JSP

14. JDBC : Insert, Update, Delete using JSP

15. Is JSP Dead or Not?


#1. What Is JSP ?


JSP(Java Server Pages) is widely used in the web development language of server-side programming.

JSP is an independent platform because it is written in java.

JSP also accesses objects from your JavaBean.

The additional features of JSP are that you can use the language of expression, JSTL.



#2. Why Choose JSP ?


Easily embedded with HTML tag, JSP inserts your business logic, adding HTML to your java codes.

Compared to Servlet, after not recompiling codes save your time, JSP codes will be modified.

JSP codes are written on the Java platform to make you feel secure about your project.

You can use the language of expression and JSTL reduces your project code.



#3. Advantages of JSP


1. Since it is written in Java, JSP is not dependent on any platform.

2. Web developer sends custom data on client-side using JSP.

3. Changing regular HTML is very simple. We will write the code for the servlet in the JSP.

4. JSP also plays the role of enterprise-level applications.

5. We can also use Java in JSP exception control.

6. This allows separating the display layer in the web application with the business logic unit.



#4. JSP Compare over Servlet


1. JSP has the feature of custom tags, which enables us to create reusable components, making them more flexible than Servlet.

2. We can make custom tag which directly calls JavaBean

3. Compare to Servlet, after not recompiling codes save your time, JSP codes will be modified.

4. Servlets put together both static code and dynamic code. They're divided into JSP.

5. We don't need to configure inside the web.xml file once we build the one JSP page.

6. Servlet presenting the data is very slow compare to JSP.



#5. Basic Fundamentals of JSP


5.1 Scripting Element of JSP


Comment :- You can explain your business logic codes on the JSP page. <% ------%>

<%-- my comment --%>

Scriptlet:- Use your logic codes more separately. Syntax :- <% jsp codes  %>

<%
  String name ="hamid";
  out.print(name);
%>

Expressions:- Use an expression to get a view of your database record on the JSP page. Syntax :- <%=  %>

<%= "Hamid" %>

Declaration:- Use a declaration to declare your variable and method. <! declare>

<%! int i=1; %>

5.2 JSP implicit object


See below JSP 9 implicit object. They are a map to Object from Servlet or JSP API.

1) request -  The request object is a java.servlet.http.HttpServletRequest illustration.

index.html

<form action="welcome.jsp">
    <input type="text" name="txt_name">
    <input type="submit" value="Click">
</form>

welcome.jsp

<%   
    String username=request.getParameter("txt_name");  
    out.print("welcome "+username);  
%>

Output :

JSP implicit request object

JSP implicit request object


2) response – The request object is a java.servlet.http.HttpServletResponse illustration.

index.html

<form action="welcome.jsp">
    <input type="submit" value="Click">
</form>

welcome.jsp

<%   
 response.sendRedirect("https://www.onlyxcodes.com/");
%>

Output :

JSP implicit response object

3) out – the out object of javax.servlet.jsp.jspWriter class. Using that to send the output on the client-side.

Example :

<% 
out.print("Hello");
%>

4) session – The session object use HttpSession API. Using that to handle authorize user login access activity.

index.jsp

<body>
    <%
        session.setAttribute("user", "My Name is Hamid");
    %>
 <a href="welcome.jsp">Click here and get Username</a>
</body>

welcome.jsp

<body>
    <%   
 out.print(session.getAttribute("user"));
    %> 
</body>

Output :

JSP implicit session object

JSP implicit session object

5) application – The application object is an illustration of javax.servlet.ServletContext. When the project is deployed on the server, ServletContext is created by the web container only once.

This object can be used from the configuration file (web.xml) to get setup parameters.

index.html

<form action="welcome">
    <input type="text" name="txt_name">
    <input type="submit" value="Click">
</form>

welcome.jsp

<%   
    out.println("Welcome in "+request.getParameter("txt_name")+ " " + "blog");  
  
    String owner=application.getInitParameter("founder");  
    out.println("Founder by = " +owner);  
        
%>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>onlyxcodes</servlet-name>
        <jsp-file>/welcome.jsp</jsp-file>
    </servlet>
    <servlet-mapping>
        <servlet-name>onlyxcodes</servlet-name>
        <url-pattern>/welcome</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>founder</param-name>
        <param-value>Hamid Shaikh</param-value>
    </context-param>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Output :

JSP implicit application object

JSP implicit application object


6) config – "Config" is the category java.servlet.servletConfig. For each JSP page, it is created by the container. Used to get the parameter of initialization in web.xml

index.html

<form action="welcome">
    <input type="text" name="txt_name">
    <input type="submit" value="Click">
</form>

welcome.jsp

<%   
    out.println("Welcome in "+request.getParameter("txt_name")+ " " + "blog");  
  
    String owner=config.getInitParameter("name");  
    out.println("Founder by = " +owner);  
        
%>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>onlyxcodes</servlet-name>
        <jsp-file>/welcome.jsp</jsp-file>
        
        <init-param>  
            <param-name>name</param-name>  
            <param-value>Hamid Shaikh</param-value>  
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>onlyxcodes</servlet-name>
        <url-pattern>/welcome</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Output :

JSP implicit config object

JSP implicit config object

7) page – The page implicit object is the same style as this variable of Java language

Example :

<%
    String pageName = page.toString();
    out.println("Page Name is " +pageName);
%>

We're going to use the page object's toString() method to try to get the JSP page string description.

Output :

JSP implicit page object

8) exception - The object of exception is the Throwable object that some other JSP page has thrown.

It is used for exception handling in JSP. But it can only be used in error pages.

index.jsp

<%@page isErrorPage="true" language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>error object</title>
    </head>
    <body>
        <%
            int no[] = {1,2,3};
            out.print(no[4]);
        %>
        <%= exception %>
    </body>
</html>

I take no name array variable with three elements. I try to get a fourth element array from no that, that not declare in Arryalist. So after executing project show error  java.lang.ArrayIndexOutOfBoundsException: 4

JSP implicit exception object

9) pageContext - This object is about the pageContext type. It is used to acquire, set and delete the attributes from a particular scope.

There are 4 types of scopes:

  • page

  • Request

  • Session

  • Application

index.jsp

<body>

    <% 
        
       pageContext.setAttribute("blog","onlyxcodes",pageContext.PAGE_SCOPE);
       
       String name = (String)pageContext.getAttribute("blog");
            
       out.println(name+ " " + "is web developing blog");
    %>
 
</body>

here the key is "blog" and value is "onlyxcodes". The scope is the scope of the page. The scope is "page" and that can using page only.

Output :

JSP implicit pageContext object



#6. Create JSP Project in XAMPP Server


6.1 JSP project directory structure


Create JSP Project in XAMPP Server

See above C:\xampp\tomcat\webapps\JSP-Started-Begginer, the name of your project's JSP-Started-Begginer folder.

Create MyJSP file and save must .jsp extension in the WEB-INF directory below.

WEB-INF directory structure will store your subfolder classes and lib. Store your Servlet java file in the folder classes and store your jar files in the lib folder.

6.2 Simple JSP Program Hello World


MyJSP.Jsp

Full code I covered comment, scriptlet & a decline of the JSP scripting element.

 
<html>

 <head>
  <title>JSP Started for Begginer </title>
 </head>
 
 <body>
 
  <%-- variable declaration --%>
  
  <%! String name="Hello JSP for Begginer"; %>
  
  <h1> 
  <%
   out.print(name);   
  %>
  </h1>
  
 </body>
 
<html>
 

Output :

Open and type your localhost web browser localhost:8080/JSP-Started-Beginner/ MyJSP.jsp.

Simple JSP Program Hello World



#7. Reading Web form Data using JSP


In web processing, forms are the common approach. We need to send data and this information to the webserver.

There are two methods used to send and get back data to the web server.

Get method :

  • This is the default method for passing browser-to-web server information.
  • Does this method display data on browser query string with separated by? symbol.
  • Get method allowed 1024 character to send your request it is the limitation of this method.
  • This method rarely uses like we get OTP number.

POST method :

  • This method not showing requested data on a browser query string.
  • The POST method secure than GET method.
  • No limit in the POST method. We send a large amount of data.

By the following method, JSP handles form data.

getParameter() – This method reads a single parameter value for the form.

getParameterValues() – This method read multiple parameter value fro the form.

getParameterNames() – Servlet didn’t know the parameter name.  Using getParameterNames() to get the parameter names.

index.jsp

<%@page isErrorPage="true" language="java" contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Registration Form - Onlyxcodes</title>
    </head>
    <body>
        <form method="post" action="process.jsp">
            <table>
                <tr>
                    <td>Firstname</td>
                    <td><input type="text" name="txt_firstname"></td>
                </tr>
                <tr>
                    <td>Lastname</td>
                    <td><input type="text" name="txt_lastname"></td>
                </tr>
                <tr>
                    <td>Address</td>
                    <td><input type="text" name="txt_address"></td>
                </tr>
                <tr>
                    <td><input type="submit" name="btn" value="Regsiter"></td>
                </tr>
            </table>
        </form>
    </body>
</html>

process.jsp

<%
    if(request.getParameter("btn")!=null)
    {
        String fname = request.getParameter("txt_firstname");
        String lname = request.getParameter("txt_lastname");
        String add = request.getParameter("txt_address");
        
        if(fname.isEmpty() || lname.isEmpty() || add.isEmpty())
        {
            RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
            rd.include(request, response);
        }
        else
        {
            RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
            rd.forward(request, response);
        }
    }
%>

welcome.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Registration Form - Onlyxcodes</title>
    </head>
    <body>
        <h1>Hello User Welcome</h1>
    </body>
</html>

See above sample JSP registration form and take three fields first name, last name and address.

You submit form at that time cause process.jsp page becuase form action= "process.jsp".

The process.jsp page get whole text box value by getParameter() method.

is.Empty() function check whole text box value not null. If found RequestDispatcher included in index page. rd.include(request, response)

If submit forward to welcome page. rd.forward(request, response).



#8. Call Java class on JSP using JavaBean 


Using JavaBean class object to access your Java class or Java method on JSP page

index.jsp

<%@page import="MyBeanClass"%>

<%
 MyBeanClass mbc = new MyBeanClass();
 
 String username=mbc.getUsername(); //get username value through mbc object 
 String password=mbc.getPassword(); //get password value through mbc object 
%>

Create a java class called MyBeanClass and apply the object called mbc. The mbc object will efficiently acquire that class property or value and store variables in username and password.

To include this class on the JSP page, use the page directive tag. import is this tag's attribute and this attribute's MyBeanClass value.

MyBeanClass.java

Use this class to set and return the property or value of your text box by setter and getter method efficiently.

public class MyBeanClass 
{
    private String username,password;
    
    public String getUsername(){
        return username;
    }
    public void setUsername(String username){
        this.username=username;
    }
    public String getPassword(){
        return password;
    }
    public void setPassword(String password){
        this.password=password;
    }
}



#9. JSP MVC Architecture


What is MVC ?


MVC is a methodical way to build standard web application. where the movement begins from the view layer, where the request is elevated and processed in the controller layer and sent to the model layer for data injection and recovery of success or failure.

M stands for Model

V stands for View

C stands for Controller

JSP MVC Architecture

Model :- 

  • This layer represents the business logic. Example to execute your secret SQL query.
  • This layer maintains your data in a database after remodified. Example insert update deletes operations.
  • Your application all controller are connected with model and obtain data and send to the view layer.

View :-  

  • This is a presentation layer.
  • To put your HTML or JSP pages. Also including your UI graphics information like images, photo, registration form, JavaScript validations, etc.
  • This layer responsible displays data obtained from the controller layer.
  • Also, display database data send from model to controller.

Controller :- 

  • This is the middle part of applications.
  • This layer communicates between the model and the view.
  • This layer gets client request and sends to model. The further model solves the query and sends it to the controller after that sends a response to the client.
  • The controller layer responsible displays data according to the client request.

JSP MVC login example with Servlet


Requirement of this project

Eclipse – Download this application build in eclipse editor.

Apache tomcat – Download this project execute on the Apache tomcat server

jsp mvc examples in eclipse

Index.jsp (view) – this file is view page and provide a simple login form.

Invalid.jsp(view) – this file shows the wrong username and password message.

LoginController.java  (Controller) – this file is a servlet file. Play the role of controller. Get a relative URL from send a login form action attribute.

LoginBean.java (Model) – this file plays the role of model. Set login form property effectively by setter and getter method.

LoginDao (Model) – this file is a model file. This file contains the main business logic check username and password valid or not.

index.jsp

 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>JSP MVC Login Example - Onlyxcodes</title>
</head>
<body>

 <center>
            
     <h2>Login Page</h2>
            
     <form method="post" action="LoginController">
                
         Username    :<input type="text" name="txt_username">
         Password    :<input type="password" name="txt_password">
                
           <input type="submit" name="btn_login" value="Login"> 
  </form>
                
    </center>
    
</body>
</html>
 

LoginController.java

package com.mvc.controller;

import java.io.IOException;

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

import com.mvc.bean.LoginBean;
import com.mvc.dao.LoginDao;


@WebServlet("/LoginController")
public class LoginController extends HttpServlet {
 
 private static final long serialVersionUID = 1L;
       
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
  if(request.getParameter("btn_login")!=null) //check index.jsp page button attribute "btn_login" not null and check not null
  {
   String username = request.getParameter("txt_username"); //get textbox name "txt_username"
   String password = request.getParameter("txt_password"); //get textbox name "txt_password"
   
   LoginBean loginBean = new LoginBean(); // this class file play role model, and set up text box value privately and effectively by setter and getter method
   
   loginBean.setUsername(username); //set username through loginBean object
   loginBean.setPassword(password); //set password through loginBean object
   
   LoginDao loginDao = new LoginDao(); //this class contain main logic to perform function calling and check authorize username and password valid or not 
   
   String check = loginDao.authorizeLogin(loginBean); //check receive string "SUCCESS LOGIN" match or not from send authorizeLogin() function, if match send to welcome.jsp page
   
   if(check.equals("SUCCESS LOGIN"))
   {
      RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp"); //redirect to welcome.jsp page
      rd.forward(request, response);
   }
   else
   {
      RequestDispatcher rd=request.getRequestDispatcher("invalid.jsp"); //send error on index.jsp page
      rd.include(request, response);
   }
   
  }
  
 }

}

LoginBean.java

package com.mvc.bean;

public class LoginBean {
 
 private String username, password;

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
 
}

LoginDao.java

package com.mvc.dao;

import com.mvc.bean.LoginBean;

public class LoginDao 
{
 public String authorizeLogin(LoginBean loginBean) //create authorizeLogin() method with String return type
 {
  String username = loginBean.getUsername(); //get username value through loginBean object and store in temporary variable "username"
  String password = loginBean.getPassword(); //get password value through loginBean object and store in temporary variable "password"
  
  if(username.equalsIgnoreCase("hamid") && password.equalsIgnoreCase("hamid")) //apply if condition check username match with "hamid" and password match with "hamid" both are true than send return type string below 
  {
   return "SUCCESS LOGIN"; //if valid send return type string "SUCCESS LOGIN"
  }
  else
  {
   return "WRONG USERNAME AND PASSWORD"; //if invalid send return type string "WRONG USERNAME AND PASSWORD"
  }
  
 }

}

welcome.jsp

 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

 <center>
  <h2>Welcome you are successfully login :) </h2>
  
  <a href="index.jsp"> Back </a>
  
 </center>

</body>
</html>
 

invalid.jsp

 
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>JSP MVC Login Example - Onlyxcodes</title>
</head>
<body>

 Sorry, invalid username and password
 
 <br /> 
 <a href="index.jsp">Back to Login </a>

</body>
</html>
 

Explanation :

Start the tomcat server. An executing project you see login form or index.jsp page.

Enter username as "hamid" and password as "hamid". After you redirect on welcome.jsp page and you see welcome you are successfully login message. 

1. First occurred LoginController. Because the form action="LoginController"

2. In LoginController, LoginBean loginBean = new LoginBean() class occurred the model to be execute and set the LoginBean properties.

3. Next LoginDao loginDao = new LoginDao() class check valid username and password.

4. If valid rd.forward(request,response); Servlet forward to welcome.jsp page.

5. If invalid rd.forward(request,response); Servlet forward to invalid.jsp page. 

Learn More JSP MVC Example





#10. JSP Directive Component


The JSP directives are signals informing the web container of how to convert a JSP document into the correct servlet.

Three types of directive let’s drive into it.

Syntax of JSP Directive

<%@ directive attribute="value" %>

1) Page directive - The page directive assigns attributes for a whole JSP page.

Page directive attribute :-

  • import - Indicates a collection of JSP packages or classes as does the Java import statement for Java classes.<%@ page import="java.util.Date" %>
  • contentType – The contentType specifies the character encoding scheme for MIME(Multipurpose Internet Mail Extension).<%@ page contentType="text/html" %>
  • extends – The extends attribute to set the parent class of Servlet that will be inherited by generated Servlet.
  • info – The info defines a string that can be accessed using getServletInfo() method. Use this attribute to set the description of the servlet.<%@ page info="This is Directive" %>

Here, the string "This is Directive" can be obtained by the Servlet getServletInfo() method in the web container.

  • buffer - The buffer attribute specifies the buffer size for handling output generated by the JSP page in kilobytes. The default buffer size is 8Kb. <%@ page buffer="16kb" %>
  • language – The language attribute defines scripting language depend upon what we want to use.<%@ page language="java" %>
  • isELIgnored – Using this attribute to ignoring the Expression Language(EL) in the JSP page.

<%@ page isELIgnored="true" %> using that EL will be ignored

<%@ page isELIgnored="false" %> using that EL to not ignored

  • autoFlush - autoFlush attribute defines the automatic flush of the buffered output. The default is "true". <%@ page autoFlush="false" %>

If the value is set to null, the buffer will not necessarily be flushed and we will get an exception if it is full.

  • session - The session attribute determines the presence of the JSP page in an HTTP session. Either the value is true or false.

<%@ page session="false" %> // the session don’t indicate in JSP page

<%@ page session="true" %> // the session indicate in JSP page

  • pageEncoding - The attribute "pageEncoding" describes the JSP page character encoding. If no other is defined, the default is "ISO-8859-1". <%@ page pageEncoding=" ISO-8859-1" %>
  • errorPage - errorPage attribute shows another JSP page to handle all the runtime exceptions from the current JSP page.<%@ page errorPage="errorTrack.jsp" %>
  • isErrorPage – The attribute isErrorPage specifies whether the current JSP page represents the error page of another JSP.

<%@ page isErrorPage="true" %> OR <%@ page errorPage="false" %>

2) Include directive – Using include directive tag to include your another JSP file or page.

<%@ include file="test.jsp" %>

3) Taglib directive - The JSP taglib directive defines a tag library that defines a bunch of tags.

<%@ taglib uri="http://java.sun.com/jsp/core" prefix="mytag" %>



#11. Web Template Dividing


JSP provides divide your web template using the Include Directive

Example divide header.jsp, index.jsp and footer.jsp into three sections. Syntax:- <% @ file="your file" percent is included. 

header.jsp


<body> 

    <h1>header Page</h1>
 
</body>
 

footer.jsp


<body> 

    <h1>footer Page</h1>
 
</body>

index.jsp

<body>
        
    <%@ include file="header.jsp"%>
        
 <h1>This is Index Page</h1>
        
    <%@ include file="footer.jsp"%>
        
</body>

Web Template Dividing using JSP

Use the include directive tag above to see that I include the header.jsp page and the footer.jsp page on the index.jsp page. You divide your web template easily. 



#12. JSTL


JSTL is split into 5 categories:

1) JSTL Core - JSTL Core produces many-core tags to assist some basic scripting tasks, such as if, forEach, import, out, etc.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2) JSTL Formatting - JSTL Formatting Library supplies tags for the formatting of text, date, number.

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

3) JSTL SQL - JSTL SQL library supports Relational Database Connection and tags for SQL database operations such as inserting, deleting, updating, selecting, etc.

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

4) JSTL XML - The JSTL XML library allows the retrieval of XML. It provides control of flow, features of transformation, etc.

<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

5) JSTL Functions - The library of JSTL functions allows string manipulation.

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>



#13. Session Management with JSP


Using session.setAttribute() method to maintain the state between client and web server.

See below example I take a simple login form with two fields username and password.

index.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Session Management in JSP - Onlyxcodes</title>
    </head>
    <body>
        <form method="post" action="authorize.jsp">
            <table>
                <tr>
                    <td>Username</td>
                    <td><input type="text" name="txt_uname"></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="txt_pwd"></td>
                </tr>
                <tr>
                    <td><input type="submit" name="btn_login" value="Login"></td>
                </tr>
            </table>
        </form>
    </body>
</html>

authorize.jsp

<%
    if(request.getParameter("btn_login")!=null)
    {
        String uname = request.getParameter("txt_uname");
        String pwd = request.getParameter("txt_pwd");
        
        if(uname.isEmpty() || pwd.isEmpty())
        {
            RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
            rd.include(request, response);
        }
        else
        {
            session.setAttribute("user", uname);
            RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
            rd.forward(request, response);
        }
    }
%>

welcome.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Session Management in JSP - Onlyxcodes</title>
    </head>
    <body>
        <h1>
            <% 
                out.print(session.getAttribute("user"));
            %>
        </h1>
    </body>
</html>

You submit form at that time cause authorize.jsp page because form action="authorize.jsp"

Via getParameter() method get username and password values.

is.Empty() function check form whole value not null. If found include in index.jsp page. rd.include(request, response).

If both fill up assign session using session.setAttribute() method.

Here, the "user" is session object name and uname of username you type on the text box.

After forward to welcome.jsp page. rd.forward(request, response).

In welcome.jsp page get session object "user" using session.getAttribute() method. That’s it.

Output :

Session Management with JSP

Session Management with JSP



#14. JDBC : Insert, Update, Delete using JSP 


JSP opens more MySQL, Oracle, Msaccess, PostgresSQL database connectivity.

We will learn to insert update delete using JSP with JDBC.

create a person table in oracle SQL command prompt.

create table in oracle sql command

Insert records


<%
    String url="jdbc:oracle:thin:@localhost:1521:XE" ; //database url string
    String username="system"; //database username
    String password="tiger"; //database password

    try
    {
        Class.forName("oracle.jdbc.driver.OracleDriver"); //load driver
        Connection con=DriverManager.getConnection(url,username,password); //create connection
        
        PreparedStatement pstmt=null; //create statement
        
        pstmt=con.prepareStatement("INSERT INTO person(id, name,owner) VALUES (1, 'Steve Jobs', 'Apple' )"); //sql insert query
        pstmt.executeUpdate();
            
        out.println("Insert Successfully");
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
%>
 

You can see the oracle database reference example above. 

Within the try/catch block, you can customize your database connection if there is an error in the database related to this block throwing it an error.

Class.forName() – this method loads the oracle JDBC class driver explicitly.

DriverManager.getConnection() – To create a database connection, paste our database connections variables url, username and password. 

After connecting the database to assign the Connection object. 

out.print() – This method will show your text messages, use this method to verify whether or not the database connects to the custom message. 

close() – using this method to close your database connection with con object.

output :

JDBC Insert data using JSP

Update records


See below simple update query using that we have updated the records

pstmt=con.prepareStatement("UPDATE person SET name='Bill Gates', owner='Microsoft' WHERE id=1)"); //sql update query
pstmt.executeUpdate();

output :

JDBC Upate data using JSP

Delete records


See below our delete query using that to delete database table records.

pstmt=con.prepareStatement("DELETE FROM person WHERE id=1)"); //sql delete query
pstmt.executeUpdate();

Learn More



#15. Is JSP Dead or Not?


Answer :  "NO".

JSP is always played a role in Java Web-Based Applications, Enterprise Applications, Web designer use own purpose.

Without JSP we don't have to handle view layer architecture on client-side and more etc.

No comments:

Post a comment