0% found this document useful (0 votes)
7 views

Unit4 Java

The document provides an overview of Java servlets and Java Server Pages (JSP), detailing their functionalities, lifecycle methods, and how they handle HTTP requests and responses. It explains key concepts such as handling parameters, sessions, and cookies, along with examples of servlet and JSP code. Additionally, it covers JSP tags, control statements, and methods for generating dynamic content within web applications.

Uploaded by

begamgulshan30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit4 Java

The document provides an overview of Java servlets and Java Server Pages (JSP), detailing their functionalities, lifecycle methods, and how they handle HTTP requests and responses. It explains key concepts such as handling parameters, sessions, and cookies, along with examples of servlet and JSP code. Additionally, it covers JSP tags, control statements, and methods for generating dynamic content within web applications.

Uploaded by

begamgulshan30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Servlet

• A Java servlet is a server-side program that is called by the user interface


or another J2EE component and contains the business logic to process a
request.
• A Java servlet is a Java class that reads requests sent from a client and
responds by sending information to the client.
• The Java class must extend Httpservlet and override the Httpservlet's
doGet() and/ or doPost() methods.
• Both the doGet() and doPost() methods require two arguments. The first
argument is an HttpservletRequest object and the other argument is an
HttpservletResponse object.
• The HttpservletRequest object contains incoming information and the
HttpservletResponse object is used to send outgoing information to the
client.
• Both methods throw a servletException and IOException
A Simple Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html"); // Set response content type
// Get the output stream to write the response
PrintWriter out = response.getWriter();
// Write the HTML response
out.println("<html><body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body></html>");
}
• The setContentType() method is used to set the value for the ContentType
HTTP header information.
• ContentType identifies the type of document that is being sent explicitly.
• Outgoing data is sent by using a PrintWriter object using the println()
method and is forwarded to the client that made the request.
Life cycle
• A Java servlet consists of at least four methods, each of which is called
during the life cycle of the Java servlet. These methods are init(), service(),
the appropriate request method, and destroy().
• The init() method is called automatically when the Java servlet is created.
The init() method is used to initialize variables and objects that are used
throughout the Java servlet.
• The init() method doesn't require an argument, returns a void, and throws
a servletException.
• The service() method is called whenever a request for the Java servlet
is made to the web server.
• The service() method examines the HTTP request type and then calls
the appropriate request method such as doGet() and doPost().
• The destroy() method is the last method to be called right before the
Java servlet terminates, such as when an instance of a Java servlet is
removed from memory.
• We can use the destroy() method with statements that release
resources, such as closing a database connection.
Reading Servlet parameters
• Data sent by a client is read into a Java servlet by calling the
getParameter() method of the HttpservletRequest object.
• The getParameter() method requires one argument, which is the
name of the parameter that contains the data sent by the client.
• The getParameter() method returns a String object. The String object
contains the value of the parameter, if the client assigns a value to the
parameter. An empty String object is returned if the client didn't
assign a value to the parameter.
• We can read a set of parameters that have the same name by calling
the getParameterValues() method.
• The getParameterValues() method has one argument, which is the
name of the parameter, and returns an array of String objects.
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ParamServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
String name = request.getParameter("name"); // Get parameters from the URL
String age = request.getParameter("age");
response.setContentType("text/html"); // Set content type
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello, " + name + "</h1>");
out.println("<h2>Your age is: " + age + "</h2>");
out.println("</body></html>");
}
When an HTML form is used to send data to the servlet, the parameters
are passed in the HTTP request body. The servlet can access these
parameters using the same getParameter() method.
<!DOCTYPE html>
<html>
<body>
<form action="ParamServlet" method="GET">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
HttpServlet
• Handling HTTP requests and responses is a fundamental part of servlet
programming.
• The HttpServlet class has two primary methods you will work with for
handling HTTP requests:
• doGet(HttpServletRequest request, HttpServletResponse response):
This method handles HTTP GET requests.
• doPost(HttpServletRequest request, HttpServletResponse response):
This method handles HTTP POST requests.
HttpServletRequest
• The HttpServletRequest object represents the HTTP request sent by
the client.
• It contains all the information about the request, such as parameters,
headers, cookies, and more.
Methods:
getParameter(String name): Retrieves the value of a form parameter.
getHeader(String name): Retrieves a header value sent by the client.
getCookies(): Returns all cookies sent by the client.
getSession(): Returns the HTTP session associated with the request.
HttpServletResponse
• The HttpServletResponse object represents the response that the
servlet sends back to the client.
• We can set the response status, headers, content type, and write
content to the response body.
Methods:
setStatus(int statusCode): Sets the status code of the HTTP response
(e.g., 200, 404).
setContentType(String type): Sets the content type of the response
(e.g., text/html, application/xml).
getWriter(): Returns a PrintWriter object to write the response content.
sendRedirect(String location): Redirects the client to another URL.
Java Server Page
• A Java Server Page is a server-side program that is similar in design and
functionality to a servlet.
• A JSP is simpler to create than a servlet because a JSP is written in HTML
rather than with the Java.
• There are three methods that are automatically called. These are the
jsplnit(), jspDestroy(), and service() method.
• The jsplnit() method is identical the init() method in a servlet. It is used to
initialize objects and variables that are used throughout the life of the JSP.
• The jspDestroy() method is identical to the destroy() method in a servlet.
Itis automatically called when the JSP terminates normally. It is used for
cleanup the resources, such as disconnecting a database.
• The service() method is automatically called and retrieves a connection to
HTTP.
JSP Tags
• A JSP program consists of a combination of HTML tags and JSP tags.
• JSP tags are used to embed Java code into HTML pages in a way that
allows dynamic content generation on web pages.
1. Directive Tags
• These tags provide global information about the JSP page. They are used
for setting the page configuration, including imports and other
parameters.
<%@ page %> - This tag is used to define page attributes such as content
type, language, and error handling.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
%>
2. Action Tags - These tags are used to invoke server-side actions like
including other resources, forwarding requests, or redirecting to different
pages.
jsp:forward: Forwards the request to another resource.
<jsp:forward page="nextPage.jsp" />
3. Scripting Tags - These tags allow embedding Java code within the JSP. It
allows you to insert Java code between the opening <% and closing %>
delimiters.
<%
String message = "Hello, World!";
out.println(message);
%>
4. Expression tag - An expression tag opens with <%= and closes with %> .
It directly outputs the result of a Java expression.
<%= "Hello, " + userName %>
5. Declaration statement tags - A declaration statement tag opens with <
%! and is followed by a Java declaration statement(s) that define variables,
objects, and methods.
<%!
public String getGreeting() {
return "Hello from the method!";
}
%>
Variables and Objects
• We can declare Java variables and objects that are used in a JSP program
by using the same coding technique as used to declare them in Java.
• Variables can be declared directly in the JSP page using scriptlets tags.
Variables are typically of int, String etc.
<%! int age=29; %>
<P> Your age is: <%=age%> </P>

You can create objects in JSP using scriptlets


// Declaring an object of String class
<% String message = new String("Welcome to JSP!"); %>
<h1>Message: <%= message %></h1>
Methods
• Methods can be used in JSP pages to encapsulate specific functionality and
improve code reusability.
• The method is declared like in regular Java code. But the Java code in scriptlets
should be placed within <% %> tags.
<%
// Method definition inside the scriptlet
public String greetUser(String name) {
return "Hello, " + name + "!";
}
// Calling the method
String message = greetUser("John");
out.println(message);
%>
Control Statements
• Control statements are used to manage the flow of content
dynamically.
• We can use control statements like if, else, and else if inside JSP
scriptlets to control the flow based on some conditions.
<%
int age = 25;
if (age >= 18) {
out.println("You are eligible to vote.");
}
%>
<%
int day = 3;
switch(day) {
case 1:
out.println("Monday");
break;
case 2:
out.println("Tuesday");
break;
case 3:
out.println("Wednesday");
break;
default:
out.println("Invalid day");
}
%>
Loops
• Loops allow you to repeat certain blocks of code based on a condition, making it easier to generate
dynamic content.JSP supports several looping statements like for, while, and do-while to iterate
over data.
For - A for loop is commonly used when you know in advance how many times you need to iterate
<%
for (int i = 1; i <= 5; i++) { Do-While - A do-while loop ensures that the
out.println("Number: " + i + "<br>"); block of code runs at least once before
} checking the condition.
%> <%
int i = 1;
While - A while loop runs as long as the condition is true. do {
It's useful when the number of iterations is not known in advance.
out.println("Number: " + i + "<br>");
<% i++;
int i = 1; } while (i <= 5);
%>
while (i <= 5) {
out.println("Number: " + i + "<br>");
i++;
}
%>
RequestString
• We can retrieve query parameters sent in an HTTP request using the
request object.
• The request.getParameter() method is typically used to fetch data from
the request string (i.e., URL parameters or form data sent via GET or
POST).
• We can retrieve the values of name and age in MyPage.jsp.
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
%>
<p>Name: <%= name %></p>
<p>Age: <%= age %></p>
The HTML form ( MyPage.html) that sends data via POST to your JSP
page.
<form action="MyPage.jsp" method="POST">
Name: <input type="text" name="name" /><br>
Age: <input type="text" name="age" /><br>
<input type="submit" value="Submit" />
</form>
Sessions
• Sessions are used to store user-specific data that can be accessed across
multiple requests.
• This is useful for scenarios like tracking user login status, storing user
preferences, or keeping track of shopping cart items.
• The session is tracked using a unique session ID by calling a getId() method.
<% String sessionId = session.getId(); %>
Storing data in a Session - The data can be stored in a Session using
setAttribute() method.
<%
session.setAttribute("username", "Arvind");
session.setAttribute("userAge", 20);
%>
Retrieving Data from the Session - The stored data in a Session is
retrieved using a getAttribute() method.
<%
String username = (String) session.getAttribute("username");
Integer userAge = (Integer) session.getAttribute("userAge");
out.println("Username: " + username);
out.println("Age: " + userAge);
%>
Cookies
• Cookies are used to store small pieces of data on the client's browser.
• Cookies are useful for maintaining state across multiple requests, such as
remembering user preferences, login credentials, or other information between
sessions.
Creating a Cookie - JSP cookies can be created using a Cookie class.
Cookie(String name, String value): This constructor creates a new cookie with a
name and a value.
<% Cookie myCookie = new Cookie("cookieName", "cookieValue"); %>
<% Cookie userCookie = new Cookie("username", "Raja"); %>
Methods
getName(): Gets the name of the cookie.
<% userCookie.getName(); %>
getValue(): Gets the value of the cookie.
<% userCookie.getValue(); %>
Storing a cookie - response.addCookie(Cookie cookie) - This method
adds the cookie to the HTTP response, so it will be stored in the
client's browser.
<% response.addCookie(userCookie); %>
Reading a Cookie - Cookies can be read in JSP using the
request.getCookies() method, which returns an array of Cookie
objects.
<% Cookie[] userCookie= request.getCookies();
for (Cookie c : userCookie) {
String cname = c.getName();
String cvalue = c.getValue();
out.println("CookieName: " + cname);
out.println("CookieValue: " + cvalue);
%>

You might also like