Adv Java #2 - Servlets Introduction: - by Raghu Sir (Sathya Technologies, Ameerpet, Hyderabad)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

ADV JAVA #2 . SERVLETS INTRODUCTION


1. What is a web application ?
A web application a collection of Web pages (Resources).
2. What is a Resource?
A Resource can be HTML Page, servlet, JSP, CSS, Java Script, PDF, Excel, Image,
Audio, Video, ..etc (any type of file)
3. What are the different types of web pages?
Two types : a. Static web page b. Dynamic web page
4. What is static web page?
A Web page has fixed (non-change) content always is known as static web page.
5. How to implement static web page?
By using HTML (Hyper Text Markup Language) we can create static Web pages
6. What is a dynamic web page ?
A web page content varies/changes every time is known as dynamic web page.
7. How to implement Dynamic web page?
By using Servlet API we can create dynamic web pages.
8. What is client ? give examples ?
A System has Client software like Google Chrome and which makes a request to
access one service.
9. What is server ? give examples ?
A System has server software like Apache Tomcat and that runs one application and
gives service to client.
10. Which language can client(browser) understand?
HTML (in case of web browser client)
11. Which language can server understand?
Programming Languages like JAVA , C#.net, PHP..etc
12. Who will write code ?
13. Who will compile the files?
14. What is request meaning?
15. Who will make request?
16. What is response means?
17. Who will give response?
18. For one application how many servers required?
19. How many clients can communicate to one server?
20. What is API?
API (Application Programming Interface) it is a collection of packages that contains
class, interface, enum, annotation, error and exception.
21. What is Servlets?
Servlets is an API given by Sun Microsystems, used to develop web applications using
Java Language.
22. Give API details of servlets?
package#1 : javax.servlet
a.Interfaces:
Servlet
ServletRequest

1|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

ServletResponse
ServletConfig
ServletContext
Filter
FilterChain
FilterConfig
RequestDispatcher
b.Classes:
GenericServlet
ServletContextEvent
ServletOutputStream
c.Exceptions:
ServletException
UnavailableException

package#2 : javax.servlet.http
a.Interfaces:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
b.Class:
Cookie
HttpServlet

package#3 : javax.servlet.annotation
a.Annotations
@WebServlet
@WebInitParam
@WebFilter
@WebListener

23. How many ways we can create dynamic web page using servlets?
By using Servlets API we can create web pages in 3 Ways.
Those are
a. By implementing ‘Servlet’ interface (javax.servlet package)
b. By extending ‘GenericServlet’ abstract class (javax.servlet package)
c. By extending ‘HttpServlet’ abstract class (javax.servlet.http package)
24. What is the default output of a servlet?
25. What is Deployment descriptor?
Web.xml files is called as Deployment Descriptor.
26. Why web.xml ?
This is input file to Web server. It contains Servlet class name, object name, URL,
..etc. Simple web.xml format looks like
<web-app>
<servlet>
<servlet-name> anyName </servlet-name>
<servlet-class> FullClassName </servlet-class>
</servlet>

2|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

<servlet-mapping>
<servlet-name> anyName </servlet-name>
<url-pattern> URL of servlet </url-pattern>
</servlet-mapping>
</web-app>
27. Explain <servlet> tag in web.xml?
28. Explain <servlet-mapping> tag in web.xml?
29. Can we write servlets without using web.xml?
Yes, Possible. Use @WebServlet(“/URL”)
30. Why servlet should have URL? Who can access this?
Browser (client) cannot understand Java code (like Class, object Name..etc)
So, browser can access/read Servlet using its URL.
31. How many life cycle methods in Servlets ?
There are 3 Life Cycle methods in Servlet which are called by Server.
a. init (..) called only once after creating object
b. service(..) called for every request
c. destroy() called only once before destroying object
32. What is the role/work of Web Server in java/servlets ?
A server will,
a. Load servlet class
b. Creates object using default constructor
c. Calls init(..) one time
d. Calls service(..) for every request
e. Calls destroy() at the end of server (before stopping server)
33. Which life cycle methods are called only once?
34. Which life cycle method is called for every request?
35. What is the difference between System.out.println and out.println() of PrintWriter?
System.out.println() prints message on console
Out.println() of PrintWriter prints message one web page (browser)

Exercise # Valid-Invalid statements


1. Servlets can be used to develop both static and dynamic web pages.
2. Servlets contains only one life cycle method
3. init() method is the first life cycle method execute only once
4. service() method called only once.
5. destroy() method must be called by programmer
6. Browser makes Request
7. Request means asking resources to server
8. Response is given by both server and client.
9. HTML is executed by web browsers.
10. Servlets are executed by Servers
11. Writing web.xml is optional in new servlets API (3.0)
12. Servlets objects are created by servers
13. Servers uses default constructor to create object
14. Service method contains two parameters
15. Servlet must be compiled by programmer/Eclipse not by servers
16. Servlets objects created and destroyed by servers only.

3|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

17. Browser doesn’t understand Programming language(like Java)


18. URL (or URL Pattern) is case sensitive?
19. HTML is case-sensitive
20. Servlets code(java code) is case-sensitive.
21. Every servlet class is web page by default.
22. @WebServlet(“/url”) is used to avoid web.xml coding.
23. Annotations are executed faster than xml coding
24. Annotations are easy to write compared in xml code.
25. Web.xml is input is server
26. out.println() prints data on webpage
27. System.out.println() prints data on console.

Exercise# Fill in the blanks


1. _____ is an interface used to create Webpage in Servlets API
2. ___________ and _________ are abstract classes used to web pages
3. __________ method is called for every request
4. ___________ and ________ methods are called only once by server
5. Servlets must be compiled by ___________
6. __________ file is called as Deployment descriptor
7. __________ tag in web.xml used to created object
8. __________ tag in web.xml is used to provide URL for a servlet
9. ___________ annotation is used to avoid web.xml for Servlet class
10. For ___________ request servlet object is created.
11. Static web pages are implemented using _______
12. HTML stands for ___________
13. Servlets API is given by ___________
14. API stands for ___________
15. Package can have ________________________________________
16. __________ method is called at the end/stopping server.
17. Generic Servlet is _________________
18. _____________________________ are packages given by Servlets API

Exercise# Match the following


1. HTML (__) a. Pre-Defined/Read made code
2. Servlets (__) b. Abstract class
3. service() method (__) c. Static web pages
4. API (__) d. Deployment Descriptor
5. Request (__) e. Dynamic Web pages
6. Response (__) f. To avoid web.xml configuration
7. GenericServlet (__) g. Called for every request
8. Web.xml (__) h. Called only once for servlet
9. @WebServlet (__) i. Resource given by server
10. inti(), destroy() (__) j. URL/ made by client

4|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

Exercise# Find Output / Errors


1. WelcomeServlet.java
package org.sathyatech;
//ctrl+shift+O
public class WelcomeServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
out.println("<p>Welcome to Sathyatechnologies</p>");
out.println("</body>");
out.println("</html>");
}
}
2. LoopServlet.java
package org.sathyatech;
//ctrl+shift+O
public class LoopServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
for(int i=0;i<4;i++) {
out.println("<p> WELCOME TO RAGHU SIR CLASS</p>");
}
out.println("</body>");
out.println("</html>");
}
}
3. MarksServlet.java
package org.sathyatech;
//ctrl+shift+O
public class MarksServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();

out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
int sub1=90; int sub2=80; int sub3=70;
int total=sub1+sub2+sub3;
out.println("<b>Raghu Total Marks : " +total +" </b>");

5|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

double avg=total/3;
out.println("<u>Raghu Average is :" + avg +"</u>") ;
out.println("</body>");
out.println("</html>");
}
}

4. BillServlet.java
package org.sathyatech;
//ctrl+shift+O
public class BillServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");

String itemCode = "PEN";


double itemCost = 500.65;
double gst = itemCost * 12 / 100.0;
double discount = itemCost * 3 /100.0;
double finalAmount = itemCost + gst - discount;

out.println("<b> Item Code is :" + itemCode + "</b>");


out.println("<b> Item Cost is :" + itemCost + "</b>");
out.println("<b> GST amount is :" + gst + "</b>");
out.println("<b> Discount given is :" + discount + "</b>");
out.println("<b> Final bill is :" + finalAmount + "</b>");

out.println("</body>");
out.println("</html>");

}
}
5. ScrollMessageServlet.java
package org.sathayetch;
//ctrl+shift+O
public class ScrollMessageServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");

6|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

out.println("<h1> RAGHU SIR CLASS </h1>");


out.println("<marquee> Welcome to Java Batch </marquee>");
out.println("</body>");
out.println("</html>");

}
}
6. ColorCodeServlet.java
package com.app;
//ctrl+shift+O
public class ColorCodeServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
String color="BLUE";
switch (color) {
case "RED": out.println("REG IS BLOOD"); break;
case "GREEN": out.println("GREEN IS FOOD"); break;
case "WHITE": out.println("WHITE IS PEACE"); break;
default: out.println("CHOOSE ONE COLOR"); break;
}
out.println("</body>");
out.println("</html>");

}
}
7. DateServlet.java
package org.sathyatech;
//ctrl+shift+O
public class DateServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
java.util.Date dte=new java.util.Date();
System.out.println(dte);
out.println("<p> Now, Date and Time is: " + dte + "</p>");
out.println("</body>");
out.println("</html>");
}
}

7|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

8. RandomNumberServlet.java
package com.app;
//ctrl+shift+O
public class RandomNumberServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
java.util.Random random = new java.util.Random();
random.nextInt(10);
out.println("</h3> Random Number is : " + random + "</h3>");
out.println("</body>");
out.println("</html>");
}
}
9. StringOperationsServlet.java
package org.sathyatech;
//ctrl+shift+O
public class StringOperationsServlet extends GenericServlet{

@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");

String message="Java By Raghu Sir!";


out.println("<b> " + message + "</b>");
out.println("<b> " + message.toLowerCase() + "</b>");
out.println("<b> " + message.toUpperCase() + "</b>");
out.println("<b> " + message.length() + "</b>");
out.println("<b> " + message.substring(4) + "</b>");
out.println("<b> " + message.contains("RAGHU") + "</b>");
out.println("<b> " + message.startsWith("Java") + "</b>");
out.println("<b> " + message.endsWith("RAGHU") + "</b>");
out.println("<b> " + message.concat(" Super Class ") + "</b>");
out.println("<b> " + message.charAt(1) + "</b>");

out.println("</body>");
out.println("</html>");

}
}

8|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

10. ResultServlet.java
package com.app;
//ctrl+shift+O
public class SampleServlet extends GenericServlet{
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head> </head>");
out.println("<body>");
int marks[] = {85,65,98,68,90};
int total =0;
for (int i = 0; i < marks.length; i++) {
total = total + marks[i];
}
out.println("<p> Total marks :" + total +"</p>");
double avg = total / marks.length;
out.println("<p> Average is :" + avg +"</p>");

out.println("</body>");
out.println("</html>");

}
}

Exercise#: Write Servlet code with web.xml configuration


1. Write a servlet “HomePage” using URL ‘/home’ that prints Welcome to Servlets using
<h1> tag.
2. Write a servlet “MessagePage” using URL ‘/inbox’ that prints HTML Paragraph
Welcome to SathayTech. This is Adv Java Batch. Raghu sir is taking this batch.
3. Write a Sevlet “QuotePage” using URL ‘/quote’ that prints
Subject + Practice = Normal Great JOB. ALL THE BEST.
2 3

a +b + 2ab = (a+b) . H O means water.


2 2 2
2

4. Write a servlet “DatePage” using URL “/dates’ that prints the current system date
and time using <b> and <marquee> tag.
5. Write a servlet “SathyaPage” using URL ‘/sathya’ that prints “WELCOME TO RAGHU
SIR CLASS” 10 times.
6. Write a servlet “CalculationPage” using URL ‘/calculate’ with below instructions
Create two int variables x,y with values. Print Addition, subtraction, division and
multiplication result in webpage.

7. Write a servlet ‘StudentDataPage’ using URL ‘/students’ that prints HTML table in
below format

9|Page
- by RAGHU SIR [ SATHYA TECHNOLOGIES, AMEERPET, HYDERABAD]

Sl.no Name Course

1 RAGHU Adv Java

2 KANNA Spring

3 SUBBA REDDY Spring boot

4 SAM Core Java

5 SALMAN KHAN Microservice

8. Write a sevlet ‘EmployeePage’ using URL ‘/employee’ that prints HTML Order List
Welcome to Employees
I. RAM (BA)
II. SAM (DEV)
III. KHAN (QA)
IV. AJAY (BA)
V. RAGHU(TL)
9. Write a Servlet “FriendsPage” using URL ‘/friends’ that prints HTML Unordered List
Welcome to Friends Page
• Ajay Kumar
• RAGHU SA
• SHIVA
• VANI
• SUBBU
• KANNA

10. Write a Servlet “RegisterPage” using URL “/register” that prints HTML Form like
Student ID (Text Input)
Student Name (Text Input)
Gender (Radio buttons)
Course (DropDown with values Core Java, Adv Java, Spring, Boot)
Address (TextArea)
Timings interested (checkbox [ ] Morning [ ] Afternoon [ ] Evening )
Submit Button with Text ‘Place Enquiry’

11. Write a Servlet ‘LoginPage’ using URL ‘/login’ that prints HTML login page like
Welcome to Login Page
User Name : Text Input
Password : Password input
Login (submit Button)
FB: https://www.facebook.com/groups/thejavatemple/

EMAIL : [email protected]

10 | P a g e

You might also like