answersLogoWhite

0

JSP and Servlets

JSP (JavaServer Pages) are Java programs encoded within webpages that research and generate pertinent results. Servlets, on the other hand, are objects (programs) that handle requests from users and provide results based on these requests.

261 Questions

How do JSP methods get translated to Servlet methods?

A JSP gets converted into a Servlet for execution and hence the methods in a JSP are similar to the ones in a Servlet.

  • Scriptlets and Expressions will end up in the body of doGet or doPost
  • Declarations will end up as instance variables
  • jspInit() and jspDestroy() will get translated to Servlet's init() and destroy() methods

Can you override the life cycle methods of a JSP?

You cannot override the jspService() method but you can override the jspInit() and jspDestroy() methods

Write a program using servlet and JDBC for developing an onine application to create a database?

// You can use this sample servlet as a starting point to connect to

// your database included with useractive account.

//

// Portions copied from Sun's HelloWorldServlet.java

// You are free to use this code in any way you chose

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public

class HelloWorldServlet extends HttpServlet {

public void doGet (HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/html");

ServletOutputStream out = res.getOutputStream();

out.println("<html>");

out.println("<head><title>Hello World</title></head>");

out.println("<body>");

try {

// The newInstance() call is a work around for some

// broken Java implementations

out.println("asdf");

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

}

catch (Exception E) {

out.println("Unable to load driver.");

E.printStackTrace();

}

out.println("<br><hr>");

try {

Connection Conn =

DriverManager.getConnection("jdbc:mysql://sql.useractive.com/USERNAME?user=USERNAME&password=PASSWORD");

// Do something with the Connection

Statement Stmt = Conn.createStatement();

ResultSet RS = Stmt.executeQuery("SELECT * from SOMETABLE");

while (RS.next()) {

out.println(RS.getString(1));

}

// Clean up after ourselves

RS.close();

Stmt.close();

Conn.close();

}

catch (SQLException E) {

out.println("SQLException: " + E.getMessage());

out.println("SQLState: " + E.getSQLState());

out.println("VendorError: " + E.getErrorCode());

}

out.println("<h1>Hello World. Sun... 1.4</h1>");

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

}

public String getServletInfo() {

return "Create a page that says <i>Hello World</i> and send it back";

}

}

Differniate between applet and servlet in java?

Applet:

It is run on browser, i mean client side.

Servlet:

It is run on server, i mean server side.

Why CGI is still used over servlets?

CGI is an outdated technology. Servelets are much more efficient and powerful when compared to the CGI technology. Hence, Servlets are more commonly used than CGI.

How do you refresh your page?

you refresh the page by pressing the f5 or by clicking the two little arrows

What is signature of service method in servlet?

The doXXX Methods

There are 3 main types of requests that get processed by a Servlet. They are:

• Get

• Post

• Put

Each of them have a corresponding doXXX() method in the Servlet class which would be:

• doGet

• doPost

• doPut

These methods are called by the service method in your Servlet.

Let us now take a look at a sample Servlet that has these 3 doXXX methods.

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/**

* A servlet that has the 3 doXXX Methods

*

* @author Anand

*/

public class OurSecondServlet extends HttpServlet

{

// doGet()

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

requestType("GET", response);

}

// doPost()

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

requestType("POST", response);

}

// doPut()

public void doPut(HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException

{

requestType("PUT", response);

}

public void requestType(String requestType,

HttpServletResponse response)

throws IOException, ServletException

{

response.setContentType("text/HTML");

PrintWriter out = response.getWriter();

out.println("< HTML >");

out.println("< head >");

out.println("< title >Our Second Servlet" +

"< / title >");

out.println("< / head >");

out.println("< body >");

out.println("< h1 >Servlet Request< / h1 >");

out.println("The Submitted Request type is : " + requestType);

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

out.println("< / HTML >");

}

}

Can you use constructor in servlet?

Yes you can but it is not required. A Servlet is nothing but another .java file and all rules that are applicable to standard Java classes are applicable to them.

Note: Even if you write a constructor in a servlet, it will not get executed.

What is the use of jsp?

JSP stands for Java Server Pages. It is the face of any web application. I.e., the stuff you see on a web page can be JSP contents. The JSP uses the features of both Java and HTML to display dynamic contents on a web page. It interacts with Servlets in a MVC architecture to provide the power to display dynamic and advanced data on any given web page.

How many implicit objects in JSP?

There are nine implicit objects in JSP.
1. pageContext
2. session
3. request
4. response
5. exception
6. out
7. application
8. config
9. page

Write a program for calculator using jsp?

<html>

<head>

<title>Using Multiple Forms</title>

</head>

<body>

<h1>Using Multiple Forms</h1>

<%

if(request.getParameter("button") != null) {

%>

<% String s = request.getParameter("button");

int no1,no2;

if(request.getParameter("no1").equals("")) { no1 = 0; } else no1 = Integer.valueOf(request.getParameter("no1"));

if(request.getParameter("no2").equals("")) { no2 = 0; } else no2 = Integer.valueOf(request.getParameter("no2"));

if (s.equals("ADD")) {

out.println("Result is " + (no1 + no2));

}

else if (s.equals("SUB")) {

out.println("Result is " + (no1-no2));

}

else if(s.equals("MUL")) {

out.println("Result is " + (no1*no2));

}

else if(s.equals("DIV")) {

out.println("Result is " + (no1/no2));

}

%>

<%

}

%>

<form name="form1" method="get">

<input name="no1">

<input name="no2">

<input type="hidden" name="button" value="ADD">

<input type="submit" value="ADD">

</form>

<form name="form2" method="get">

<input name="no1">

<input name="no2">

<input type="hidden" name="button" value="SUB">

<input type="submit" value="SUB">

</form>

<form name="form3" method="get">

<input name="no1">

<input name="no2">

<input type="hidden" name="button" value="MUL">

<input type="submit" value="MUL">

</form>

<form name="form4" method="get">

<input name="no1">

<input name="no2">

<input type="hidden" name="button" value="DIV">

<input type="submit" value="DIV">

</form>

</body>

</html>

Raj...

Random numbers without repetition of numbers in jsp or servlet?

The normal way of "generating" random numbers without repetition is to first define an array of all possible values, and then to randomize their order. You can then iterate over the array to get your "random" values.

// Returns an array containing the values in the range [start, end] in a random order.

static int[] getRandom(final int start, final int end) {

final int[] nums = new int[end - start + 1];

// Fill array

for (int i = 0; i < nums.length; ++i) {

nums[i] = start + i;

}

// Shuffle array

final Random rnd = new Random(System.currentTimeMillis());

for (int i = nums.length - 1; i > 0; --i) {

// Generate an index to swap with...

final int swapIndex = rnd.nextInt(i + 1);

// ...and swap

final int temp = nums[i];

nums[i] = nums[swapIndex];

nums[swapIndex] = temp;

}

return nums;

}

Where is the correct place to insert a JavaScript?

hi,

This is sunil maurya . I am working with Geometric solution Bangalore... as software developer.

According to java script rule we can use this language on separate file and use in the HTML code as well as we also write code in the same file and use it where needed...

Thanks

Sunil maurya

What is JSP web language?

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.

What is different between jsp and servlets?

A JSP is typically oriented more towards displaying information, and a servlet is more oriented towards processing information. For example, a JSP might display a report, while a servlet would process a user submitted form. These uses are not exclusive, but they are optimized more for performing tasks in this manner. It is much easier to incorporate HTML coding into a JSP than a Servlet. It is also easier to write more complex Java code in a servlet.

What is difference between servlets and java server pages?

SERVLETS

JSP

1. Servlet is a java class.

2. Servlet is a single instance multiple thread web application, In which HTML code can be included in java code.

3. In servlets the presentation logic and the B.logic is tightly coupled.

4. For every modification done in servlet program, we need to recompile and reload the application.

5. In servlets implicit objects are not available.

6. Servlets are supported to HTTP, FTP, and SMTP protocols.

7. Sevlets are need Deployment Descriptor file (web.xml)

1. Jsp is a file.

2. In jsp java code can be included in HTML code by using special tags.

3. In jsp's the presentation logic and B.logic are separated by defining the java beans.

4. If any modifications done in jsp's without recompiling and reloading , the modifications are reflected.

5. In jsp's implicit objects are available which is we can implement directly into jsp pages.

6. Jsp are supported to HTTP protocol only.

7. No need of Deployment Descriptor file (web.xml)

rajus_1219@yahoo.co.in

What are the servlet config methods?

Methods in the Servlet Context

Apart from setting and getting custom attributes used for our application, the context also contains various methods that we can use to retrieve specific information about the application and other aspects. They are:

• getAttributeNames() - Returns an Enumeration object containing the attribute names available within this servlet context.

• getContext(String uripath) - Returns a ServletContext object that corresponds to a specified URL on the server.

• getInitParameter(String name) - Returns a string containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

• getInitParameterNames() - Returns the names of the context's initialization parameters as an Enumeration of string objects, or an empty Enumeration if the context has no initialization parameters.

• getMajorVersion() - Returns the major version as an int of the Java Servlet API that this Servlet Container supports.

• getMimeType(java.lang.String file) - Returns the MIME type as a string of the specified file, or null if the MIME type is not known.

• getMinorVersion() - Returns the minor version as an int of the Servlet API that this Servlet Container supports.

• getNamedDispatcher(String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

• getRealPath(String path) - Returns a string containing the real path for a given virtual path.

• getRequestDispatcher(String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

• getResource(String path) - Returns a URL to the resource that is mapped to a specified path.

• getResourceAsStream(String path) - Returns the resource located at the named path as an InputStream object.

• getServerInfo() Returns the name and version as a String of the Servlet Container on which the servlet is running.

When do you use JSPs as opposed to Servlets?

JSPs and Servlets can be used interchangeably for the most part. In fact, when a JSP is compiled, it is actually turned into a servlet! That being said, there are some guidelines for using servlets over JSPs or vice versa. Here are a couple of examples, but by no means a complete list: Typically, you would use a JSP to display dynamic data, or a form. A Servlet is usually what you would want to use to process a post or a get, especially considering the method that is called when you call a servlet (either doGet or doPost). For more information on this, here is a good article on Servlet and JSP Best Practices: http:/java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp

What are the advantages and disadvantages of servlet?

Servlets are an integral part of any J2EE Web application. The key benefits of using Servlets in our web applications are:

a. They are faster than CGI scripts because each CGI script produces an entirely new process that takes a lot of time to execute, whereas a servlet creates only a new thread.

b. Servlet API is standard and available easily on the internet (like JSPs)

c. Servlets have the advantages like ease of development & platform independence (like Java)

d. They can access all the J2SE and J2EE APIs

e. Can take the full advantage & capabilities of the Java programming langauge

As you can see, there are numerous advantages of using the Servlet & JSP technologies. This is exactly why numerous organizations use them as a staple part of their J2EE application development work.

The Disadvantage would be that Servlets are a little difficult to learn and use.

Is it necessary to learn advanced java for JSP?

It is a good to know item. It is not mandatory or necessary. Basic knowledge of core Java is enough to learn JSP and Servlets.

How do you refresh a page?

Click on the refresh button which is mostly located next to the address bar on the top of the page and looks like a blue arrow, mostly 2 arrows making a circle. to make it easier, you can also press the 'F5' button on the top of your keyboard.

What is java servlet chaining?

Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

Where you can download java servlet development kit2.0?

There is no specific/separate servlet development kit. Servlets can be developed and compiled using the standard JDK and JRE.

The only difference being the fact that - to run them you need a web server

How do you transfer values from javascript to JSP?

You can set the value in the hidden form fields using javascript and access the form fields in JSP