JSP and Java Servlets

Discussion in 'JSP' started by pradeep, Oct 17, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    JSP

    JSP stands for Java Server Pages. JSP is a server-side technology Java Server Pages are an extension to the Java Servlet technology that was developed by Sun.

    JSPs have dynamic scripting capability that works in tandem with HTML code, separating the page logic from the static elements -- the actual design and display of the page -- to help make the HTML more functional (i.e. dynamic database queries).

    JSPs are not restricted to any specific platform or server. It was originally created as an alternative to Microsoft's ASPs (Active Server Pages). Recently, however, Microsoft has countered JSP technology with its own ASP.NET, part of the .NET initiative.

    Java Servlets

    Servlets are Java technology's answer to CGI programming. A JSP is translated into Java servlet before being run and it processes HTTP requests and generates responses like any servlet. However, JSP technology provides a more convenient way to code a servlet. Translation occurs the first time the application is run. A JSP translator is triggered by the .jsp file name extension in a URL. JSPs are fully interoperable with servlets. You can include output from a servlet or forward the output to a servlet and a servlet can include output from a JSP or forward output to a JSP.

    They are programs that run on a Web server and build Web pages. Building Web pages on the fly is useful (and commonly done) for a number of reasons:

    The Web page is based on data submitted by the user. For example the results pages from search engines are generated this way and programs that process orders for e-commerce sites do this as well.

    The data changes frequently. For example, a weather-report or news headlines page might build the page dynamically, perhaps returning a previously built page if it is still up to date.

    The Web page uses information from corporate databases or other such sources. For example, you would use this for making a Web page at an on-line store that lists current prices and number of items in stock.

    Advantage of Servlets Over CGI

    Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. More importantly, servlet developers get paid more than Perl programmers.

    Efficient

    With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.

    Convenient

    Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.

    Powerful

    Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.

    Portable

    Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.

    Inexpensive

    There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.

    What is JSP?

    Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly static, with the dynamic part limited to a few small locations. But most CGI variations, including servlets, make you generate the entire page via your program, even though most of it is always the same. JSP lets you create the two parts separately. Here's an example:
    Code:
     <html>
     Welcome to Our Store<head>
     <body>
     <h1>Welcome to Our Store
     <small>Welcome,
     <!-- User name is "New User" for first-time visitors -->
     <% out.println(Utils.getUserNameFromCookie(request)); %>
     To access your account settings, click
     <a href="account-settings.html">here.
     <p>Regular HTML for all the rest of the on-line store's Web page.
     </body>
    Advantages of JSP

    Over Active Server Pages (ASP)


    ASP is a similar technology from Microsoft. The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual Basic or other MS-specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers.

    Over Pure Servlets

    JSP doesn't give you anything that you couldn't in principle do with a servlet. But it is more convenient to write and to modify regular HTML than to have a zillion println statements that generate the HTML. Plus, by separating the look from the content you can put different people on different tasks: your Web page design experts can build the HTML, leaving places for your servlet programmers to insert the dynamic content.

    Over Server-Side Includes (SSI)

    SSI is a widely-supported technology for including externally-defined pieces into a static Web page. JSP is better because it lets you use servlets instead of a separate program to generate that dynamic part. Besides, SSI is really only intended for simple inclusions, not for "real" programs that use form data, make database connections, and the like.

    Over JavaScript

    JavaScript can generate HTML dynamically on the client. This is a useful capability, but only handles situations where the dynamic information is based on the client's environment. With the exception of cookies, HTTP and form submission data is not available to JavaScript. And, since it runs on the client, JavaScript can't access server-side resources like databases, catalogs, pricing information, and the like.

    Over Static HTML

    Regular HTML, of course, cannot contain dynamic information. JSP is so easy and convenient that it is quite feasible to augment HTML pages that only benefit marginally by the insertion of small amounts of dynamic data. Previously, the cost of using dynamic data would preclude its use in all but the most valuable instances.
     
  2. hasmukh

    hasmukh New Member

    Joined:
    Jul 31, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    Bandhu i used to develop web page using ASP and ASP.net , then i decided to dirty my hands with JSP and believe me ..... Its just toughest thing to do . May be i selected wrong book to start with .

    Suggest a good book for JSP

    I am using java server pages in 24 hours---sams series

    Thanks in Advance

    :) HASMUKH :)
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
  4. ali hasnain

    ali hasnain New Member

    Joined:
    Jun 5, 2007
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    I have post my query from long time. nobuddy reply my query. It is request you to please give me the solution.

    Dear All,

    I need your help on below problems.

    Here’s in my use two computers one is in my home use and second in my office use. On both computers I found some problems. Here’s I am mentioning the problem of my Computers

    At home use: I am using windows me on my home computer. And I have Avg antivirus on my computer. The folder option not display on my control panel and tool menu and I found the folder.exe file on my computer and I delete this file with my pc but it comes again. Please advise and If you have any tips to improve the speed of my pc please advise.

    At Office Use: I am using windows 2000 on my office computer and I have Norton antivirus on my computer. When my PC boot completely an error comes on my window screen RHVOST.EXE and another problem is that I can’t load my Ms Office Excel file directly. First I run the Office Excel and then browse the required file. Please advise.

    I hope you will entertain my quires. Thanks in advance.


    Regards,

    Ali hasnain
     
  5. parvez.yu

    parvez.yu New Member

    Joined:
    Feb 14, 2008
    Messages:
    100
    Likes Received:
    0
    Trophy Points:
    0
    jsp is tough ,but i like it more than asp
     
  6. prabhat1

    prabhat1 New Member

    Joined:
    Mar 21, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0

    hiiiiiiii Mr. pradeep i m new to JSP kindly help me in updating database(SQL server 05) thru JSP but always getting unexpected results like insertion of null values,persistence of previous values into the string........looking forward for your help.......thanks
     
  7. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    We'll need to have a look at your code to debug what's wrong, please your DB insertion code.
     
  8. prabhat1

    prabhat1 New Member

    Joined:
    Mar 21, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    ******** post by prabhat*********for database updation
    the relation table is" test(roll(int),sub_code(int),stud_name(varchar),sub_name(varchar),fees(money),status(bit)
    *********
    basic prob is that when updation is done the form keeps the prevoius values of updation and that leads to incosistent results..........

    HTML:
    <%@ page import="java.sql.*"%>
    <html>
    
    <head><title>table update test</title></head>
    <body>
    <form name="f1">
    
    <%
    	
    
    int id=0;
    
    
    Connection con = null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ;
    con=DriverManager.getConnection("jdbc:odbc:SQL_SERVER;user=sa;password=password@123");
    	
    	Statement stmt=con.createStatement();
    
    // for test table update 	  
    
        int id1=0;
        float id2=0;
    	String st=request.getParameter("cmbroll");
    	String st1=request.getParameter("txtsub_code");
    	String st2=request.getParameter("txtstud_name");
    	String st3=request.getParameter("txtsub_name");
    	String st4=request.getParameter("txtfees");
    	boolean st5=Boolean.parseBoolean(request.getParameter("txtstatus"));
    
    	if(st!=null)
    	{
       		id=Integer.parseInt(st);
    	} 
    	 
    	if(st1!=null)
    	{
    	  id1=Integer.parseInt(st1);
    	}
    	
    	if(st4!=null)
    	{
    		id2=Float.parseFloat(st4);
    	}
    	
    	
    	  
    	
    %>
    
    <h2>roll<sup>*</sup><select name="cmbroll" onChange="document.f1.submit()"></h2>
    <option>select</option>
     <%
     ResultSet rs=stmt.executeQuery("select roll from test ");
     	while(rs.next())
     	{
     	
     		int x=rs.getInt("roll");
     	
     	
      %>
    <option
    <% if(id!=0 && id==x) 
    out.println("selected");
     %>
    
    >
    
    
    <%= x %></option>
    
    <% 
    
    } 
    
    %>  
    </select>
    
     <% 
     
     
     	
     	if(id!=0)
     	{ 
     	
     		ResultSet rs1=stmt.executeQuery("select * from test where roll="+id);
     		while(rs1.next())
     		{
     			 int code=rs1.getInt("sub_code");
     			 String sname=rs1.getString("stud_name");
     			 String sbname=rs1.getString("sub_name");
     			 float fss=rs1.getFloat("fees");
     			 boolean sts=rs1.getBoolean("status");
    
    
    
     			 
     	
     	
      %>
       
      
      <h2>Subject Code<input type="text" name="txtsub_code" value="<%=code%>"></h2>
      <h2>Student Name<input type="text" name="txtstud_name" value="<%=sname%>"></h2>
      <h2>Subject Name<input type="text" name="txtsub_name" value="<%=sbname%>"></h2>
      <h2>Fees<input type="text" name="txtfees" value="<%=fss%>"></h2>
      <h2>Status<input type="text" name="txtstatus" value="<%=sts%>"></h2>
      <input type="submit" value="update">
      
      <% 
       	  }
    		  if(st1!=null && id1!=0 && st3!=null && id2!=0)
    		  stmt.executeUpdate("update test set sub_code="+id1+",stud_name='"+st2+"',sub_name='"+st3+"',fees="+id2+",status='"+st5+"' where roll="+id);
    
      }
      
     
     
     %>
     
     </form>
     </body>
     </html>
    
    looking forard for your response......
    thanks .........
    prabhat....
     
    Last edited by a moderator: Mar 23, 2008
  9. prabhat1

    prabhat1 New Member

    Joined:
    Mar 21, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    hiiiiiiiii.. pradeep .......i hope there is no changes in the code.........thn where was d problem is .......
     
  10. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    You should make an update only when the second form is posted, here you are running the update while displaying the form...make a flowchart of your program then you'll understand!
     
  11. prabhat1

    prabhat1 New Member

    Joined:
    Mar 21, 2008
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    problem is not with the update ..actually the first value which is fetched from the database appears every time after update is done....... i want that the updated value should persist after clicking the update button............
    looking forward for your response..

    thanx.........

    prabhat
     
  12. Jenniferlinn

    Jenniferlinn New Member

    Joined:
    Dec 24, 2008
    Messages:
    23
    Likes Received:
    3
    Trophy Points:
    0
    Occupation:
    search engine optimization
    Location:
    UK
    Home Page:
    http://www.micrositez.co.uk/se
    Here are some more details:

    JSP is a server-side scripting technology that enables Java code to be dynamically embedded within Web pages (HTML files) and executed when the page is served, returning dynamic content to a client.

    The JSP syntax adds additional XML-like tags, called JSP actions, to be used to invoke built-in functionality. Additionally, the technology allows for the creation of JSP tag libraries that act as extensions to the standard HTML or XML tags. Tag libraries provide a platform independent way of extending the capabilities of a Web server.

    JSPs are compiled into Java Servlets by a JSP compiler. A JSP compiler may generate a servlet in Java code that is then compiled by the Java compiler, or it may generate byte code for the servlet directly. JSPs can also be interpreted on-the-fly, reducing the time taken to reload changes.

    JSP syntax

    A JavaServer Page may be broken down into the following pieces:

    * static data such as HTML
    * JSP directives such as the include directive
    * JSP scripting elements and variables
    * JSP actions
    * custom tags with correct library

    On the other hand Java Servlets are small programs coded in the Java programming laguage that are executed on a web server.

    The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of a Web container and a servlet. A Web container is essentially the component of a Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

    A Servlet is an object that receives a request and generates a response based on that request. The basic servlet package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web application.

    Servlets can be generated automatically by JavaServer Pages (JSP) compiler, or alternately by template engines such as WebMacro. Often servlets are used in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.

    Lifecycle of a Servlet

    The Servlet lifecycle consists of the following steps:

    1. The Servlet class is loaded by the container during start-up.
    2. The container calls the init() method. This method initializes the servlet and must be called before the servlet can service any requests. In the entire life of a servlet, the init() method is called only once.
    3. After initialization, the servlet can service client-requests. Each request is serviced in its own separate thread. The container calls the service() method of the servlet for every request. The service() method determines the kind of request being made and dispatches it to an appropriate method to handle the request. The developer of the servlet must provide an implementation for these methods. If a request for a method that is not implemented by the servlet is made, the method of the parent class is called, typically resulting in an error being returned to the requester.
    4. Finally, the container calls the destroy() method which takes the servlet out of service. The destroy() method like init() is called only once in the lifecycle of a Servlet.

    Here is a simple servlet that just generates HTML
    HTML:
    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 HelloWorld extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
                                            "Transitional//EN\">\n" +
                    "<HTML>\n" +
                    "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
                    "<BODY>\n" +
                    "<H1>Hello WWW</H1>\n" +
                    "</BODY></HTML>");
      }
    }
     
  13. gkumar

    gkumar New Member

    Joined:
    Jun 16, 2009
    Messages:
    58
    Likes Received:
    5
    Trophy Points:
    0
    JSP:-Short for Java Server Page. A server-side technology, Java Server Pages are an extension to the Java servlet technology that was developed by Sun.

    JSPs have dynamic scripting capability that works in tandem with HTML code, separating the page logic from the static elements -- the actual design and display of the page -- to help make the HTML more functional(i.e. dynamic database queries).

    A JSP is translated into Java servlet before being run, and it processes HTTP requests and generates responses like any servlet. However, JSP technology provides a more convenient way to code a servlet. Translation occurs the first time the application is run. A JSP translator is triggered by the .jsp file name extension in a URL. JSPs are fully interoperable with servlets. You can include output from a servlet or forward the output to a servlet, and a servlet can include output from a JSP or forward output to a JSP.
    Java Servlets:-Java servlets are essentially Java programs which extend the functionality of a server. They are not confined to web servers, but are most often referred to in this context. Virtually all references to servlets cite them as a replacement for CGI scripts, so it is easiest to think of them as Java programs that perform CGI functions.

    The intriguing thing about servlets is their claimed performance. Traditional CGI scripts written in Perl, C, etc. all have a disadvantage in that a new process must be created for each call of the script. The overhead of process creation and management can be very taxing on a loaded server. Servlets solve this problem by creating a thread for each request, rather than an entire process. A single process for each servlet is created, then a request to the servlet causes a thread to be created to handle it.
     
    shabbir likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice