Servlet API life cycle methods
init(): called when servlet is instantiated; must return before any other methods will be called
service(): method called directly by server when an HTTP request is received; default service() method calls doGet() (or related methods covered later)
destroy(): called when server shuts down
Server side programs can be written using different server-side technologies , such as Common Gateway Interface (CGI) , Active Server Pages (ASP) and Servlets.
CGI scripts are written in C , C++ or perl programming languages .
In case of an application server using CGI script to process client request , the server creates a separate instance of the CGI script to process the request.
As a result, the efficiency of the server is affected when there is large number of concurrent requests.
Server side programs can be written using different server-side technologies , such as Common Gateway Interface (CGI) , Active Server Pages (ASP) and Servlets.
CGI scripts are written in C , C++ or perl programming languages .
In case of an application server using CGI script to process client request , the server creates a separate instance of the CGI script to process the request.
As a result, the efficiency of the server is affected when there is large number of concurrent requests.
Servlet is java class which extends the functionality of web server by dynamically generating web pages.
Servlet technology is used to create Dynamic web application. Servlet technology is robust and scalable. init() and service() methods are more important in life cycle of a servlet. doGet() and doPost() are methods used under service() method.
Topics:servlet config, servlet filters,servlet context,session tracking
To know more about
Offer- http://mazenet-chennai.in/mazenet-offers.html
Syllabus- http://www.mazenet-chennai.in/java-training-in-chennai.html
Slide share: http://www.slideshare.net/mazenet_solution/presentations
For more events- http://mazenet-chennai.in/mazenet-events.html
Slide share- https://www.youtube.com/c/Mazenetsolution
Facebook- https://www.facebook.com/Mazenet.IT.Solution/
Twitter- https://twitter.com/Maze_net
Mail us : marketing@mazenetsolution.com
Contact: 9629728714
J2EE : Java servlet and its types, environmentjoearunraja2
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement, independent Web server providers offer some proprietary solutions in the form of APIs (Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one of the component APIs of Java Platform Enterprise Edition (nowadays known as – ‘Jakarta EE’) which sets standards for creating dynamic Web applications in Java.
Today we all are aware of the need to create dynamic web pages i.e. the ones that can change the site contents according to the time or can generate the content according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send a response back to the web server. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
Servlets, as written in Java, are platform independent.
Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance that handles all requests concurrently. This also saves the memory and allows a Servlet to easily manage the client state.
It is a server-side component, so Servlet inherits the security provided by the Web server.
The API designed for Java Servlet automatically acquires the advantages of the Java platforms such as platform-independent and portability. In addition, it obviously can use the wide range of APIs created on Java platforms such as JDBC to access the database.
Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are rather expensive, with the notable exception of Apache, which is free.
The Servlet Container
Servlet container, also known as Servlet engine, is an integrated set of objects that provide a run time environment for Java Servlet components. In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.
Services provided by the Servlet container:
Network Services: Loads a Servlet class. The loading may be from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.
Servlet is java class which extends the functionality of web server by dynamically generating web pages.
Servlet technology is used to create Dynamic web application. Servlet technology is robust and scalable. init() and service() methods are more important in life cycle of a servlet. doGet() and doPost() are methods used under service() method.
Topics:servlet config, servlet filters,servlet context,session tracking
To know more about
Offer- http://mazenet-chennai.in/mazenet-offers.html
Syllabus- http://www.mazenet-chennai.in/java-training-in-chennai.html
Slide share: http://www.slideshare.net/mazenet_solution/presentations
For more events- http://mazenet-chennai.in/mazenet-events.html
Slide share- https://www.youtube.com/c/Mazenetsolution
Facebook- https://www.facebook.com/Mazenet.IT.Solution/
Twitter- https://twitter.com/Maze_net
Mail us : marketing@mazenetsolution.com
Contact: 9629728714
J2EE : Java servlet and its types, environmentjoearunraja2
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement, independent Web server providers offer some proprietary solutions in the form of APIs (Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one of the component APIs of Java Platform Enterprise Edition (nowadays known as – ‘Jakarta EE’) which sets standards for creating dynamic Web applications in Java.
Today we all are aware of the need to create dynamic web pages i.e. the ones that can change the site contents according to the time or can generate the content according to the request received by the client. If you like coding in Java, then you will be happy to know that using Java there also exists a way to generate dynamic web pages and that way is Java Servlet. But before we move forward with our topic let’s first understand the need for server-side extensions.
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the web server, process the request, produce the response, and then send a response back to the web server. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every new request received.
Servlets, as written in Java, are platform independent.
Removes the overhead of creating a new process for each request as Servlet doesn’t run in a separate process. There is only a single instance that handles all requests concurrently. This also saves the memory and allows a Servlet to easily manage the client state.
It is a server-side component, so Servlet inherits the security provided by the Web server.
The API designed for Java Servlet automatically acquires the advantages of the Java platforms such as platform-independent and portability. In addition, it obviously can use the wide range of APIs created on Java platforms such as JDBC to access the database.
Many Web servers that are suitable for personal use or low-traffic websites are offered for free or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web servers are rather expensive, with the notable exception of Apache, which is free.
The Servlet Container
Servlet container, also known as Servlet engine, is an integrated set of objects that provide a run time environment for Java Servlet components. In simple words, it is a system that manages Java Servlet components on top of the Web server to handle the Web client requests.
Services provided by the Servlet container:
Network Services: Loads a Servlet class. The loading may be from a local file system, a remote file system or other network services. The Servlet container provides the network services over which the request and response are sent.
3.1 Identify the uses for and the interfaces (or classes) and methods to achieve the following features:
Servlet context init. Parameters
Servlet context listener
Servlet context attribute listener
Session attribute listeners
3.2 Identify the WebApp deployment descriptor element name that declares the following features:
Servlet context init. Parameters
Servlet context listener
Servlet context attribute listener
Session attribute listeners
1.1 For each of the HTTP methods,GET,POST, andPUT, identifythe corresponding method in the HttpServletclass.
1.3 For each of the following operations, identify the interfaceand method name that should be used:
Retrieve HTML form parameters from the request
Retrieve a servlet initialization parameter
Retrieve HTTP request header information
Set an HTTP response header
set the content type of the response
Acquire a text stream for the response
Acquire a binary stream for the response
Redirect an HTTP request to another URL
1.4 Identify the interface and method to access values and resources and to set object attributes within the following three web scopes:
Request
Session
Context
1.5 Given a life-cycle method: init,service , or destroy, identify correct statements bout its purpose or about how and when it is invoked.
1.6 Use a RequestDispatcher to include or forward to a web resource.
1.1 For each of the HTTP methods,GET,POST, andPUT, identifythe corresponding method in the HttpServletclass.
1.3 For each of the following operations, identify the interfaceand method name that should be used:
Retrieve HTML form parameters from the request
Retrieve a servlet initialization parameter
Retrieve HTTP request header information
Set an HTTP response header
set the content type of the response
Acquire a text stream for the response
Acquire a binary stream for the response
Redirect an HTTP request to another URL
1.4 Identify the interface and method to access values and resources and to set object attributes within the following three web scopes:
Request
Session
Context
1.5 Given a life-cycle method: init,service , or destroy, identify correct statements bout its purpose or about how and when it is invoked.
1.6 Use a RequestDispatcher to include or forward to a web resource.
POWER GENERATION OF THERMAL POWER PLANTsathish sak
. The kinetic energy of the molecules in a solid, liquid or gas
2. The more kinetic energy, the more thermal energy the object possesses
3. Physicists also call this the internal energy of an object
mathematics application fiels of engineeringsathish sak
MATHS IS HARD
MATHS IS BORING
MATHS HAS NOTHING TO DO WITH REAL LIFE
ALL MATHEMATICIANS ARE MAD!
BUT I CAN SHOW YOU THAT MATHS IS IMPORTANT IN
CRIME DETECTION MEDICINE FINDING LANDMINES
Plastic is a material consists of wide range of synthetic or organics that can be moulded into solid object with diverse shapes.
The word PLASTIC is derived from the Greek Word “PLASTIKOS” meaning capable of being shaped or moulded.
Plastics are organic polymers of higher molecular mass.
Radio frequency identification(RFID) technology using at various application by using radio frequency ranges.
It is especially used at tollgates. For automation of gate control.
It can also used at library systems.
Green Chemistry is the utilisation of a set of principles that reduces or eliminates the use or generation of hazardous substances in the design, manufacture and application of chemical products .
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Large Language Models and the End of ProgrammingMatt Welsh
Talk by Matt Welsh at Craft Conference 2024 on the impact that Large Language Models will have on the future of software development. In this talk, I discuss the ways in which LLMs will impact the software industry, from replacing human software developers with AI, to replacing conventional software with models that perform reasoning, computation, and problem-solving.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
A Comprehensive Look at Generative AI in Retail App Testing.pdfkalichargn70th171
Traditional software testing methods are being challenged in retail, where customer expectations and technological advancements continually shape the landscape. Enter generative AI—a transformative subset of artificial intelligence technologies poised to revolutionize software testing.
A Comprehensive Look at Generative AI in Retail App Testing.pdf
SERVIET
1.
2. Life Cycle of Servlet
init(ServletConfig);
service(ServletRequest,
ServletResponse);
destroy();
servlet
GenericServlet HttpServlet
doGet(HttpServletRequest,
HttpServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
…….
3. 3
Servlet Life Cycle
• Servlet API life cycle methods
– init(): called when servlet is instantiated; must
return before any other methods will be called
– service(): method called directly by server
when an HTTP request is received; default
service() method calls doGet() (or related
methods covered later)
– destroy(): called when server shuts down
6. The Servlet API
• javax.servlet
– Basic servlet API definitions.
– What are the inputs and outputs to/from Servlet
– Not tied to any specific protocol (e.g., HTTP)
– These low-level classes/interfaces usually are not used
• javax.servlet.http
– HTTP-related definitions
– Extension of the basic interfaces to handle the HTTP
protocol functionality
– This package will be heavily used
7. Servlet classes
• GenericServlet class
– implements Servlet
– also implements Serializable, ServletConfig
– implements all Servlet methods
• HttpServlet class
– extends the GenericServlet class
– provides a framework for handling the HTTP protocol
– has its own subclasses of ServletRequest and
ServletResponse that do HTTP things
8. HttpServlet methods
• HTTPServlet class provides helper methods for
handling HTTP requests
– doGet (GET and HEAD)
– doPost (POST)
– doPut, doDelete (rare)
– doTrace, doOptions (not overridden)
• The service() method dispatches the requests to the
appropriate do* methods
9. Generic Servlet vs. HTTP Servlet
GenericServlet
service ( )Server
Client
HTTPServlet
service ( )HTTP
Server
Browser
request
response
doGet ( )
doPost ( )
request
response
10. ServletRequest class
• Encapsulates the clientserver communication
• Allows the Servlet access to
– Names of the parameters passed in by the client
– The protocol being used by the client
– The names of the remote host that made the request
and the server that received it
– The input stream, ServletInputStream, through which
the servlet gets data from clients
• Subclasses of ServletRequest allow the servlet to
retrieve more protocol-specific data
– HttpServletRequest for accessing HTTP-specific header
information
11. ServletRequest - Client Info
• getRemoteAddr()
– Returns the IP address of the client that sent the request
• getRemoteHost()
– Returns the fully qualified host name of the client that sent
the request
• getProtocol()
– Returns the protocol and version of the request as a string
<protocol>/<major version>.<minor version>.
12. ServletRequest - URL Info
• getScheme()
– Returns the scheme of the URL used in this request, for
example "http", "https", or "ftp".
• getServerName()
– Returns the host name of the server receiving the request
• getServerPort()
– Returns the port number on which this request was
received
• getServletPath()
– Returns the URL path that got to this script, e.g.
“/servlet/com.foo.MyServlet”
– Useful for putting in a <FORM> tag
13. ServletRequest - Contents
• getContentLength()
– Returns the size of the request data
• getContentType()
– Returns the MIME type of the request data
• getInputStream()
– Returns an input stream for reading binary data in the
request body.
• getReader()
– Returns a buffered reader for reading the request body.
14. ServletRequest - Parameters
• String getParameter(String)
– Returns a string containing one value of the specified
parameter, or null if the parameter does not exist.
• String[] getParameterValues(String)
– Returns the values of the specified parameter as an
array of strings, or null if the named parameter does not
exist.
– Useful for parameters with multiple values, like lists
• Enumeration getParameterNames()
– Returns the parameter names as an enumeration of
strings, or an empty enumeration if there are no
parameters or the input stream is empty.
15. ServletResponse class
• Encapsulates the serverclient communication
– Gives the servlet methods for replying to the client
– Allows the servlet to set the content length and MIME
type of the reply
– Provides an output stream, ServletOutputStream
through which the servlet can send the reply data
• Subclasses of ServletResponse give the servlet
more protocol-specific capabilities.
– HttpServletResponse for manipulating HTTP-specific
header information
16. ServletResponse
• Embodies the response
• Basic use:
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<HTML><BODY>Hello</BODY></HTML>");
• setContentType() is usually called before calling
getWriter() or getOutputStream()
17. ServletResponse - Output
• getWriter()
– for writing text data
• getOutputStream()
– for writing binary data
– or for writing multipart MIME
• And many other methods, similarly to the methods of
ServletRequest
• Refer the documentation
18. import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServWelcome extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>First Servlet Program</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
}
Servlet Example Servlets are not part of the standard SDK,
they are part of the J2EE
Servlets normally extend HttpServlet
Details of the HTTP request from the client
The response to be sent to the client
Set the response type to text/html (this is
normal)
This HTML text is
sent to the client
Do not forget to close the
connection with the client
19. Servlet Architecture Overview
• Servlet Interface
– methods to manage servlet
• GenericServlet
– implements Servlet
• HttpServlet
– extends GenericServlet
– exposes HTTP-specific
functionality
Servlet
extends
doGet()
doPost()
service()
...
Override one or more of:
doGet()
doPost()
service()
...
Clas
s
Interface
Class
Class
Clas
s
extendsHttpServlet
implements
GenericServlet
UserServlet
20. REQUEST METHODS
• GET- This method gets the resource at the requested
URL.
• POST- Asks the server to accept the body info attached. It
is like GET request with extra info sent with the request.
• HEAD- Asks for only the header part with no body.
• PUT- Says to put the body at the requested URL
• DELETE- Says to delete the resource at the requested URL.
• OPTIONS- Asks for a list of the HTTP methods to which
the thing at the request URL can respond.
• TRACE-Asks for the loopback of the request message
21. DIFFERENCE BETWEEN GET AND POST
GET:
• GET/test/demo_form.jsp?name1=value1&name2=value2
HTTP/1.1
• In GET method the data is exposed in the URL and only a limited
amount of data is sent. Because the data is sent in the URL.
POST:
• POST/test/demo_form.jsp HTTP/1.1
• In POST method the data is not exposed in the URL and large
amount of data is sent. Because the data is sent in the body.
22. SESSION TRACKING
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in
servlet.
• It is used to recognize the particular user.
23. SESSION TRACKING TECHNIQUE
• There are four techniques used in Session
tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
24. COOKIES
• A cookie is a small piece of information that is
persisted(client-side) between the multiple client requests.
• There are two types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
• javax.servlet.http.Cookie class provides the functionality
of using cookies
25. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletRespon
se response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating cookie object
Cookie ck=new Cookie("uname",n);
26. //adding cookie in the response
response.addCookie(ck);
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);} }}
27. SERVLET2
public class SecondServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletRespon
se response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}}}
28. • In this example,We are storing the name of the
user in the cookie object and accessing it in
another servlet.
• As we know well that session corresponds to
the particular user.
• So if you access it from too many browsers
with different values, you will get the different
value.
29. HIDDENFIELD
• Hidden Form Field a hidden (invisible)
textfield for maintaining the state of user.
• We store the information in the hidden field
and get it from another servlet.
• To store value in hidden field
<input type="hidden" name="uname"
value=“Java">
30. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
31. //creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname'
value='"+n+"'>");
out.print("<input type='submit' value='go'>")
out.print("</form>");
out.close();
}
catch(Exception e)
{System.out.println(e);}}}
32. SERVLET2
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
/ /Getting the value from the hidden field
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);} } }
33. URL REWRITING
• Append a token or identifier to the URL of the next Servlet or the next
resource.
• Parameter name/value pairs can be sent using the following format:
url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&).
34. EXAMPLE
SERVLET1
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResp
onse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
35. //appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} }
SERVLET2
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServl
etResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
36. //getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e)
{
System.out.println(e);}
}
}
37. HTTP SESSION
• Container creates a session id for each user.
• The container uses this id to identify the
particular user.
• An object of HttpSession can be used to
perform two tasks:
1. bind objects
2. view and manipulate information about a session,
such as the session identifier, creation time, and last
accessed time.
38. EXAMPLE
SERVLET1
public void doGet(HttpServletRequest request, HttpServletRespo
nse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
42. What is Tomcat?
• Tomcat is a Servlet container (Web server that
interacts with Servlets)
• Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
• Tomcat is an open-source, non commercial project
– Licensed under the Apache Software License
• Tomcat is written in Java (OS independent)
43. A Servlet Example
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html><head><title>Hello</title></head>");
out.println("<body>");
out.println("<h2>" + new java.util.Date() + "</h2>");
out.println("<h1>Hello World</h1></body></html>");
}
} HelloWorld.java
http://localhost/dbi/hello
44. A JSP Example
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2><%= new java.util.Date() %></h2>
<h1>Hello World</h1>
</body>
</html> hello.jsp
http://localhost/dbi/hello.jsp
45. Tomcat Directory Structure
Tomcat-Home
bin common
Tomcat-Base
webapps work
lib classesROOT myApp1 myApp2server.xml
WEB-INF
lib classesweb.xml
server sharedlogsconf
lib classes
46. Installing Tomcat
• Create a directory for tomcat base
– For example: mkdir ~/tomcat-base
• Set the environment variable CATALINA_BASE to
your tomcat-base directory
– For example: setenv CATALINA_BASE ~/tomcat-base
– Insert this line into your .cshrc file
• Run ~dbi/tomcat/bin/setup
• $CATALINA_BASE is now a regular Tomcat base
directory, and Tomcat is ready to run
47. Running Tomcat
• To start tomcat use ~dbi/tomcat/bin/catalina run
• Or, in background, ~dbi/tomcat/bin/catalina start
• To stop tomcat use ~dbi/tomcat/bin/catalina stop
• To see the default page of Tomcat from your browser
use the URL http://<machine-name>:<port>/
– machine-name is the name of the machine on which Tomcat
runs and port is the port you chose for Tomcat
• You can also use http://localhost:<port>/ if your
browser runs on the same machine as Tomcat
48.
49. Choosing a port for Tomcat
• In the file $CATALINA_HOME/conf/server.xml you
will find the element Connector of Service
“Catalina”
• Choose a port (greater than 1024) and change the
value of the port attribute to your chosen one:
<Server>
…
<Service name="Catalina”>
<Connector port="8090"/>
…
</Service>
…
</Server>
51. JDBC
What is JDBC
• The java Database Connectivity(JDBC)API is the industry standard for
database independent connectivity between the java programming
language and wide range of database.
• Java API is used to connect and execute query to the database. JDBC API
uses jdbc drivers to connects to the database.
52. Why JDBC & What is API
Why we use JDBC?
• Before JDBC, ODBC API was used to connect and execute query to the
database.
• But ODBC API uses ODBC driver that is written in C language which is
platform dependent and unsecured.
• That is why Sun Microsystem has defined its own API (JDBC API) that uses
JDBC driver written in Java language.
53. API
What is API
• API (Application programming interface) is a document that contains
description of all the features of a product or software.
• It represents classes and interfaces that software programs can follow to
communicate with each other.
• An API can be created for applications, libraries, operating systems, etc
55. JDBC Drivers
JDBC Driver is a software component that enables java application to interact
with the database.There are 4 types of JDBC drivers:
• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)
56. JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC
function calls. This is now discouraged because of thin driver.
57. Native-API driver
• The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API. It
is not written entirely in java.
58. Network Protocol driver
• The Network Protocol driver uses middleware (application server) that
converts JDBC calls directly or indirectly into the vendor-specific database
protocol. It is fully written in java.
59. Thin driver
• The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully written
in Java language.
60. RDBMS
• MySQL
• Driver Name : com.mysql.jdbc.Driver
• URL Format : jdbc:mysql://hostname/ databaseName
• ORACLE
• Driver Name : oracle.jdbc.driver.OracleDriver
• URL Format : jdbc:oracle:thin:@hostname:port Number:databaseName
61. 5 Steps to connect to the database in java
• Register the driver class
• Create the connection object
• Create the Statement object
• Execute the query
• Close the connection object
62. Register the driver class
• The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
Syntax of forName() method
• public static void forName(String className)throws
ClassNotFoundException
• Example to register the OracleDriver class
• Class.forName("oracle.jdbc.driver.OracleDriver");
63. Create the connection object
• The getConnection() method of DriverManager class is used to establish connection with the
database.
• Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password) throws S
QLException.
Example to establish connection with the Oracle database
• Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
64. Create the Statement object
• The createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with
the database.
Syntax of createStatement() method
• public Statement createStatement()throws SQLException
Example to create the statement object
• Statement stmt=con.createStatement();
65. Execute the query
• The executeQuery() method of Statement interface is used to execute queries
to the database. This method returns the object of ResultSet that can be used
to get all the records of a table.
Syntax of executeQuery() method
• public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next()){
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }
66. Close the connection object
• By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close
the connection.
Syntax of close() method
• public void close()throws SQLException
Example to close connection
• con.close();
67. Statement, Prepared Statement, Callable
Statement
• Statement
• Use for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. The Statement interface cannot
accept parameters.
• Prepared Statement
• Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
• Callable Statement
• Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
68. Example to Connect Java Application with
mysql database
• import java.sql.*;
• class MysqlCon{
• public static void main(String args[]){ try{
• Class.forName("com.mysql.jdbc.Driver");
• Connection con=DriverManager.getConnection(
• "jdbc:mysql://localhost:3306/sonoo","root","root");
• //here sonoo is database name, root is username and password
• Statement stmt=con.createStatement();
• ResultSet rs=stmt.executeQuery("select * from emp");
90. Example
• SQLException
• String sql= "insert into
RegistrationTable(Name,EmailId,Gender,Address,Contact,BikeName,Passw
ord)values(?,?,?,?,?,?, )";
• //java.sql.SQLException: Parameter index out of range (7 > number of
parameters, which is 6).
• ClassNotFoundException.
• public class ClassNotFoundExceptionExample {
• private static final String CLASS_TO_LOAD = "main.java.Utils";
92. • Verify that the name of the class is correct and that the
appropriate .jar file exists in your classpath. If not, you must explicitly add
it to your application’s classpath.