Friday, December 24, 2010

Jsp & Servlet


Question 1: Which of the following is not a standard method called as part of the JSP life cycle?
 Answer: jspService()

Question 2: If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
 Answer: <%! %>

Question 3: Which can not be used as the scope when using a JavaBean with JSP?
 Answer:  Response is not a valid object scope for JavaBeans

Question 4: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect
 Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

Question 5: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?
 Answer: forward executes on the server while sendRedirect() executes on the client.

Question 6: How you  makes your compiled JSP page implement the SingleThreadModel interface?
 Answer: <%@ page isThreadSafe="false" %>

Question 7: What is the difference between doing an include or a forward with a RequestDispatcher?
 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

Question 8: When a JSP page is compiled, what is it turned into?
 Answer: Servlet

Question 9: What is JavaServer Pages technology?
 Answer: JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

Question 10: How does the JavaServer Pages technology work?
 Answer: JSP pages use XML tags and scriptlets written in the JavaTM programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.

JSP technology is part of the Java technology family; it uses a Java programming language-based scripting language, and JSP pages are compiled into servlets. JSP pages may call JavaBeansTM components (beans) or Enterprise JavaBeansTM components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

Question 11: Why do I need JSP technology if I already have servlets?
 Answer: JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

Question 12: What is a JSP page?
 Answer: A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.

Question 13: How do JSP pages work?
 Answer: A JSP engine interprets tags and scriptlets, and generates the content required - for example, by calling a bean, accessing a database with the JDBCTM API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. JSP scriptlets let developers tie everything together, and ordinary HTML tags control the formatting and display of the generated page.

Question 14: How is a JSP page invoked and compiled?
 Answer: Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

Question 15: Can I create XML pages using JSP technology?
 Answer: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

Question 16: Can I generate and manipulate JSP pages using XML tools?
 Answer: The JSP 1.1 specification describes a mapping between JSP pages and XML documents.The mapping enables the creation and manipulation of JSP pages using XML tools.

Question 17: How do I use JavaBeans components (beans) from a JSP page?
 Answer: The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

Question 18: Why are there no try/catch blocks around my JSP scriptlets? I know the code should throw errors.
 Answer: Don't be confused. Scriplets do eventually end up with try/catch blocks around thier code. A JSP will catch any thrown error and display it to a user, or optionally handle it with a error page if specified.

If you would like to see the error handling examine the generated code by your JSP container.

Question 19: How do I call a function in my JSP via client-side JavaScript?
 Answer: It is not possible to do that.

A common misconception about JSP is where it takes place. JSP occurs only on the server-side. As it implies, client-side JavaScript takes place only on the client's computer. You cannont interchange the two.

Question 20: What are Implicit Objects?
Answer. An implicit object is available for a JSP developer to use inside scriptlets and expressions. The implicit objects represent all of the important components of the PageContext. Implicit objects need not be declared. They already exist and an error will be thrown if another variable of the same name is used.

User friendly documentaion of the implicit objects along with code examples is also provided at JSP Insider. Here is a list of the JSP 1.1 implicit objects and links for the documentation provided by JSP Insider.

A. pageContext
B. application
C. out
D. response
E. request
F: Session

 Question 21: Is it possible to pass in any Object other than a String to a taglib?
 Answer. Yes, just use an expression. The value of the expression will not be converted to a string in this case.
 Take the following example
 <example:tag date="<%= new java.util.Date()%>" />
 In the above example, the corresponding tag handler will have the setDate method called with a java.util.Date object passed in as a parameter.
 This is perfectly valid in your JSP assuming the tag's value can be a runtime expression. The TLD for this taglibrary would have to include the following snippet.
  
  <attribute> 
    <name>date</name> 
    <rtexprvalue>true</rtexprvalue> 
  </attribute>
  
Question 22: Both <%!...%> and <%...%> can be used for declaring variables. What is the difference between both and which to use?
 Answer: There is a distinct difference between an declaration, <%!...%>, and a scriptlet, <%...%>.

<%!...%> Declares a variable or method valid in the scripting language used in the JSP page.
<%...%> Contains a code fragment valid in the pages scripting language.

The big difference is that <%...%> is initialized once per each request to the JSP. Often the <%...%> is prefered and recommended for this reason, variables declared by <%!...%> are only loaded once, at the beginning of the JSP's lifecycle.
Question 23: What JSP servers are currently available?
 Answer: Here's a list of JSP servers with which we are familiar. This is only a partial list.
                                Extreme Internet Server
                                IPlanet WebServer 
                                JRun
                                Orion
                                Resin
                                Tomcat
                                WebLogic
                                WebSphere
                                ServletExec
                                LiteWebServer
For a more complete list check out the Java server list at the Java Skyline web site. This list contains more than just JSP servers, but it is a great place to start.
  
Question 24: How do I Pass an Object between a Servlet and a JSP?
 Answer: On the server-side you may forward the request with, pageContext.forward("Relative URI..."); for a JSP, or with getServletConfig().getServletContext().getRequestDispatcher("Relative URI...").forward(request, response); for a Servlet. The same HttpServletRequest object is shared when using these methods. Because of this objects may be stashed and retrieved using the getAttribute() and setAttribute() methods of HttpServletRequest.

Take for example the following Servlet. A java.lang.String object is set in the request object with "text" as the key. The servlet then fowards to a JSP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException  
  {
   String text  = new String("Some text to pass...");
   request.setAttribute("text", text);
   getServletConfig().getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

  }
}

  Using getAttribute(), a JSP can access the object set by the servlet.

1
2
3
4
5
6
7
8
9
10
<html>
 <head><title>Passing an object.</title></head>
 <body>
<%
  String text = (String)request.getAttribute("text");
%>
<%= text %>
 </body>
</html>


 If the result would be a webpage displaying, "Some text to pass..."

Any object may be passed using this method. Just remember to use the appropriate type cast when getting the object from the request. This method may also be used to pass objects between only servlets or JSP.

Question 25: How can I set a cookie in JSP?
 Answer: This should work:

response.setHeader("Set-Cookie", "cookie string");
To give the response-object to a bean, write a method setResponse
(HttpServletResponse response)
- to the bean, and in jsp-file:

<%
bean.setResponse (response);
%>

Question 26: How can I include one JSP inside another JSP?
 Answer: <%@ include="FileName.jsp" %>
  
Question 27: How do I delete a cookie with JSP?
 Answer:
<%
                Cookie killCookie = new Cookie("foo", null);
                killCookie.setPath("/");
                killCookie.setMaxAge(0);
                response.addCookie(killCookie);
%>

Question 28: What is a web application?
 Answer: A web application is a collection of resources that is mapped to a specific Uniform Resource Identifier (URI) prefix. These resources may include JSP pages, Servlets, HTML files, and images.

Question 29: If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
 Answer: <%! %>

Question 30: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?
 Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

Question 31: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?
 Answer: forward executes on the server while sendRedirect() executes on the client.

Question 32. What is the difference between doing an include or a forward with a RequestDispatcher?
 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

Question 33. What are the elements available in JSP?
 Answer: There are three types of elements: directive elements, scripting elements, and action elements.

Question 34. How do you invoke a JSP page from a servlet?
 Answer:
                ServletContext context = getServletConfig().getServletContext();
                context.getResourceDispatcher(urlpath).forward(request, response);
                                                                                (Or)
                RequestDispatcher rd = request.getRequestDispatcher(urlpath);
                rd.forward(request, response);

Question 35. Can JSP and Servlet share same Session and Beans?
 Answer: Yes

Question 36. What are the different scopes available for usebean tag in JSP?
 Answer: Page, Request, Session and Application.





PHP Form Image Upload

















This tutorial shows you how to upload an image on your server using PHP and html forms. You will also learn how to verify if the uploaded file is an image (checking the extension), if it doesn't overtakes a size limit and how to change the uploaded file name.
Important: You must set the enctype form atribute to "multipart/form-data", otherwise the form will not show you any errors, but it will just not upload your images!

Step 1: Create a folder named images located in the path you are planning to place the php script you are about to create. Make sure it has write rights for everybody or the scripts won't work ( it won't be able to upload the files into the directory).
Step 2: Paste the following code into a php file.
Please read carefuly the comments. All steps are explained there.
<?php
//define a maxim size for the uploaded images in Kb
 define ("MAX_SIZE","100");

//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
 function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
 }

//This variable is used as a flag. The value is initialized with 0 (meaning no error  found) 
//and it will be changed to 1 if an errro occures. 
//If the error occures the file will not be uploaded.
 $errors=0;
//checks if the form has been submitted
 if(isset($_POST['Submit']))
 {
               //reads the name of the file the user submitted for uploading
               $image=$_FILES['image']['name'];
               //if it is not empty
               if ($image)
               {
               //get the original name of the file from the clients machine
                               $filename = stripslashes($_FILES['image']['name']);
               //get the extension of the file in a lower case format
                               $extension = getExtension($filename);
                               $extension = strtolower($extension);
               //if it is not a known extension, we will suppose it is an error and will not  upload the file, 
               //otherwise we will do more tests
 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif"))
                               {
                               //print error message
                                              echo '<h1>Unknown extension!</h1>';
                                              $errors=1;
                               }
                               else
                               {
//get the size of the image in bytes
 //$_FILES['image']['tmp_name'] is the temporary filename of the file
 //in which the uploaded file was stored on the server
 $size=filesize($_FILES['image']['tmp_name']);

//compare the size with the maxim size we defined and print error if bigger
if ($size > MAX_SIZE*1024)
{
               echo '<h1>You have exceeded the size limit!</h1>';
               $errors=1;
}

//we will give an unique name, for example the time in unix time format
$image_name=time().'.'.$extension;
//the new name will be containing the full path where will be stored (images folder)
$newname="images/".$image_name;
//we verify if the image has been uploaded, and print error instead
$copied = copy($_FILES['image']['tmp_name'], $newname);
if (!$copied)
{
               echo '<h1>Copy unsuccessfull!</h1>';
               $errors=1;
}}}}

//If no errors registred, print the success message
 if(isset($_POST['Submit']) && !$errors)
 {
               echo "<h1>File Uploaded Successfully! Try again!</h1>";
 }

 ?>

 <!--next comes the form, you must set the enctype to "multipart/frm-data" and use an input type "file" -->
 <form name="newad" method="post" enctype="multipart/form-data"  action="">
 <table>
               <tr><td><input type="file" name="image"></td></tr>
               <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
 </table>
 </form>


0 comments:

Post a Comment