Docsity

Advanced Java Notes: Generics, Collections, Lambda Expressions, JSP & JavaBeans, Study notes of Java Programming

Toggle sidebar
bg1
Unit: Introduction to Java EE Programming and JSP
Part A: Java EE and JSP Architecture
1. What is Java EE? Explain its features and importance.
Java EE (Java Platform, Enterprise Edition) is a set of specifications and APIs
built on top of Java SE for developing large-scale, distributed, multi-tier,
secure enterprise applications. It gives a standard runtime plus ready-made
services (transactions, security, messaging, persistence), so the developer
writes only business logic.
Features of Java EE
Multi-tier architecture: client, web, business and database layers are
kept separate.
Component based: Servlets, JSP, JSF (web) and EJB (business) are
reusable components.
Container services: the container manages life cycle, threads, security,
transactions and pooling for the components.
Web services support: JAX-RS (REST) and JAX-WS (SOAP).
Persistence: JPA maps Java objects to database tables (ORM).
Transaction management: JTA gives ACID transactions across many
resources.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a

Partial preview of the text

Download Advanced Java Notes: Generics, Collections, Lambda Expressions, JSP & JavaBeans and more Study notes Java Programming in PDF only on Docsity!

Unit: Introduction to Java EE Programming and JSP Part A: Java EE and JSP Architecture

  1. What is Java EE? Explain its features and importance. Java EE (Java Platform, Enterprise Edition) is a set of specifications and APIs built on top of Java SE for developing large-scale, distributed, multi-tier, secure enterprise applications. It gives a standard runtime plus ready-made services (transactions, security, messaging, persistence), so the developer writes only business logic. Features of Java EEMulti-tier architecture: client, web, business and database layers are kept separate.  Component based: Servlets, JSP, JSF (web) and EJB (business) are reusable components.  Container services: the container manages life cycle, threads, security, transactions and pooling for the components.  Web services support: JAX-RS (REST) and JAX-WS (SOAP).  Persistence: JPA maps Java objects to database tables (ORM).  Transaction management: JTA gives ACID transactions across many resources.

Messaging: JMS for asynchronous communication between applications.  Security: authentication and authorization with JAAS , role based access.  Dependency injection: CDI and annotations reduce boilerplate and XML.  Scalability and high availability: clustering and load balancing support.  Portability: a standard, vendor neutral platform. The app moves between servers.  Database connectivity: JDBC and connection pooling. Importance of Java EE  Faster development: the server supplies common services, so less code is written.  Reliable for big systems: banking, insurance, e-commerce and government systems use it.  Scalable: supports thousands of users at the same time through clustering.  Secure: built-in authentication, authorization and encryption support.  Standardised: one specification, many vendors. No vendor lock-in.  Easy maintenance: separate tiers can be changed without breaking the others.  Strong ecosystem: Spring and Hibernate build on the same ideas, and the skill is in demand for jobs.

  1. Define JSP (JavaServer Pages). Explain its advantages. JSP (JavaServer Pages) , now called Jakarta Server Pages , is a server-side web technology that lets us write HTML with Java code embedded in it to create dynamic web pages. A JSP file ( .jsp ) is converted into a Servlet by the web container (like Tomcat) and then executed to send HTML back to the browser. Advantages of JSP  Easy to learn and write: it looks like normal HTML, so web designers can understand it.  Separates presentation from logic: design stays in the JSP, business logic goes in beans and servlets (MVC).  Less code than Servlets: no need for out.println() on every HTML line.  Automatic compilation: the container compiles and reloads a changed page by itself.

Explanation of the stepsRequest: the browser sends an HTTP request for a .jsp page. The web server passes it to the JSP container (engine).  Translation: the translator parses the page and converts it into Servlet source code. HTML becomes out.write() statements and Java code is copied as it is.  Compilation: the compiler turns that source into a .class file (byte code).  Loading and initialization: the class loader loads the servlet class, the container creates its object and calls jspInit() once.  Execution: for every request _jspService() runs. It can use implicit objects , call JavaBeans and read or write the database through JDBC.  Response: the generated HTML goes back through the web server to the browser. The client never sees the Java code. Components of the architecture Component Role Client (browser) Sends the request, displays the HTML Web server Receives the HTTP request, hands JSP pages to the container JSP engine / container Translates, compiles and runs JSP (Jasper in Tomcat) Translator Converts JSP into Servlet source Compiler Converts Servlet source into a class file Servlet instance Handles each request in _jspService() JavaBeans / DB Business logic and data storage

  1. Explain the life cycle of a JSP page. The life cycle of a JSP page is the series of phases it goes through, from the moment it is first requested until the container removes it. The web container controls all the phases. Phases explainedTranslation: the container checks the JSP syntax and converts the page into a Servlet source file, for example index_jsp.java.  Compilation: the generated Java file is compiled into a .class file. Compile errors show up here.  Class loading: the class loader loads the compiled servlet class into memory.  Instantiation: the container creates one instance of the servlet class.  Initialization: the container calls jspInit() once. It is used to open database connections or read settings.  Request processing: for every request the container calls _jspService(request, response). This method contains the page's HTML and Java code and creates the response.  Destruction: when the page is removed or the server stops, the container calls jspDestroy() once to release resources. Example: Overriding the methods

1. Directives Directives give instructions to the container about the whole page. They are processed at translation time. Syntax: **<%@ directive attribute="value" %>

  1. Scripting elements** They let us write Java code inside the page.

3. Actions Actions are XML-style tags that perform a task at request time, such as including a page or using a bean.  **** includes another page at run time.  **** passes the request to another page.  **** creates or finds a JavaBean.  **** and **** set or read bean properties.  **** sends a parameter with include or forward. 4. CommentsJSP comment: <%-- note --%> is removed on the server. The client never sees it.  **HTML comment: ** is sent to the browser and shows in view source. 5. Implicit objects These 9 objects are created by the container and can be used without declaring them.

Java Code style Java code with HTML inside out.println() HTML code with Java inside tags Ease of use Harder, more code to write Easier, much less code Best suited for Business and control logic Presentation of data (the view) Role in MVC Controller View Compilation Compiled manually by the developer Translated and compiled automatically by the container Changes Recompile and redeploy, sometimes restart Edit and save, the page reloads by itself Request method doGet() , doPost() , service() _jspService() (generated) Implicit objects Not available, must be created in code Available: request, response, session, out and more Tags, EL, JSTL Not supported Supported, which reduces Java code Session handling Get it with request.getSession() session object is ready by default Mapping and access Mapped with web.xml or @WebServlet Opened directly by its file URL First request Fast, already compiled Slower once, because of translation and compilation Who can work on it Java programmers Web designers and developers together Maintenance HTML changes need Java code changes Layout changes are easy and separate from logic Servlet public class HelloServlet extends HttpServlet {

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Hello, "

  • req.getParameter("name") + ""); } } JSP Hello, <%= request.getParameter("name") %>

Part B: JSP Scripting Tags and Implicit Objects

  1. Explain the different JSP scripting tags. Scripting tags (scripting elements) let us write Java code inside a JSP page. There are three types: Scriptlet , Expression and Declaration. A fourth, the comment tag, is often listed along with them. 1. Scriptlet tag Syntax: <% Java statements; %>  Holds any number of Java statements: variables, loops, conditions, method calls.  Each statement must end with a semicolon.  The code is placed inside the _jspService() method, so it runs for every request.  Variables declared here are local to that method. <% int marks = 72; if (marks >= 40) { out.println("Result: Pass"); } %> 2. Expression tag Syntax: <%= expression %>

out.print(visits); } }

  1. What is a JSP Declaration tag? Give an example. The Declaration tag is a JSP scripting element used to declare variables and methods that belong to the class level of the servlet generated from the JSP page. Syntax <%! declaration; [declaration; ...] %> Features  Starts with <%! and ends with %>. Note the exclamation mark.  Each declaration ends with a semicolon.  The code is placed outside the _jspService() method, directly inside the servlet class.  Variables become instance variables. Their value is kept between requests and shared by all users.  Methods declared here can be called from scriptlets and expressions.  It runs once , when the servlet object is created, not on each request.  It does not produce output by itself. Use an expression to display a value.  Used to define jspInit() and jspDestroy(). Example: variable and method <%@ page language="java" contentType="text/html" %>
&lt;%! // Declaration tag int visitCount = 0; int square(int n) { return n * n; } %&gt; &lt;% visitCount++; %&gt; &lt;%-- Scriptlet --%&gt; Page visited: &lt;%= visitCount %&gt; times Square of 6 is: &lt;%= square(6) %&gt;

Example 2: using jspInit() <%! String appName; public void jspInit() { appName = "Student Portal"; // runs once at start } %> Welcome to <%= appName %>

  1. What is a JSP Scriptlet tag? Give an example. The Scriptlet tag is a JSP scripting element used to write any number of Java statements inside a JSP page. The code is copied into the _jspService() method of the generated servlet and runs on every request. Syntax <% Java statement; Java statement; ... %> Features  Can hold variables, conditions, loops, method calls, try-catch and other Java statements.  Every statement must end with a semicolon.  Variables declared inside are local to _jspService(). A new copy is made for each request.  Can use all implicit objects : request , response , out , session and more.  Does not print anything by itself. Use out.println() or an expression tag < %= %> for output.  Cannot define methods. Use the declaration tag for that.  HTML and scriptlets can be mixed, so one Java block can be split around HTML. Example: simple scriptlet
&lt;% int marks = 72; String result; if (marks &gt;= 40) {

Example

Sum of 10 and 20 = <%= 10 + 20 %>

Is 15 greater than 9? <%= 15 > 9 %>

Upper case: <%= "jsp".toUpperCase() %>

Current date: <%= new java.util.Date() %>

Example 2 <% String name = request.getParameter("name"); int price = 250, qty = 3; %> Hello, <%= name %>

Total bill: Rs. <%= price * qty %>

<%-- inside an attribute --%>
  1. What are implicit objects in JSP? Explain any five. Implicit objects are predefined Java objects that the JSP container creates automatically for every JSP page. We can use them directly in scriptlets and expressions without declaring or creating them. They are available inside the _jspService() method.

Five objects explained

1. request Type: javax.servlet.http.HttpServletRequest (jakarta.* in newer versions)  Holds everything the client sent : form data, query string, headers, cookies.  Lives for one request only.  Common methods: getParameter() , getParameterValues() , getHeader() , getMethod() , setAttribute(). <% String user = request.getParameter("username"); %> Welcome, <%= user %> 2. response Type: javax.servlet.http.HttpServletResponse  Represents the reply sent back to the client.  Used to set content type, add cookies and headers, and redirect.  Common methods: setContentType() , sendRedirect() , addCookie() , setHeader(). <% response.sendRedirect("home.jsp"); %> 3. out Type: javax.servlet.jsp.JspWriter

1. requestType: HttpServletRequestPurpose: carries all data sent by the client to the server: form fields, URL parameters, headers, cookies.  Scope: request. It exists for one request only, and a new one is made for the next. <%-- login.html sends: username, password --%> <% String user = request.getParameter("username"); String method = request.getMethod(); %>

User: <%= user %> (sent by <%= method %>)

**2. response**  **Type: HttpServletResponse**  **Purpose:** controls the reply sent back to the browser: content type, headers, cookies, redirection, status codes.  **Scope: page**. <%

String user = request.getParameter("username"); if ("admin".equals(user)) { response.sendRedirect("dashboard.jsp"); } else { response.sendRedirect("login.html"); } %>

3. sessionType: HttpSessionPurpose: keeps data about one user over many requests, such as login status or a shopping cart. HTTP itself is stateless, so the session fills that gap.  Scope: session. It lasts until timeout (default about 30 minutes) or until invalidate().  Each user gets a separate session, identified by a session ID (cookie JSESSIONID ). <%-- page1.jsp --%> <% session.setAttribute("user", "Yukta"); %> <%-- page2.jsp, a later request --%> <% String u = (String) session.getAttribute("user"); %> Welcome back, <%= u %> <%-- logout.jsp --%> <% session.invalidate(); %> 4. applicationType: ServletContext