- JSP is the technology used in Java web applications to mix Java and HTML Code.
- These JSP's are translated by jsp interpreters in webservers into Java Source Code.
- The source code is then compiled that results in class files which are loaded and executed by a Java Virtual Machine.
- JSP files can be used to process browser requests directly.
- On subsequent calls only service method of the JSP class is called which makes processing more quicker.
- The files created for jsp has org.apache.jasper.runtime.HttpJspBase class which is a sub class of HttpServlet
- So all jsp files are converted to servlets.
- JSP is used for rendering dynamic web content.
- JSP has separated backend code from front end code.
- JSP is a server side scripting technology.
- JSP is abbreviation of Java Server Pages.
- JSP is based on servlet only.
- We can introduce Java code in JSP using tags
- Scripting tags are used to embed Java code within the JSP page. Three types are
- Scriptlet Tags
- Scriptlet tag Is used to embed Java code directly into the JSP page. It allows you to write Java statements, Perform computations and manipulate data within JSP.
- <% Java Code %>
- Expression tag
- Expression tag is used to evaluate an expression and directly output its result within the JSP page.
- <% =anExpressionTag %>
- Declaration Tag
- Declaration tag is used to define variables, methods and other declarations.
- <%! Variable declaration and method definition %>
- Directive Tag are used to provide instructions or directives To the JSP container On how to handle the JSP page During compilation and execution.
- <%@ directives %>
- Three types are
- Page directive
- <%@Page attribute=“value”>
- Include directive
- <%@Include file=“resource”>
- Taglib directive
- <%@taglib uri=“” prefix=“”>
- Comment Tag
- <% any text %>
- Action Tag Are used to perform specific specific actions or operations within the JSP page. action tags provide a way To interact with Java objects, control flow, and perform actions, forwarding, including other resources, And manipulating session attribute.
- <jsp !actionName />
- Action tags are of following types
- Include tags
- <jsp:include -/>
- Forward tags
- <jsp:forward -/>
- Bean Action tags
- <jsp:getproperty />
- <jsp:setproperty />
- <jsp: useBean />
- JSP can only accept HTTP requests
- Below is a specimen of Java file generated for a jsp file.
- JSP is executed in JSP container.
- JSP life cycle
- Translation
- JSP is converted to Servlet
- Compilation
- Servlet page Is converted to class
- Loading and instantiation
- Class file is loaded on server and object is created.
- Initialisation
- jspInit() Method is called.
- Request handling
- jspService() method is called.
- Destroy
- jspDestroy() method is called.
JSP file
<%@ page import="java.util.Date" %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
Date now = new Date();
out.println(now);
%>
</body>
</html>
/*
* Generated by the Jasper component of Apache Tomcat
* Version: Apache Tomcat/8.5.43
* Generated at: 2019-08-02 08:35:58 UTC
* Note: The last modified time of this file was set to
* the last modified time of the source file after
* generation to assist with modification tracking.
*/
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.Date;
public final class now_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent,
org.apache.jasper.runtime.JspSourceImports {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;
private static final java.util.Set<java.lang.String> _jspx_imports_packages;
private static final java.util.Set<java.lang.String> _jspx_imports_classes;
static {
_jspx_imports_packages = new java.util.HashSet<>();
_jspx_imports_packages.add("javax.servlet");
_jspx_imports_packages.add("javax.servlet.http");
_jspx_imports_packages.add("javax.servlet.jsp");
_jspx_imports_classes = new java.util.HashSet<>();
_jspx_imports_classes.add("java.util.Date");
}
private volatile javax.el.ExpressionFactory _el_expressionfactory;
private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
return _jspx_dependants;
}
public java.util.Set<java.lang.String> getPackageImports() {
return _jspx_imports_packages;
}
public java.util.Set<java.lang.String> getClassImports() {
return _jspx_imports_classes;
}
public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
if (_el_expressionfactory == null) {
synchronized (this) {
if (_el_expressionfactory == null) {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
}
}
}
return _el_expressionfactory;
}
public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
if (_jsp_instancemanager == null) {
synchronized (this) {
if (_jsp_instancemanager == null) {
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
}
}
return _jsp_instancemanager;
}
public void _jspInit() {
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("<html>\r\n");
out.write("\t<head>\r\n");
out.write("\t\t<title>Insert title here</title>\r\n");
out.write("\t</head>\r\n");
out.write("\t<body>\r\n");
out.write("\t\t");
Date now = new Date();
out.println(now);
out.write("\r\n");
out.write("\t</body>\r\n");
out.write("</html>");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
- To add a JSP to application and pass data to it via servlet we use the following code
<jsp:useBean id="message" scope="request" class="java.lang.String" />
<html>
<head>
<title>website</title>
</head>
<body>
<h1>Home</h1>
<p>
<%=message%>
</p>
</body>
</html>
Servlet File
package website.javaimplant.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
public class HomeServlet extends HttpServlet {
private Logger logger=Logger.getLogger(this.getClass());
private RequestDispatcher homeJsp;
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
homeJsp = context.getRequestDispatcher("/WEB-INF/jsp/home.jsp");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.println("<h1>Hello, World!</h1>");
BasicConfigurator.configure();
logger.debug("Returning website");
logger.debug("Returning message: bye");
req.setAttribute("message", "bye");
homeJsp.forward(req, resp);
}
}
- The usebean element in jsp attempts to locate an instance of java class with name message in Request Scope.
- It tries to find the associated value with key "message" in HttpServletRequest object.
- HttpServletRequest is an associative array which is called by terms map or dictionary.
- If usebean dosen't find the key message in request object then it creates an instance of java.lang.String which is specified in class attribute.
- We need to pass "message" key as shown in the Servlet request object which is passed as a parameter to RequestDispatcher.
- This pattern is called as MVC where views are segregated from the Business Logic in Servlets
- We create an instance of RequestDispatcher in our Servlet
- This encapsulates the jsp.
- This has a forward method.
- All JSP pages are converted into a class that extends HttpJspBase
- All declarations from declaration tag go directly as class variables.
- All the code in Scriptlet tag Goes in the _jspService() method.
- All the code In expression tag goes in _jspService() Method and is shown via out.println() method.
- Variables declared in Scriptlet tag are Local to _jspService().
- JSP implicit objects Are predefined variables That are available for use without any explicit declaration or initialisation.
- These objects are automatically created by the JSP container and provide access to Various functionalities and information related to the JSP page, Request, session, application and more.
- Nine implicit objects of JSP are as follows
- Out type of JSPWriter
- Request type of HttpServletRequest
- Response type of HttpServletResponse
- Session type of HttpSession
- Config type of ServletConfig
- Application type of ServletContext
- Page type of Object
- Exception type of Throwable
- Expression Language
- Expression Language(EL) is A simplified language that is used to access and manipulate data with JSP pages.
- It provides a convenient way to access the data stored in the objects Like request, session, application, Java Bean Component etc.
- Syntax is ${Expression}
- Some implicit objects in expression language are
- RequestScope
- Contains attributes that are specific to the current HTTP request.
- Param
- Param Provides Access to request parameter sent to the server
- ParamValues
- Provides access To request parameter values In an array.
- SessionScope
- Contains attributes that are specific to the current user session.
- PageContext
- Provides access to various objects and methods related to the JSP page context.
- PageScope
- Contains attributes that are specific to the current JSP page.
- ApplicationScope
- Contains attributes that are specific to entire web application.
No comments:
Post a Comment