Unit – 2
JSP
JSP stands for Java Server Pages, and it's a technology for creating interactive Web pages. This allows developers to embed java code in HTML pages by using special JSP tags, the majority of which begin with % and end with % >.
A Java Server Pages component is a type of Java servlet that serves as the user interface for a Java web application. JSPs are text files that contain HTML or XHTML code, XML components, and embedded JSP actions and commands, and are written by web developers.
You can use JSP to collect user feedback via Web Page forms, present records from a database or another source, and dynamically construct Web Pages.
JSP tags can be used for a number of things, including retrieving data from a database or registering user preferences, interacting with JavaBeans components, transferring control between pages, and exchanging data between requests, pages, and so on.
Why use JSP?
Java Server Pages are often used in the same way that programs written with the Popular Gateway Interface are (CGI). However, as compared to CGI, JSP has some advantages.
Finally, JSP is an essential component of Java Enterprise Edition (Java EE), a comprehensive framework for enterprise-class applications. As a result, JSP can be used in a wide range of applications, from the easiest to the most complex and challenging.
Advantages of JSP
Key takeaway
The steps below show how the web server uses JSP to produce the webpage.
● Your browser sends an HTTP request to the web server, just like it would for any other page.
● The web server recognizes the HTTP request as being for a JSP page and sends it to a JSP engine. This is accomplished by utilizing a URL or JSP page that ends in.jsp rather than.html.
● The JSP engine fetches a JSP page from disk and turns it to servlet content. All template text is translated to println() commands, and all JSP components are converted to Java code in this conversion. This code is used to implement the page's dynamic behavior.
● The JSP engine converts the servlet into an executable class and sends the request to the servlet engine.
● The servlet engine is a component of the web server that loads and executes the Servlet class. During running, the servlet generates an HTML output. The servlet engine then sends the output to the web server as part of an HTTP response.
● In terms of static HTML content, the web server sends the HTTP response to your browser.
● Finally, the web browser treats the dynamically created HTML page contained within the HTTP response identically to a static page.
● The JSP engine converts the servlet into an executable class and sends the request to the servlet engine.
● The servlet engine is a component of the web server that loads and executes the Servlet class. During running, the servlet generates an HTML output. The servlet engine then sends the output to the web server as part of an HTTP response.
● In terms of static HTML content, the web server sends the HTTP response to your browser.
● Finally, the web browser treats the dynamically created HTML page contained within the HTTP response identically to a static page.
Fig 1: JSP processing
The JSP engine typically checks to determine if a servlet for a JSP file already exists and if the JSP's update date is older than the servlets. The JSP container assumes that the JSP hasn't changed and that the created servlet still matches the JSP's contents if the JSP is older than the generated servlet. This makes the procedure more efficient and thus faster than with other scripting languages (such as PHP).
In some ways, a JSP page is merely another way to construct a servlet without needing to be an expert in Java programming. A JSP page is treated identically like a standard servlet, with the exception of the translation process.
Key takeaway
Everything from the simplest web application, such as an online phone book or an employee vacation planner, to full-fledged corporate applications, such as a human resource application or a complex online shopping site, can benefit from JSP technology. introduces the Model-View-Controller (MVC) design model, which can be used for both simple and complex applications.
In a series of articles released in the late 1980s, Xerox explained MVC for the first time. The key to using MVC is to break down components into three discrete units: Model, View, and Controller. The parts of a server application are generally divided into three categories: business logic, presentation, and request processing.
● The word "business logic" refers to the manipulation of data in an application, such as customer, product, and order information.
● The position, typeface, and size of the program are all factors in how it is presented to the user.
● Finally, request processing is responsible for connecting the business logic and presentation components.
Fig 2: MVC
Model
● The data layer is the model layer.
● It contains all of the information from our online application.
● It represents an application's current state.
● The Model Layer is in charge of both connecting to the database and storing the data in it.
● It contains all of the classes in our program that have a database connection.
View
● It denotes the layer of presentation.
● It usually represents the application's User Interface (UI).
● To develop a presentation layer, we can utilize HTML, CSS, and JS, among other things.
Controller
● It serves as a link between the view and model layers.
● View Layer sends it a request, which it accepts.
● It takes the data from the presentation layer and reads it.
● We can utilize Servlet, JSP, Filter, and other tools to read data from the presentation layer.
Key takeaway
Apache Tomcat, commonly known as Tomcat Server, is a popular choice among web developers who are creating and maintaining dynamic websites and Java-based applications. Tomcat is said to have been named by the founder's vision of an animal that could care for and fend for itself. In the same way, Apache Tomcat is contributed to by developers all around the world, thus it takes care of itself.
Apache Tomcat is a Java Servlet container, or web container, that was first released in 1999 as an open-source project by the Apache Software Foundation (ASF). It provides extended functionality for interacting with Java Servlets while also implementing several technical specifications of the Java platform, including
● Java Server Pages (JSP)
● Java Expression Language (Java EL), and
● WebSocket.
The most recent version of Apache Tomcat is 9.x, which is currently in active development. Servlet 5.0, JSP 3.0, EL 4.0, WebSocket 2.0, and Authentication 2.0 should all be supported in version 10. Versions 9 and 10 of Tomcat support Java 8 and later.
Tomcat is used for?
Because Tomcat just serves as a Web server and a Servlet container, it is not considered a full application server. It doesn't have all of the Java EE features, but it isn't necessarily a drawback. Many applications just require Tomcat's functionality, thus upgrading to the more powerful tools isn't necessary. If the functionality provided by Apache Tomcat is sufficient, you can use it for production applications that process millions of requests. In any event, Tomcat is a ready-to-use application.
How does Tomcat work?
Tomcat is a platform-independent application, and installing it is simple as long as you have Java installed. Simply download the desired version from the official website and unpack it on your computer's file system. You can test Tomcat's installation by launching the server from the $CATALINA_BASE/bin folder using a startup script.
Open your browser and go to http://localhost:8080 after the server is up and running (if the default configuration is used). If you see a page that looks like the one below, Tomcat has been properly installed.
Fig 3: Tomcat server installation page
It's quite simple to deploy the application to the server. Tomcat supports startup deployment, which means you can copy compressed (.WAR) or uncompressed (exploded web application) files to the correct directory, $CATALINA BASE/webapps/.
If you wish to deploy the application on the fly, you can use the Tomcat Web Application Manager GUI to deploy the application to a running Tomcat server. The Manager App in Tomcat can be used to manage all of the deployed applications.
Fig 4: Web application manager GUI
Tomcat makes use of a few major components. Catalina is the actual Servlet container that implements the Servlets and Java Server Pages specification. Coyote, the other component, handles all HTTP connectivity and sends requests to the Tomcat Engine (Catalina).
Components
Catalina (servlet container), Coyote (HTTP connector), and Jasper were all included in Tomcat 4.x (a JSP engine).
Catalina
Tomcat's servlet container is named Catalina. Sun Microsystems' servlet and Java Server Pages specifications are implemented by Catalina (JSP). A Realm element in Tomcat is a "database" of usernames, passwords, and responsibilities (akin to Unix groups) that have been allocated to those users. Catalina may be integrated into environments where authentication information is already being created and maintained, and then use that information to build Container Managed Security as stated in the Servlet Specification, using different implementations of Realm.
Coyote
Coyote is Tomcat's HTTP Connector component, which allows the web server or application container to use the HTTP 1.1 protocol. On the server, Coyote waits for incoming connections on a certain TCP port and transmits the request to the Tomcat Engine, which processes it and responds to the requesting client. It is capable of running JSPs and Servlets. Jasper Tomcat's JSP Engine is named Jasper. Jasper parses JSP files and compiles them as servlets in Java code (that can be handled by Catalina). Jasper recognizes changes to JSP files and recompiles them at runtime.
Key takeaway
These Objects are Java objects that the JSP Container makes accessible to developers in each page, and the developer can call them without having to declare them explicitly. Pre-defined variables are another name for JSP Implicit Objects.
The nine Implicit Objects that JSP supports are mentioned in the table below.
No. | Object | Description |
1 | request | This is the HttpServletRequest object that the request is associated with. |
2 | response | This is the HttpServletResponse object that corresponds to the client's response. |
3 | out | This is the PrintWriter object, which is responsible for sending output to the client. |
4 | session | This is the HttpSession object that the request is connected with. |
5 | application | The application context is associated with this ServletContext object. |
6 | config | This is the page's associated ServletConfig item. |
7 | pageContext | This includes the use of server-specific features such as faster JspWriters. |
8 | page | This is just another name for this, and it's used to call the methods specified by the translated servlet class. |
9 | Exception | The Exception object allows designated JSPs to access exception data. |
The request Object
The request object is a javax.servlet instance. http.HttpServletRequest is an entity that represents a http.HttpServletRequest request. When a client requests a page, the JSP engine generates a new object to represent it.
The request object contains methods for retrieving HTTP header information such as form data, cookies, and HTTP methods, among other things.
The response Object
The answer object is a javax.servlet.http.HttpServletResponse object, which is an instance of javax.servlet.http.HttpServletResponse. The server creates an object to represent the answer to the client in the same way that it creates the request object.
The interfaces for creating new HTTP headers are also defined by the response object. The JSP programmer will use this object to add new cookies, date stamps, HTTP status codes, and so on.
The out Object
The out implicit object is a javax.servlet.jsp.JspWriter object that is used to submit content as part of a response.
Depending on whether the page is buffered or not, the initial JspWriter object is generated in a different way. The buffered = 'false' attribute of the page directive can be used to switch off buffering.
Many of the methods in the JspWriter object are the same as those in the java.io.PrintWriter class. JspWriter, on the other hand, has several additional buffering methods. JspWriter, unlike the PrintWriter object, throws IOExceptions.
The session Object
The session object is a javax.servlet.http.HttpSession instance that behaves in the same way that session objects in Java Servlets do. The session object is used to keep track of a client's session from one request to the next.
The application Object
The application object is a wrapper around the ServletContext object for the created Servlet, and is actually a javax.servlet. ServletContext kind.
This object represents a JSP page during its entire life cycle. This object is generated when the JSP page is first loaded and is removed when the jspDestroy() method is used to delete the JSP page.
You will ensure that all JSP files that make up your web application have access to it by adding an attribute to the application.
The config Object
The config object is an instantiation of javax.servlet.ServletConfig and For the created servlet, is a direct wrapper around the ServletConfig item.
This object gives the JSP programmer access to Servlet or JSP engine initialization parameters including paths and file positions, among other things.
The pageContext Object
A javax.servlet.jsp.PageContext object is an instance of the pageContext object. The entire JSP page is represented by the pageContext object.
This object is designed to provide access to page information while removing most of the implementation specifics.
The page Object
This object is a real-time reference to the page's case. It's similar to an object that represents the entire JSP page.
The page object is essentially the same as this object.
The Exception Object
The exception object is a wrapper that contains the previous page's exception. It's usually used to come up with a suitable answer to an error state.
Key takeaway
In most web applications, distinct output is produced depending on runtime factors, such as the state of a bean or the value of a request header like UserAgent (containing information about the type of client that is accessing the page).
If the variations are minor, you can utilize JSP scripting elements to control which sections of the JSP page are transmitted to the browser, resulting in different outputs from the same JSP page. If the outputs are absolutely distinct, though, I recommend creating a separate JSP page for each option and passing control from one to the other. This chapter includes several cases where only one page is used.
We have used two of the three JSP scripting elements: scriptlets and expressions. A declaration element, which is used to declare variables and methods in a JSP page, is another option.
public class SomeClass {
// Instance variable
private String anInstanceVariable;
// Method
public void doSomething( ) {
String aLocalVariable;
}
}
An instance variable is a variable declared outside the body of all methods. Its value is accessible from any method in the class, and it retains its value even after the method that sets it returns. A local variable is a variable declared within the body of a method. Only the method in which a local variable is declared can access it. The local variable vanishes when the method returns.
Scriptlet
Any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language can be included in a scriptlet.
The syntax of Scriptlet is as follows:
<% code fragment %>
Declaration
A declaration defines one or more variables or methods that can be used later in the JSP file in Java code. Before you use a variable or method in a JSP file, you must define it.
The syntax for JSP Declarations is as follows:
<%! declaration; [ declaration; ]+ ... %>
The following is the XML equivalent of the above syntax:
<jsp:declaration>
code fragment
</jsp:declaration>
An example of a JSP Declaration is shown below.
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>
Example of method declarations
<%@ page language="java" contentType="text/html" %>
<html>
<body bgcolor="white"> <%!
String randomColor( ) {
java.util.Random random = new java.util.Random( );
int red = (int) (random.nextFloat( ) * 255);
int green = (int) (random.nextFloat( ) * 255);
int blue = (int) (random.nextFloat( ) * 255);
return "#" +
Integer.toString(red, 16) +
Integer.toString(green, 16) +
Integer.toString(blue, 16);
}
%>
JSP Expression
A programming language expression is evaluated, transformed to a String, and inserted where the expression appears in the JSP file in a JSP expression element.
Because an expression's value is converted to a String, you can use it in a JSP file within a line of text, whether or not it is tagged with HTML.
Any expression that is legitimate according to the Java Language Specification can be used in the expression element, although a semicolon cannot be used to finish an expression.
The syntax for JSP Expression is as follows:
<%= expression %>
Key takeaway
Errors are unavoidable when developing any program that is more complex than a simple example. It's no different with a JSP-based application. You'll have to deal with a variety of errors. During the development phase, simple syntax errors in JSP pages are almost unavoidable. Even after you've addressed all the syntax problems, you might still need to figure out why the application isn't working the way you wanted it to due to design flaws.
The program must also be built to handle issues that may arise once it is launched for production use. Users can enter incorrect data and try to utilize the application in unexpected ways. Network difficulties can cause external systems, such as databases, to fail or become inaccessible.
Because a web application is a company's face, it's critical to ensure that it acts smoothly even when people misbehave and the environment around it falls apart for a positive consumer view. The only way to achieve this goal is through proper design and testing. Unfortunately, when it comes to creating online applications, many developers appear to forget the hard-learned lessons from traditional application development.
Syntax Error
The first form of problem you'll come across is one caused by simple typos made by you or your coworkers: a syntax error. To convert a JSP page into a valid servlet class, the JSP container requires that each JSP element be written exactly as it is stated in the standard. It will alert you if it discovers something that isn't quite correct. However, how easy it is to comprehend what it says is dependent on the sort of fault, the JSP container implementation, and, in some cases, how fluent you are in computer jargon.
Scripting syntax Error
Unfortunately, syntax problems in scripting components result in far more difficult-to-understand error messages. Because of the way the JSP container handles scripting code when converting a JSP page to a servlet, this is the case. The container reads the JSP page and generates servlet code by replacing all JSP directives and actions with suitable code. This necessitates a thorough examination of these types of features. It can simply detect which element is faulty if there is a syntax problem in a directive or action element.
Scripting components, on the other hand, are generally used as-is in the servlet code that is generated. A syntax problem in scripting code is identified when the resultant servlet is compiled, not when the JSP page is read. The compiler reports a mistake in terms of where it appears in the resulting servlet code (rather than where it appears in the JSP page), with messages that aren't always clear to a JSP page author.
Debugging
Testing and debugging JSPs and servlets are never easy. Because JSP and Servlets entail a lot of client/server interaction, problems are likely yet difficult to reproduce.
Here are a few pointers and tips to help you with your troubleshooting.
Using System.out.println()
System.out.println() is a handy marker for determining whether or not a piece of code is being run. Variable values can also be printed. Take into account the following extra considerations:
● Because the System object is part of the core Java objects, it can be used everywhere without requiring the installation of any additional classes. Servlets, JSPs, RMIs, EJBs, regular Beans and classes, and standalone apps are all examples of this.
● Writing to System.out has a lower impact on the application's normal execution flow than stopping at breakpoints, which makes it highly useful when timing is critical.
Following is the syntax to use System.out.println() −
System.out.println("Debugging message");
Following example shows how to use System.out.print() –
<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>System.out.println</title></head>
<body>
<c:forEach var = "counter" begin = "1" end = "10" step = "1" >
<c:out value = "${counter-5}"/></br>
<% System.out.println( "counter = " + pageContext.findAttribute("counter") ); %>
</c:forEach>
</body>
</html>
When you visit the above JSP, your browser will display the following result:
-4
-3
-2
-1
0
1
2
3
4
5
These lines will also be appended to the end of stdout.log in the logs directory if you're using Tomcat.
counter = 1
counter = 2
counter = 3
counter = 4
counter = 5
counter = 6
counter = 7
counter = 8
counter = 9
counter = 10
This allows you to add variables and other data to the system log, which may then be evaluated to determine the root cause of the problem or for a variety of other purposes.
Debugging tools
NetBeans is a free and open-source Java Integrated Creation Environment that contains a JSP debugger and facilitates the development of standalone Java programs and Web applications that implement the JSP and servlet specifications.
The following basic debugging features are supported by NetBeans:
● Breakpoints
● Stepping through code
● Watchpoints
Key takeaway
HTTP is a "stateless" protocol, which means that each time a client requests a Web page, the client establishes a new connection with the Web server, and the server does not retain track of prior requests.
Data is made available to multiple sites processing the same request thanks to the request scope. However, data must frequently be transferred over numerous requests.
Consider an application for a travel agency. It's critical to remember the dates and destination entered when booking a flight so that the consumer doesn't have to reenter the information when booking a hotel or renting a car. The session scope can be used to provide information that is only available to requests from the same user.
Regardless of who the current user is, some information is required by numerous sites. Through the application scope, JSP allows access to this type of shared data. Even if the two pages were requested by separate users, information kept in the application scope by one page can later be retrieved by another page. Database connection pool objects, information about currently logged-in users, and cache objects that avoid wasteful database queries for data that is the identical for all users are examples of information that is often shared across the application scope.
Fig 5: Session and application scopes
Counting page Hits
To demonstrate how the scope influences the lifetime and reach of shared information, a simple page counter bean can be utilized. When you use the bean in both the session and application contexts, the distinction between the two scopes becomes clear.
Example: A page with counter beans
<%@ page language="java" contentType="text/html" %>
<html>
<head>
<title>Counter page</title>
</head>
<body bgcolor="white">
<jsp:useBean
id="sessionCounter"scope="session"
class="com.ora.jsp.beans.counter.CounterBean"
/>
<jsp:useBean
id="applCounter"
scope="application"
class="com.ora.jsp.beans.counter.CounterBean"
/>
<% String uri = request.getRequestURI( ); %>
<h1>Counter page</h1>
This page has been visited <b>
<%= sessionCounter.getNextValue(uri) %>
</b> times by the current user in the current session, and <b>
<%= applCounter.getNextValue(uri) %>
</b> times by all users since the application was started.
</body>
</html>
<c:set> Counters in the session and application scopes are incremented by activities. Take note of how the scope property is used to place each counter variable in a specific scope. Every time the same browser requests this page, the variable in the session scope is detected, and so counts hits per browser. However, because the application scope variable is shared by all users, it counts the total number of hits for this page.
You should get a page that looks like Figure if you execute this example.
Fig 6: A page with session and application page hit counters
Because none of the counter variables exist the first time you visit the page, the <c:set> operations generate them and set them to 1 (the EL interprets a missing variable as 0 when used in an arithmetic operation). The session and application counters remain in sync as long as you use the same browser. When you close and restart your browser, however, a new session is formed when you go to the initial page. The session counter resets to 1, but the application counter resumes where it left off at the end of the previous session.
URL Rewriting
At the end of each URL, you can attach some more info. This information identifies the session, and the server can link that identification to the information it has on that session.
The session ID required to maintain track of requests within a single session can be passed back and forth between the server and the browser in a variety of ways. One method is to encrypt it in the URLs generated by JSP pages. This is referred to as URL rewriting. Even if the browser doesn't support cookies, this method works.
URL rewriting is a better technique to keep sessions alive, and it works even if your browser doesn't support cookies. The disadvantage is that, even though the website is a simple static HTML page, you will have to build every URL dynamically to issue a session ID.
Example: Page with an Encoded Reference to Another Page (counter2.jsp)
<%@ page language="java" contentType="text/html" %>
<html>
<head>
<title>Counter page 1</title>
</head>
<body bgcolor="white">
<jsp:useBean
id="sessionCounter"
scope="session"
class="com.ora.jsp.beans.counter.CounterBean"
/>
<% String uri = request.getRequestURI( ); %>
<h1>Counter page 1</h1>
This page has been visited <b>
<%= sessionCounter.getNextValue(uri) %>
</b> times by the current user in the current session.
<p>
Click here to get to
<a href="<%= response.encodeURL("counter3.jsp") %>">
Counter page 2</a>.
</body>
</html>
Key takeaway
References: