Sun River
Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ...
posts - 78,comments - 0,trackbacks - 0
 
  1. Page translation
  2. JSP page compilation

  3. Load class

  4. Create instance

  5. Call jspInit

  6. Call _jspService

  7. Call jspDestroy

posted @ 2006-10-08 12:21 Sun River| 编辑 收藏

Question 1:

You need to create a database connection in your application after reading the username, password, and database server URL from the deployment descriptor. Which will be the best place to do this?

Choices:

  • A. Servlet constructor
  • B. init() method
  • C. service() method
  • D. doGet() method
  • E. doPost() method

Correct choice:

  • B

Explanation:

The init() method is invoked once and only once by the container, so the creation of the database connection will be done only once, which is appropriate. The service() , doGet() , and doPost() methods might be called many times by the container.

The username, password, and URL are to be read from the deployment descriptor. These initialization parameters are contained in the ServletConfig object, which is passed to the init() method. That is why we need to use the init() method instead of the constructor for this purpose, even though the constructor is also called only once.

Question 2:

A user can select multiple locations from a list box on an HTML form. Which of the following methods can be used to retrieve all the selected locations?

Choices:

  • A. getParameter()
  • B. getParameters()
  • C. getParameterValues()
  • D. getParamValues()
  • E. None of the above

Correct choice:

  • C

Explanation:

The getParameterValues(String paraName) method of the ServletRequest interface returns all the values associated with a parameter. It returns an array of Strings containing the values. The getParameter() method returns just one of the values associated with the given parameter, so choice A is incorrect. There are no methods named getParameters() or getParamValues() , so choices B and D are incorrect.

posted @ 2006-10-08 05:01 Sun River| 编辑 收藏
Question 1:

Consider the following servlet code:

public class MyServlet extends HttpServlet
{
final static int i=0;
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
private HttpSession session=req.getSession();
private ServletContext ctx=getServletContext();
synchronized(ctx)
{
Object obj=ctx.getAttribute(); // code to alter obj
}
}
}

Which of the following variables in the above code are thread safe?

Choices:

  • A. i
  • B. session
  • C. ctx
  • D. req
  • E. obj
  • F. res

Correct choices:

  • A , C , D , and F

Explanation:

The static variable i is thread safe because it is final (cannot be modified), or else it would not have been safe. Request and response objects are scoped only for the lifetime of the request, so they are also thread safe. Session and ServletContext objects can be accessed from multiple threads while processing multiple requests, so they are not thread safe. However, in this case, the ServletContext object is synchronized, so it can be accessed only by one thread at a time. obj is not thread safe because even though the ServletContext object is synchronized, its attributes are not. They need to be synchronized separately. Hence choices B and E are incorrect and choices A, C, D and F are correct.

Question 2:

Which of the following statements are true?

Choices:

  • A. Multiple instances may be created on a servlet implementing SingleThreadModel
  • B. No more than one instance is created for a servlet implementing SingleThreadModel
  • C. Even static variables in a SingleThreadModel servlet are thread safe
  • D. If no threading model is implemented, by default a servlet is executed in a multi-threaded model

Correct choices:

  • A and D

Explanation:

When SingleThreadModel is implemented, the servlet container ensures that only one thread is executing the servlet's method at a time. So what will happen for multiple requests? In that case, the container may instantiate multiple instances of the servlet to handle multiple requests, so option A is correct and B is incorrect.

If the SingleThreadModel interface is not implemented, a servlet uses the multi-threaded model (that is, multiple threads can access the methods of the servlet). Static variables can be accessed through multiple instances of the same class, so they are not always thread safe. Hence choices B and C are incorrect and choices A and D are correct.

posted @ 2006-10-08 04:29 Sun River| 编辑 收藏

Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:

Questions:

- Entry level:
  - Is AJAX a programming language?
  - What is AJAX?
  - How new is AJAX?
  - Why can/should AJAX be used?
 A: AJAX is best suited for small (hopefully unobtrusive) updates to the current
    web page, based on information that is not available until it has been provided
    by the end user.
  - When should AJAX NOT be used?
  A: It would not be appropriate to use AJAX when the "answer/result" can be determinded
    by the client.  Generally, the purpose of AJAX is to submit a short request to the server,
    and process the response in such a way as to add value to the currently displayed page.
    It would also not be appropriate to use AJAX when the magnitude of the response is such
    that it would be easier, and more clear to redisplay the page.

  - What objects are used by AJAX programs?

- Intermediate-level?
  - Describe the  formats and protocols used/specified by AJAX
  - Describe some things that can't be done with AJAX
 A: Sending a request to a server outside of the domain from which  the web page originated.
  - How should AJAX objects be created?
  - For what error conditions should programs check?
  - Are Finite State Machines (FSM's) appropriate for use with AJAX?
  - Identify and describe the state transitions that can/should occur within a transaction
A: - Reset : When the XmlHttpRequest object is created, no connection yet exists between the clent, and the server.
      Open  : When the xmlHttp.open() is issued, the request is being prepared for transmission to the server
      Sent   : When the xmlHttp.send() is issued, the request is transmitted to the server application
      Rcvd   : When the xmlHttp callback routine is called, the readyState and status fields of the object define why the routine was called

Q. How do you know that an AJAX request has completed?
A. The XHR.readyState is 4 and the XHR.status is 200 (or zero if the request is to a local file). The callback function is called four times - first with status=1, then 2,3, and finally 4.
Q. How does XML processing differ on the different browsers?
A. It's an ActiveX object on IE, but is native on the other browsers
Q: What values exists for the XmlHttpRequest.readyState field, and what do they mean?
A: readyState values:
    0 = uninitialized
    1 = loading
    2 = loaded
    3 = interactive
    4 = complete  


Other areas to check up on:
   How do you process the returned XML data?
   If it's a Java/J2EE place: what about AJAX and JSF?
   How to populate the XML response on the server?
   How to terminate an active request?

posted @ 2006-10-05 10:09 Sun River| 编辑 收藏

What are the design patterns in Java?

In j2ee they have 15 Design Pattern:

Presentation Tier:
1.Intercepting Filter
2. Front Controller
3. View Helper
4. Composite View
5. Service to Worker
6. Dispatcher View

Business Tier:
7. Business Delegate
8. Transfer Object
9. Session Facade
10. Service Locator
11. Transfer Object
12. Value List Handler
13. Composite Entity

Integration Tier:
14.Service Activator
15 Data Access Object

posted @ 2006-09-25 09:47 Sun River| 编辑 收藏
  In need to save XML representation of your Java object? Here is a simple 200-line class that will do this using reflection. But don't worry, there is some very powerful caching going on, so that the performance will be very good.

Thanks to comments for pointing out the isAssignableFrom() function in Class. Also, now the resulting XML is valid with all the special characters (&, <, >, &apos; and ").

package own;

import java.lang.reflect.*;
import java.util.*;

public class OptimizedReflectionMarshaller {
  // cache for getters
  private static HashMap gettersMap = new HashMap();

  // cache for storing info on whether certain class implements Collection
  private static HashMap collectionsMap = new HashMap();

  private static final String JAVA = "java.";
  private static final String JAVAX = "javax.";
  
  private static final Class[] EMPTYPARAMS = new Class[0];
  
  /**
   * Info on a single field and the corresponding getter method
   */
  private static class FieldMethodPair {
    private String fieldName;

    private Method getterMethod;

    public FieldMethodPair(String fieldName, Method getterMethod) {
      this.fieldName = fieldName;
      this.getterMethod = getterMethod;
    }

    public String getFieldName() {
      return fieldName;
    }

    public Method getGetterMethod() {
      return getterMethod;
    }
  }

  /**
   * Returns the marshalled XML representation of the parameter object
   */
  public static String marshal(Object obj) {
    StringBuffer sb = new StringBuffer();
    Class clazz = obj.getClass();

    // get class name in lower letters (w/o package name)
    String className = clazz.getName();
    int lastDotIndex = className.lastIndexOf(".");
    if (lastDotIndex >= 0)
      className = className.substring(lastDotIndex + 1);
    className = className.toLowerCase();

    sb.append("<" + className + ">");
    marshal(obj, sb);
    sb.append("</" + className + ">");
    return sb.toString();
  }

  /**
   * Returns getter function for the specified field
   */
  private static Method getGetter(Class clazz, String fieldName) {
    try {
      // for example, for 'name' we will look for 'getName'
      String getMethodName = fieldName.substring(0, 1);
      getMethodName = getMethodName.toUpperCase();
      getMethodName = "get" + getMethodName
          + fieldName.substring(1, fieldName.length());
      Method getMethod = clazz.getMethod(getMethodName, EMPTYPARAMS);
      return getMethod;
    } catch (NoSuchMethodException nsme) {
      return null;
    }
  }

  /**
   * Returns a list of all fields that have getters
   */
  private static List getAllGetters(Class clazz) {
    try {
      // check if have in cache
      if (gettersMap.containsKey(clazz.getName()))
        return (List) gettersMap.get(clazz.getName());

      List fieldList = new LinkedList();
      Class currClazz = clazz;
      while (true) {
        Field[] fields = currClazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
          Field currField = fields[i];
          int modifiers = currField.getModifiers();
          // check if not static and has getter
          if (!Modifier.isStatic(modifiers)) {
            Method getterMethod = getGetter(clazz, currField
                .getName());
            if (getterMethod != null) {
              FieldMethodPair fmp = new FieldMethodPair(currField
                  .getName(), getterMethod);
              fieldList.add(fmp);
            }
          }
        }
        currClazz = currClazz.getSuperclass();
        if (currClazz == null)
          break;
      }

      // store in cache
      gettersMap.put(clazz.getName(), fieldList);

      return fieldList;
    } catch (Exception exc) {
      exc.printStackTrace();
      return null;
    }
  }

  /**
   * Checks whether the specified class implements Collection interface
   */
  private static boolean isImplementsCollection(Class clazz) {
    String className = clazz.getName();
    // check in cache
    if (collectionsMap.containsKey(className)) {
      return ((Boolean) collectionsMap.get(className)).booleanValue();
    }

    boolean result = Collection.class.isAssignableFrom(clazz);

    // store in cache
    collectionsMap.put(className, new Boolean(result));
    return result;
  }

  private static void appendFormatted(Object obj, StringBuffer sb) {
    String strRepresentation = obj.toString();
    int len = strRepresentation.length();
    for (int i = 0; i < len; i++) {
      char c = strRepresentation.charAt(i);
      switch (c) {
      case '&':
        sb.append("&amp;");
        break;
      case '<':
        sb.append("&lt;");
        break;
      case '>':
        sb.append("&gt;");
        break;
      case '\'':
        sb.append("&apos;");
        break;
      case '\"':
        sb.append("&quot;");
        break;
      default:
        sb.append(c);
      }
    }
  }

  private static void marshal(Object obj, StringBuffer sb) {
    try {
      Class clazz = obj.getClass();
      String className = clazz.getName();

      // check if implements Collection
      if (isImplementsCollection(clazz)) {
        Collection cobj = (Collection) obj;
        Iterator it = cobj.iterator();
        while (it.hasNext()) {
          Object eobj = it.next();
          sb.append("<" + eobj.getClass().getName() + ">");
          marshal(eobj, sb);
          sb.append("</" + eobj.getClass().getName() + ">");
        }
        return;
      }

      // check for primitive types
      if (className.startsWith(JAVA) || className.startsWith(JAVAX)) {
        appendFormatted(obj, sb);
        return;
      }

      // otherwise put all fields with getters
      List allGetters = getAllGetters(clazz);
      Iterator itGetters = allGetters.iterator();
      while (itGetters.hasNext()) {
        FieldMethodPair currGetter = (FieldMethodPair) itGetters.next();
        String currFieldName = currGetter.fieldName;
        Method currentGetter = currGetter.getterMethod;

        // call method
        Object val = currentGetter.invoke(obj, EMPTYPARAMS);
        if (val != null) {
          sb.append("<" + currFieldName + ">");
          // call recursively
          marshal(val, sb);
          sb.append("</" + currFieldName + ">");
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Feel free to use and modify.
posted @ 2006-09-25 09:36 Sun River| 编辑 收藏
1. How do i find whether a parameter exists in the request object?(JSP)
A:   boolean hasPara=request.getParameterMap().contains(theParameter);
     or boolean hasfoo=!(request.getParameter("foo")==null || request.getParameter("foo").equals(""))
2. What is 2 phase commit?
 A: It is an algorithm used to ensure the integrity of a committing transaction. In Phase 1, the transaction coordinator contacts potential participants in the transaction, the participants all agree to make the results of the transaction permanent but do not do so immediately. The participants log information to disk to ensure they can complete in phase 2. if all the participants agree to commit, the coordinator logs that agreement and the outcome is decided. The recording of this agreement in the log ends in Phase 2, thecoordinator informs each participant of the decision, and they permanently update their resources.
3. How Can I insert images into a MySql Database?
 A:   
           File file=new File(fPic);
           FileInputStream fis=new FileInputStream(file);
           PreparedStatement ps=con.prepareStatement("insert into dbPic values(?,?)");  
           ps.setString(1,file.getName());
           ps.setBinaryStream(2,fis,(int)file.length());
           ps.executeUpdate();
           ps.close();
           fis.close();
posted @ 2006-09-25 06:43 Sun River| 编辑 收藏
From Manager:
   1. Describe for us your current position. what are you major responsibility in this position?
   2. Describe to us what you understand this position to be/
   3. Why does this position interest you? What are your expectations?
   4. What past experience do you have that you feel qualified you for this position?
About Experience:
   5. Tell us about you past experience with (probe for breadth & depth of involvement in projects/complexity of workload --how was success measured? what kinds o results were achieved? )
   6. We have all had occasion when we were working on something and overlooked a small detail. Give me an example of when this happened to you. what causeed it to happen? what was the result?
Relationship Building:
   7. Tell me about a time when you had to work with a business partner who you had not worked with before. how did you approach initiating and developing this relationship so that you could achieve your project or organization goals?
   8. This position requires the ability to juggle many tasks at once. how have you gone about meeting all of your deadlines on line/ what have you done when faced with missing a deadline(How do you organize your time)?
Closing
  
9. What drives/moitivates you?
  10. What are your business goal?
  11. What do you see as your initial challenges if you were offered this position? what are your developmental gaps in relation to this position?
  12. Do you have any questions?
posted @ 2006-09-24 23:14 Sun River| 编辑 收藏

RUP Contains phases, iterations, and workflows.  
Has 4 phases:
              1). Inception--Define the scope of project
              2). Elaboration-- Plan project, specify features, baseline architecture
              3). Construction--Build the product
              4). Transition--Transition the product into end user comminity
Use Case Driven, Designed and Documented using UML.

rup_fu1.jpg

posted @ 2006-09-24 15:43 Sun River| 编辑 收藏

Using Ajax

Page update without refresh using Javascript, PHP and XML's XMLHTTPRequest object (also known as 'remote scripting')

In this tutorial we'll discuss the basic principles of remote scripting using Ajax, a combination of javascript and XML to allow web pages to be updated with new information from the server, without the user having to wait for a page refresh.  Ajax therefore allows us to build web applications with user interfaces rather more like those of desktop applications, providing a better experience for the user.  Ajax tools are becoming increasingly popular, and a list of ajax development projects is also given.

Here you'll find:

  • a brief tour of the important principles of Ajax
  • code examples of all important points
  • links to further Ajax and related resources

This tutorial covers subjects which require some degree of familiarity with Javascript and PHP.  Beginners may therefore find it a little hard going, but hopefully should still be able to grasp the principles and uses of Ajax, if not the details.  There are some demos and further links at the bottom of the article and elsewhere on these pages - feel free to explore..

What is it?
The standard and well-known method for user interaction with web-based applications involves the user entering information (e.g. filling out a form), submitting that information to the server, and awaiting a page refresh or redirect to return the response from the server.

This is at times frustrating for the user, besides being rather different to the 'desktop' style of user interface with which (s)he may be more familiar.

Ajax (Asynchronous Javascript And XML) is a technique (or, more correctly, a combination of techniques) for submitting server requests 'in the background' and returning information from the server to the user without the necessity of waiting for a page load.

Ajax is actually a combination of several technologies working together to provide this capability.

How does it work?
Instead of a user request being made of the server via, for example, a normal HTTP POST or GET request, such as would be made by submitting a form or clicking a hyperlink, an Ajax script makes a request of a server by using the Javascript XMLHTTPRequest object.

Although this object may be unfamiliar to many, in fact it behaves like a fairly ordinary javascript object.  As you may well know, when using a javascript image object we may dynamically change the URL of the image source without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.

How is it coded?
There are a few, relatively simple, steps to coding an Ajax application.  The description below is an attempt to describe the salient points without bogging down the new user in too many of the technicalities.

Firstly, we need to know how to create an XMLHTTPRequest object.  The process differs slightly depending on whether you are using Internet Explorer (5+) with ActiveX enabled, or a standards-compliant browser such as Mozilla Firefox.

With IE, the request looks like:

http = new ActiveXObject("Microsoft.XMLHTTP");

whereas in a standards-compliant browser we can instantiate the object directly:

http = new XMLHttpRequest();

There's an example of a short piece of code to create the object here, which clearly demonstrates the different approaches for the two different browser types, along with a browser detection routine.

Secondly, we need to write an event handler which will be called via some event on our user's page, and will handle sending our request for data to our server.

The event handler will use various methods of our XMLHTTPRequest object to:

  • make the request of the server
  • check when the server says that it has completed the request, and
  • deal with the information returned by the server

We can make our request of the server by using a GET method to an appropriate server-side script.  Here's an example event handler called updateData which assumes that we have created our XMLHTTPRequest object and called it http:

function updateData(param) {
  var myurl = [here I insert the URL to my server script];


   http.open("GET", myurl + "?id=" + escape(param), true );
  http.onreadystatechange = useHttpResponse;
  http.send(null);

}

 

Note that the function listens to the onreadystatechange property of the XMLHTTPRequest object and, each time this parameter changes, calls a further function useHttpResponse.

You will note also that, for the sake of clarity, I have said little about the server-side script which is called - essentially this can be any server routine which will generate the required output when called with the relevant URL and appended parameters, as in any other HTTP GET request.  For the sake of the example we are passing a variable named id with a value param passed as an argument to the updateData function.

Thirdly, then, we need to write a function useHttpResponse which will establish when the server has completed our request, and do something useful with the data it has returned:

function useHttpResponse() {
  if (http.readyState == 4
) {
    var textout = http.responseText;
    document.write.textout;
  }
}

Note here that our function checks for a readyState value of 4 - there are various numbered states describing the progress of such a request, but we are only interested in the value of 4, which indicates that the request is complete and we can use the returned data.

In this case, we have received our information as simple text via the responseText property of our XMLHTTPRequest object.  Information can, however, be returned as XML or as properties of a predefined javascript object, though this is perhaps beyond the scope of this tutorial.

Try out all the techniques described above in the Ajax Demonstration

Making Ajax Easy

There are quite a few toolkits springing up that package the Ajax calls into useable libraries.  For small projects, these may not be worth using due to the code overhead and learning curve involved, but for more complex Ajax projects you may find them useful.  You'll find some relevant links below and elsewhere on these pages - feel free to explore.


(From Ajaxprojects)
posted @ 2006-09-24 13:24 Sun River| 编辑 收藏
仅列出标题
共8页: 上一页 1 2 3 4 5 6 7 8 下一页