Showing posts with label JSP/Servlet. Show all posts
Showing posts with label JSP/Servlet. Show all posts

31 January 2012

Servlets and thread safty

From Servlet 2.4 specs:

SRV.2.3.3.3
Thread Safety
Implementations of the request and response objects are not guaranteed to be thread
safe. This means that they should only be used within the scope of the request han-
dling thread.
References to the request and response objects should not be given to objects
executing in other threads as the resulting behavior may be nondeterministic. If
the thread created by the application uses the container-managed objects, such as
the request or response object, those objects must be accessed only within the
servlet’s service life cycle and such thread itself should have a life cycle within
the life cycle of the servlet’s service method because accessing those objects
after the service method ends may cause undeterministic problems. Be aware
that the request and response objects are not thread safe. If those objects were
accessed in the multiple threads, the access should be synchronized or be done
through the wrapper to add the thread safety, for instance, synchronizing the call
of the methods to access the request attribute, or using a local output stream for
the response object within a thread.

When the destroy method gets called in the Servlet?

It is an implementation-depended, nobody knows!
SRV.2.3.4
End of Service
The servlet container is not required to keep a servlet loaded for any particular
period of time. A servlet instance may be kept active in a servlet container for a
period of milliseconds, for the lifetime of the servlet container (which could be a
number of days, months, or years), or any amount of time in between.
When the servlet container determines that a servlet should be removed from
service, it calls the destroy method of the Servlet interface to allow the servlet to
release any resources it is using and save any persistent state. For example, the
container may do this when it wants to conserve memory resources, or when it is
being shut down.
Before the servlet container calls the destroy method, it must allow any
threads that are currently running in the service method of the servlet to complete
execution, or exceed a server-defined time limit.
Once the destroy method is called on a servlet instance, the container may
not route other requests to that instance of the servlet. If the container needs to
enable the servlet again, it must do so with a new instance of the servlet’s class.
After the destroy method completes, the servlet container must release the
servlet instance so that it is eligible for garbage collection.


Source Servelt-2.4 specs document

11 February 2011

And at last I know why some Objects should be mutable!

Hello Everybody ....

We all know the difference between mutable and immutable objects as we know the difference between StringBuffer and String objects.

But believe me, it is the first time to know that this difference is very very vital in some situations.

Let me tell you a story ....

I am a some Servlet Filter that I need to modify some Http headers in it before sending the request to the Servlet to process the request.

I looked at the HttpServletRequest methods trying to find a method allows me from modifing the request headers (some thing like request.setHeader("")) but i cannot.

I tried to make a trick (this is the point) on the same way of:

// suppose we have employee object that composes a manage object but with no setter method..
// we need to change some data in the employee's manager we could do:

Employee e = ....;
e.getManager().setManagerName("new name");


I tried to do the following:

String headerValue = request.getHeader("headerName")
headerValue.set("newValue");/// ooooops, Strings are mutables!!!

For such case, The string object is mutable....

19 May 2010

request.getCharacterEncoding() always returns null

Alsalamo Alykom,

If you suffer from this problem, so this is the place you need to visit!

Well, you need to get the character encoding of the request sender in Servlets and you have tried using this method again and again but without any results!

So, this is not the problem of the Servlets, It is the problem of the browser you use!

Yes, try the following code to make sure that the Servlet engine can interpret the character encoding of your request, but only when they are really sent

the following code written suing Commons-http, and need commons-logging and commons-codes:

package com.forat;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class Client {
public static void main(String[] args) throws IOException{
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod("http://localhost:8080/aServer/AServlet");
method.setRequestHeader("Content-Type", "text/plain; charset=GB2312");
client.executeMethod(method);
}
}


And here's the Servlet code:

package com.forat;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class AServlet
*/
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getCharacterEncoding());
}

}



And here's the output:
GB2312


For Firefox, try Firebug to make sure that firefox doesn't send the Content-Type as a request header even if you set.

Here's a sample HTML page that sends to the same above servlet:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312">
</head>
<body>

<form action="AServlet" method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>


and the result of the servlet is:
null


And here's a screenshot from Firebug displaying all request header but doens't display Content-type.

06 May 2010

Beware, your text editor encodes your characters

Al salamo Alykom,

Actually nowadays I am falling in some encoding issue that making me walk thinking in how characters being encoded!

And here's another note, actually I got from BalusC, from stackoverflow

Ok, When you intend to use some character encoding in your html/jsp/php/... page, you have to know that your text editor is actually encoding your text.

What does this mean??

Well, suppose you have a html page that you need to submit in another encoding rather than UTF-8 (say, GB3212 - some chines encoding)

If you write any field value in the text editor (as opposite to make the user enter it through text boxes), you will get the characters corrupted. (this happens when using hidden fields)

For example, this page:

<HTML>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>
<BODY >
<form name="form" method="post" action="http://localhost:8080/testChinaEncoding/EncodingServlet" accept-charset="gb2312" accept="gb2312">
<input type="text" name="username" size="50" value="美白祛斑—做完美女人"> <!-- UTF-8 characters -->
<input type="submit">
</form>
</BODY>
</HTML>


The point is, when open this page in a browser, you will notice that the characters appear in the text box, are corrupted!
Yes, this is because you are typing these characters in the text editor using one encoding (usually UTF-8), and want to display these characters using other character encoding (GB2312)!

And here's a screen-shot from the output page:


Note, the big difference from the character being written in the form, and the characters being displayed!

for more info, please see: http://balusc.blogspot.com/2009/05/unicode-how-to-get-characters-right.html

07 December 2008

Building UI components using JSP custom tags

In the name of Allah, the gracious the merciful


In this article, we will build custom UI components using JSP custom tags so that we can customize your own UI components by adding for example style sheet effects.

Lets start:

Tocreate any custom tag in JSP, first you need to figure it out, so we expect that tag will looks like that

<ui:TextBox
id=”txt1” size=”20” value=”${param.username}” />

so, the TextBox component appears to have id attribute that is mandatory, size and value attributes that are not.

Lets build the Tag Handler class:

we will use JSP 2.0 new SimpleTagSupport class as a superclass for our handler:

package org.daz;


import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.JspException;


public class UITagHandler extends SimpleTagSupport {

private java.lang.String id;
private java.lang.String value = "";
private java.lang.String size;

public void doTag() throws JspException {

JspWriter out=getJspContext().getOut();

try
{


String tag = "<input type='text' name='" + id + "' size='"
+ size + "'"
+ " value = '" + value + "' />";

out.write(tag);}

catch (java.io.IOException ex) {

throw new JspException(ex.getMessage());

}

}
public void setId(java.lang.String value) {

this.id = value;

}

public void setValue(java.lang.String value) {

this.value = value;

}


public void setSize(java.lang.String value) {

this.size = value;

}


}


Note the doTag() method, it calls getJspContext() to get a JspContext instance that can get a JspWriter from to write tag contents.

As you noticed that we utilize the class <input> tag of HTML, so we need to customize that tag as we need as I said before.

Lets now create the TLD file:


<?xml
version="1.0" encoding="UTF-8"?>


<taglib
version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-jsptaglibrary_2_0.xsd">



<tlib-version>1.0</tlib-version>


<short-name>ui
customtags</short-name>


<uri>http://daz.org/uicustomtags</uri>


<tag>


<name>TextBox</name>



<tag-class>org.daz.UITagHandler</tag-class>


<body-content>empty</body-content>


<attribute>


<name>id</name>


<required>true</required>



<type>java.lang.String</type>


</attribute>


<attribute>


<name>value</name>


<rtexprvalue>true</rtexprvalue>


<type>java.lang.String</type>



</attribute>


<attribute>


<name>size</name>


<rtexprvalue>true</rtexprvalue>


<type>java.lang.String</type>


</attribute>



</tag>


</taglib>


That's all about the custom UI component, lets try it in.


create a JSP page and code that in it:


<%@
taglib uri=”http://daz.org/uicustomtags
prefix=”ui” %>


<form
action="doAction.do" method="post" >



firstname
<ui:TextBox id="firstname" size="50" /> <br
/>


lastname
<ui:TextBox id="lastname" size="50" /> <br
/>



programming
languages <ui:TextBox id="fav" size="30" />
<br />


<input
type="submit" />


</form>


create
this Servlet to handle the JSP page ( as a Controller ):


import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class TestServlet extends HttpServlet {


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


response.setContentType("text/html");

PrintWriter out = response.getWriter();
out.println ("Hello " + request.getParameter("firstname") + " " + request.getParameter("lastname"));

out.println ("<br> we know that you like " + request.getParameter("fav")+ " programming language.");


out.flush();

}

}

note: put this in your DD file to make the Servlet is the action of the form:


<servlet>

<servlet-name>TestServlet</servlet-name>


<servlet-class>TestServlet</servlet-class>

</servlet>


<servlet-mapping>


<servlet-name>TestServlet</servlet-name>


<url-pattern>/insertData.do</url-pattern>


</servlet-mapping>


Now our example has finished, but you should realize that this idea also can be used to make the design of your JSP pages more easier.
thus instead of using <jsp:include> and <c:import> tags to import headers and footers for your pages, you can build your own custom tags that represent each part of you page, example you would

design tag for the header <ui:header id=”hdr1” param1=”${xx}
param2=${xxx} /> and also for the navigation pans and the footer,
so your page design became easier and more clearer.

03 December 2008

The new Servlets3.0 Specifications

Well, Servlets new release 3.0 has be annonced.
the new 3.0 specs changed servlet tech on the way that EJB3.0 does, it uses annotations to obsolete xml meta data and make all its objects as POJOs.

many changes added to the new release such as annotations (@xxx ), making all componenet as POJO, request suspention and allowing servlets to be added to the web app after deployement.

you can find more in this article :
http://www.theserverside.com/tt/articles/article.tss?track=NL-461&ad=677675&l=PonderingAboutJSR135&asrc=EM_NLN_5169898&uid=6248156

16 October 2007

JSP Model1 and Model2 (MVC)

أنا بصراحه حابب أشاركم بصورتين حلوين جدا لمبرمجين ال Jsp بيوضحوا الفرق بين model1 و model2 في ال jsp /servlet
ممكن ميفهمش كلامي ده غير حد ليه في ال Jsp بس بجد صورتين واضحين جدا.

رابط الموضوع كده أهه

الصوره الاولي :



إيه بقه اللي بيحصل هنا ؟

اولا الطريقه دي في كتابة برامج ال Jsp تعتبر طريقة المبتدئين عشان هيا طريقه سلطه شويه ( عامله زي الطريقه اللي بيتبعها الاخوه بتوع الدوت نيت في كتابت برامج ال asp.net كل حاجه بتكون سايحه على بعضها )

ال request بيجي من المتصفح، بنستقبله بصفحة ال jsp و بيتم معالجته سواء عمل إستعلام من قاعدة البانات أو تخزين أو تعديل بيانات، مثلا إفرض إن الصفحه دي صفحة تسجيل دخول فهيحصل التالي :

في بداية الكود بتاع الصفحه هيفحص اسم المستخدم و كلمة المرور من قاعدة البيانات و بعد كده لو لقي المستخدم مرخصله الدخول ، هيوجهه لصفحه تانيه أو يظهرله في نفس الصفحه الحساب بتاعه، لو غير كده هيرجعه لنفس الصفحه و يقوله أعد إدخال البيانات.


نيجي بقه للطريق الاحترافيه ، طريقة ال MVC ( Model-View-Controller ):



اللي بيحصل هنا إن الموضوع منظم، ازاي ؟

دلوقتي عندنا بدل ما بنستخدم صفح jsp بس ، لا هنستخدم sevlets كمان ، و معروف إن كل واحد منهم ليه إستخدامه، فال jsp تستخدم للعروض فقط ( ال Presentation ) الكلام ده كبعا متحققش في الوضع الاول ، أحنا إستخدمنا صفحة ال Jsp في إننا نتأكد هل المستخدم ده عندنا ولا لأ ، و بكده نكون إستخدمنا Jsp في عمل حاجه خارج حدود ال presentation ، أما في الوضع التاني فإحنا هنستخدم ال Jsp استخدامن أمثل و نخليها تعرض بس و برضه ال servlet هنخليها تقوم بالمعالجه و عدم العرض .

طبعا الراجل بيروح يدخل البيانات في صفحة ، jsp أو html أهم حاجه صفحه فيها فورمه وخلاص، إحنا بقه في موديل 2 ( الوضع التاني ) هنخلى أول حاجه الراجل يقابلها في وشه هي ال servlet و هنفحص ، هل ال request اللي جايلك ده فيه قيم في ال متغيرات بتاعته ( request parameters ) ؟ لو لا يبقه الراجل لسه مشفش الفورمه ولسه مملهاش بالبيانات فنروح نعرض الفورمه ليه و نخليه يملاها ، و نخلى ال فورمه دي تبعت على ال servlet ـاني يعني نخلي المتغير action في ال form tag بتاع الفورمه ب ال servlet و بالتالي لما المستخدم يروح يمله الفورمه و يدوس submit تروح الفورمه بمتغيرتها لل servlet ، فيقوم ال servlet فاحص تاني ، هل الفورمه دي متغيرتها مليانه قيم ، لو لأ هيروح ينفذ الخطوه اللي فاتت لو أه هيروح يعالج القيم دي ، في حالتنا دي هيروح يفحص هل اسم المستخدم و كلمة المرور دول موجودين في قاعدة البانات ؟ لو أه روح إبعتني لصفحة jsp مناسبه لو لأا ، رجعني تاني للصفح ه الرئسيه.

ميزة الطريقه دي إننا خلينا صفحات ال Jsp للعرض فقط ، اما ال servlet فيكون فيها كا الكود التاني ، ال Business login يعني .

شوفتوا الحوار موش سيهل إزاي يبتوع الدوت نيت !!؟؟؟؟

و ده بيحصل مع كول فورمه عندنا في التطبيق بتاعنا .

أنا عارف إن الموضوع متعب شويه بس بجد منظم جدا ، و عشان هوا متعب فيه frameworks مخصوصه إتعملت بتساعد المبرمج في عمل الحوار ده من أشهرهم و أهمه ال struts وده مشروح مفتوح المصدر من المنظمه المشهوره جدا apache.org

الاسترتس بقه بتعمل كل حاجه كل اللي عليك إنته إنك تحدد ال process اللي إنتا عاوز تعملها في السيستم بتاعك و هي تقوم بالباقي ، بس موش بالبساطه دي!!!!!

الاسترتس دي متنفعش مع المشاريع الصغيره عشان هتعقد الدنيا ع الفاضي ، بس بجد لو المشروع كبير لازم framework تنظم الدنيا زي الاسترتس.

ودمتم في رعاية الله و أمنه.