banner



Can I Jump To Learn Hiberante And Spring Without Learning Jsp And Servlets

In the recent trends, a billion bytes of data is generated on a day-to-24-hour interval ground. Most of u.s.a. believe in the misconception that all of the web applications are created over spider web frameworks similar HTML, PHP, JavaScript etc. But, did you know, spider web applications can be based on Java using services like Servlets and JSP? In this Servlet and JSP Tutorial, allow'southward delve deep into the technology and sympathise how it is useful for creating a web application.

Beneath is the listing of topics that I will be covering in this Servlet and JSP tutorial

    • Servlet
      • Web & HTTP
      • Introduction to Servlets
      • Servlet Life Bicycle
      • Steps to Create Servlets
      • Session Tracking
      • Cookies
    • JSP
      • Introduction to JSP
      • JSP vs Servlets
      • JSP Scripting Elements
      • JSP Request and Response

You may also go through this recording of  Servlet and JSP Tutorial where you tin can sympathize the topics in a detailed manner with examples.

Servlet Tutorial | JSP Tutorial | Advanced Java Tutorial | Edureka

This Edureka tutorial on "Servlet and JSP tutorial" will talk the central concepts of servlets and JSP, its life cycle and various steps to create Servlet and Java Server Pages.

Servlet and JSP Tutorial: Web & HTTP

Spider web is a system ofCyberspaceservers that supports formatted documents. The documents are formatted using a markup language chosen HTML (HyperText Markup Language) that supports links to other documents like graphics, sound, and video files etc.

Servlet and JSP Tutorial: Web & HTTPNow that we know what is spider web,  let'due south motion farther and empathize what is a website. So, a website is a collection of static files i.eastward. web pages like HTML pages, images, graphics etc. And,the Web awarding is a website with dynamic functionality on the server.Google,Facebook,Twitter  are examples of web applications.

So, what is the link between the Web and HTTP? Permit's at present find out.

HTTP (Hypertext Transfer Protocol)

HTTP is used by clients and servers to communicate on the web. It is considered asa stateless protocol considering it supports merely one request per connexion. With HTTP the clients connect to the server to ship one asking and then disconnect. And this mechanism allows more users to connect to a given server over a menstruation of time. Hither, the client sends an HTTP asking and the server answers with an HTML page to the client, using HTTP.

That was all about HTTP and Web. Now let'south dive deep into Servlets and sympathize its working mechanism.

Introduction to Servlets

Servlet is a server-side Java program module that handles client requests and implements theservlet interface. Servlets can respond to any type of request, and they are commonly used to extend the applications hosted past web servers.

Servlets-Introduction to Java Servlets - EdurekaIn this figure yous can run into, a client sends a request to the server and the server generates the response, analyses it and sends the response dorsum to the client.

At present, let's jump into the side by side concept and understand Servlet Life Bicycle.

Servlet Life Cycle

The entire life cycle of a servlet is managed by theServlet container which uses thejavax.servlet.Servlet interface to empathize the Servlet object and manage it.

 Servlet Life Cycle: The Servlet life cycle mainly goes through four stages:

Servlet Life Cycle-Servlet and JSP tutorial- Edureka

  • Loading a Servlet

When a server starts up, the servlet container deploy and loads all the servlets.

  • Initializing the Servlet

Side by side, a servlet is initialized by calling the init() method.Servlet.init()method is called past the Servlet container to notify that this Servlet instance is instantiated successfully and is about to put into service.

  • Request handling

Then, servlet callsservice()method to process a client'southward request and is invoked to inform the Servlet about the client requests.

  • Destroying the servlet

Finally, a servlet is terminated past calling thedestroy(). The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.

init() and destroy() methods are called only once. Finally, a servlet is garbage nerveless past the garbage collector of the JVM. And then this concludes the life bicycle of a servlet. At present, permit me guide you through the steps of creating Java servlets.

 Servlet and JSP Tutorial: Steps to Create Servlet

In order to create a servlet, we need to follow a few steps in social club. They are as follows:

  1. Create a directory structure
  2. Create a Servlet
  3. Compile the Servlet
  4. Add together mappings to the web.xml file
  5. Start the server and deploy the project
  6. Access the servlet

Now, based on the to a higher place steps, let'south create a program to empathise ameliorate, how a servlet works.

To run a servlet programme, we should have Apache Tomcat Server installed and configured.Eclipse for Java EE provides in-built Apache Tomcat. Once the server is configured, you can commencement with your program. Ane important betoken to note – for any servlet programme, you need 3 files –index.html file, Java class file, and web.xml file. The very showtime pace is to create a Dynamic Web Project and and then proceed further.

Now, let's take an case where I volition be creating a elementary login servlet and display the output in the browser.

Commencement,  I will create alphabetize.html file

<!DOCTYPE html> <html> <torso>  <grade activeness="Login" method="mail service">  <table>  <tr>  <td>Name:</td>   <td><input type="text" name="userName"></td>  </tr>   <tr>  <td>Password:</td>   <td><input type="countersign" proper noun="userPassword"></td>  </tr>  </table>  <input type="submit" value="Login"> </form>  </body> </html>        

Next, let'southward lawmaking the Java Class file.

package Edureka; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse; public class Login extends HttpServlet { protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException PrintWriter prisoner of war=res.getWriter(); res.setContentType("text/html"); String user=req.getParameter("userName"); String pass=req.getParameter("userPassword"); pw.println("Login Success...!") if(user.equals("edureka") && pass.equals("edureka")) pw.println("Login Success...!"); else pw.println("Login Failed...!"); pw.close(); } }        

In the higher up code, I take prepare a condition – if username and password are equal to edureka,  only and so it will brandish successfully logged in, else login will exist denied. After writing the Java course file, the last stride is to add mappings to the web.xml file. Let's see how to practise that.

Theweb.xml file volition be nowadays in the WEB-INF binder of your web content. If information technology is not nowadays, then you can click on Deployment Descriptor and click onGenerate Deployment Descriptor Stub.In one case you get your web.xml file ready, yous need to add the mappings to it. Let'south see how mapping is done using the below example:

<?xml version="1.0"encoding="UTF-8"?> <web-app xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-example">http://www.w3.org/2001/XMLSchema-instance</a>" xmlns="<a href="http://xmlns.jcp.org/xml/ns/javaee">http://xmlns.jcp.org/xml/ns/javaee</a>"xsi:schemaLocation="<a href="http://xmlns.jcp.org/xml/ns/javaee">http://xmlns.jcp.org/xml/ns/javaee</a> <a href="http://xmlns.jcp.org/xml/ns/javaee/spider web-app_3_1.xsd">http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd</a>"version="three.1"> <display-proper name>LoginServlet</display-name> <servlet> <servlet-proper name>Login</servlet-name> <servlet-class>Edureka.Login</servlet-form> </servlet> <servlet-mapping> <servlet-name>Login</servlet-proper name> <url-pattern>/Login</url-pattern> </servlet-mapping> <welcome-file-listing> <welcome-file>alphabetize.html</welcome-file> </welcome-file-list> </spider web-app>        

So, this is how a servlet is created and configured. Let's at present see what a Generic servlet is and how is information technology created.

Generic Servlets

It is a protocol-independent servlet that should override the service() method to handle the customer asking. The service() method accepts two arguments,ServletRequest object, and ServletResponse object. Work of request object is to inform the servlet about the request made by the customer while the response object returns a response back to the client. GenericServlet is anabstract grade and information technology has only one abstract method, which isservice(). That's the whole concept when nosotros create a Generic Servletpast extending the GenericServlet course, we must override the service() method.

At present, let's encounter how to create and invoke a Generic servlet. Again I volition code three files as shown beneath:

 HTML file

Nosotros are creating an HTML file that volition call the servlet once we click on the link on the web page. Create this file in the WebContent binder. The path of this file should look like this: WebContent/alphabetize.html

<html> <championship>Generic Servlet Demo</title> </caput> <body> <a href="welcome">Click hither to call Generic Servlet</a> </trunk> </html>        

Java Course file

Hither we will be creating a Generic Servlet by extending GenericServlet course. When creating a GenericServlet, you must override the service() method. Right click on thesrc folder and create a new class file and name the file every bit generic. The file path should look like this: Java Resouces/src/default bundle/generic.coffee

packet EdurekaGeneric; import coffee.io.*; importjavax.servlet.*; public grade generic extends GenericServlet{ public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{ res.setContentType("text/html"); PrintWriter pwriter=res.getWriter(); pwriter.print("<html>"); pwriter.print("<torso>"); pwriter.impress(" <h2>Generic Servlet Instance</h2>  "); pwriter.print("Welcome to Edureka YouTube Aqueduct"); pwriter.print("</body>"); pwriter.impress("</html>"); } }        

 web.xml
This file can be institute at this path WebContent/Web-INF/spider web.xml. In this file, we volition map the Servlet with the specific URL. Since we are calling the welcome page upon clicking the link onindex.html, information technology volition map the welcome page to the Servlet form that we take already created above.

<servlet> <servlet-name>MyGenericServlet</servlet-name> <servlet-class>EdurekaGeneric.generic</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyGenericServlet</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping>        

After this, beginning your Tomcat Server and run the servlet. You will get the desired output. And then this was all nigh Generic Servlets. Now allow'south move further and sympathise the concept of session tracking.

Servlet and JSP Tutorial: Session Tracking

Sessiononly ways a particular interval of time. Session trackingis a technique to maintain state (data) of a user also known equallysession direction in servlet. So, each time user requests to the server, the server treats the request every bit the new request.

Below figure depicts how each request from the client is considered as a new request.
Session Tracking - Advanced Java Tutorial - Edureka

In order to recognize the detail user, nosotros need session tracking. At present permit's move further and see one of the techniques of session tracking i.e. Cookies.

Servlet and JSP Tutorial: Cookies

Acookie is a small piece of information that is persisted between the multiple customer requests. A cookie has a name, a single value, and optional attributes such as a annotate, path and domain qualifiers, a maximum historic period, and a version number.

How Does Cookie Piece of work?

Every bit it is a technique of Session tracking, by default, each request is considered every bit a new request.

Cookie - Servlet and JSP Tutorial-EdurekaIn this, we add together a cookie with the response from the servlet. So the cookie is stored in the enshroud of the browser. Subsequently that, if a request is sent past the user, a cookie is added with the request by default.

Now equally yous have understood how cookie works, permit meet a small instance illustrating the utilize of cookies.

Permit's see an case of creating a cookie, adding the response and retrieving the results. Here I volition be writing ii java form files i.e MyServlet1 and MyServlet2.

File: MyServlet1

package Edureka; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/login") public class MyServlet1 extends HttpServlet{ public void doGet(HttpServletRequest request,&nbsp; HttpServletResponse response) { try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = asking.getParameter("userPassword"); pwriter.print("Hello here:"+name); pwriter.print(" Your Countersign is: "+password); //Creating ii cookies Cookie c1=new Cookie("userName",proper noun); Cookie c2=new Cookie("userPassword",countersign); //Adding the cookies to response header response.addCookie(c1); response.addCookie(c2); pwriter.print(" <a href='welcomehere'>View Details</a>"); pwriter.close(); }catch(Exception exp){ Organisation.out.println(exp); } } }        

File: MyServlet2

package Edureka; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet("/welcomehere") public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ attempt{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); //Reading cookies Cookie[] c=request.getCookies(); //Displaying User name value from cookie pwriter.impress("Name here: "+c[0].getValue()); pwriter.print("Password: "+c[1].getValue()); //pwriter.print(" <a href='welcome'>View Details</a>"); pwriter.close(); }take hold of(Exception exp){ System.out.println(exp); } } }        

Now, permit's create a simple HTML grade for cookies.

<!DOCTYPE html> <html> <body> <body>  <form action="login"> User Proper name:<input type="text" name="userName"/> Password:<input type="password" name="userPassword"/> <input type="submit" value="submit"/> </form>  </body> </html>        

Now, the concluding step is to create XML file and add all the mappings to it.

<servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>Edureka.MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>Edureka.MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcomehere</url-pattern> </servlet-mapping>        

Now you are all set for execution. You tin run the code and get the desired output. This is how a cookie works. So that was all almost Servlets. If you ish to learn Advance Java in depth, you tin can refer to this Advanced Java Tutorial. Now that yous have gained some insights on Servlets, let's move ahead and understand what is Java Server Pages.

Servlet and JSP Tutorial: Java Server Pages

JSP or Java Server Pages is a technology that is used to create spider web application simply similar Servlet technology. It is an extension to Servlet – as it provides more functionality than a servlet such as expression language, JSTL, etc. A JSP folio consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development.

At present, as we know what JSP is, allow's compare JSP with Servlets and understand which is best suitable for the web.

Servlet and JSP Tutorial: Advantages of JSP Over Servlets

JSP Servlets
Extension to Servlet Not an extension to servlet
Easy to Maintain Bit complicated
No need to recompile or redeploy The lawmaking needs to be recompiled
Less code than a servlet More than code compared to JSP

I hope you understood the difference between JSP and Servlets. Now, let'southward move further and empathize Scripting elements.

Servlet and JSP Tutorial: JSP Scripting Elements

The scripting elements provide the power to insert java lawmaking inside the JSP. At that place are iii types of scripting elements:

  • scriptlet tag–  A scriptlet tag is used to execute Coffee source lawmaking in JSP.
                  Syntax : <%  coffee source lawmaking %>            

In this example, nosotros have created two files index.html and welcome.jsp. The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message. Now, allow's look at the code.

File: alphabetize.html

<html> <body> <form&nbsp;action="welcome.jsp"> <input&nbsp;type="text"&nbsp;name="uname"> <input&nbsp;blazon="submit"&nbsp;value="go"> </form>  </body> </html>        

File: welcome.jsp

<html> <body> <% String&nbsp;name=asking.getParameter("uname"); print("welcome&nbsp;"+name); %> </form>  </body> </html>        
  • expression tag– The code placed withinJSP expression tagiswritten to the output stream of the response. Then you need not write out.impress() to write information. It is mainly used to print the values of variable or method.
                  Syntax : <%=  statement %>            

Now let'due south take a small example of displaying the current time.  To display the current time, nosotros have used the getTime() method of Calendar form. The getTime() is an instance method of Calendar class, so we take called it afterwards getting the instance of Calendar class by the getInstance() method.

File: index.jsp

<html> <body> Electric current&nbsp;Time:&nbsp;<%=&nbsp;java.util.Calendar.getInstance().getTime()&nbsp;%> </torso> </html>        
  • declaration tag– The JSP announcement tag is usedto declare fields and methods. The code written inside the JSP declaration tag is placed exterior the service() method of an auto-generated servlet. So it doesn't get retention at each request.
                  Syntax: <%!  field or method declaration %>            

In the below example of JSP annunciation tag, we are defining the method which returns the cube of a given number and calling this method from the JSP expression tag. But we can also use JSP scriptlet tag to call the declared method. Let'southward see how.
File: alphabetize.jsp

<html> <body> <%! int&nbsp;cube(int&nbsp;due north){ return&nbsp;due north*n*due north*; } %> <%=&nbsp;"Cube&nbsp;of&nbsp;iii&nbsp;is:"+cube(three)&nbsp;%> </body> </html>        

Then, this is all about JSP Scripting Elements.  Now permit'due south move ahead and run into request and response objects of JSP.

Servlet and JSP Tutorial: JSP Request and Response Objects

JSP request is an implicit object of blazon HttpServletRequest that is created for each JSP asking by the web container. It tin be used to become asking information such as a parameter, header data, remote address, server name, server port, content type, grapheme encoding etc. It can also be used to prepare, get and remove attributes from the JSP request scope.

Allow's see the simple example of request implicit object where nosotros are printing the proper noun of the user with a welcome message. Allow's see how.

Example of JSP request implicit object

File: index.html

<form&nbsp;action="welcome.jsp"> <input&nbsp;blazon="text"&nbsp;name="uname"> <input&nbsp;blazon="submit"&nbsp;value="go"> </form>        

File: welcome.jsp

<% String&nbsp;proper noun=request.getParameter("uname"); impress("welcome&nbsp;"+name); %>        

JSP response implicit object

In JSP, the response is an implicit object of type HttpServletResponse. The instance of HttpServletResponse is created past the web container for each JSP request. Information technology can exist used to add or manipulate responses such as redirect response to another resources, transport error etc.

Allow'south encounter the instance of response implicit object where nosotros are redirecting the response to Google.

Instance of response implicit object

File: index.html

<form&nbsp;action="welcome.jsp"> <input&nbsp;blazon="text"&nbsp;proper name="uname"> <input type="submit"&nbsp;value="get"> </form>        

File: welcome.jsp

<% sendRedirect("http://www.google.com"); %>        

And so, this is how asking and response objects work. This brings to the end of Servlet and JSP tutorial article. I hope this web log was informative and added value to your knowledge.

Check out theJava Certification Grooming by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread beyond the globe. Edureka'due south Java J2EE and SOA training and certification class is designed for students and professionals who want to exist a Java Developer. The course is designed to give you a caput start into Coffee programming and train yous for both core and advanced Coffee concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this "Java Servlet" blog and nosotros volition get dorsum to you as shortly equally possible.

Can I Jump To Learn Hiberante And Spring Without Learning Jsp And Servlets,

Source: https://www.edureka.co/blog/servlet-and-jsp-tutorial/

Posted by: smithupyrairow.blogspot.com

0 Response to "Can I Jump To Learn Hiberante And Spring Without Learning Jsp And Servlets"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel