Saturday, November 19, 2011

Case Sensative Database Query

Normally, the information kept in a cell of a database is not case sensative. For the query as below


Select * from tblShopInfo where shopName='bata'
Select * from tblShopInfo where shopName='batA'
Select * from tblShopInfo where shopName='Bata'



we will get same results for the all of the above queries. But if we are in need to get the information of case sensative partameter. Then we need to make the query as below:


Select * from tblShopInfo where shopName COLLATE Latin1_General_CS_AS ='baTa'



The above query will return only the specific info we need.

Tuesday, November 8, 2011

Request, Response, getParameter, getAttribute

All the above four terms are not so difficult. But for me sometimes they create a jam in my brain. To solve this jam..

Request : From Client to Server
Response: From Server to Client
Server: Receive Request and Send Response
Client: Send Request and Receive Response


Now,about getParameter()

when we submit a form they all the info is send to action element(resource) of the form. On the context of action element if we want to get the information of the submitted form, we should use

request.getParamater()

So request.getParameter() will retrieve a value that the client has submitted. You will get the value on the server side.

request.getAttribute(), this is all done server side. YOU add the attribute to the request and YOU submit the request to another resource, the client does not know about this. So all the code handling this would typically be in servlets.

Difference between sendRedirect and forward

sendRedirect is the marriage which is leagal as both the parties know each other and faithful.
forward: where one of the party cheats and contacts to third party.. a illicit relationship..

Probably this will make a clear concept to us, as all time we like to thinks in different way.

So, from the above we are sure about the family where Hubby and wife don't hide anything from each other. They share to each others every thing. Suppose, coming back from office, Husband request to make a cup of tea to his lovely wife. Wife is busy with her favorite TV serials. So, she tells the maid servant to mak the tea for him. Beside this Wife also inform his hubby about the maker of the tea and request to get tea from the servant. Then hubby will take the update of the tea from the servant.

On the contrary, in another family getting the request of tea from the husband, wife asked to make tea another one but after completion she must provide the tea directly to his wife.

First Family is sendRedirect and the second one is forward.

sendRedirect() sends a redirect response back to the client's browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.

forward() does not involve the client's browser. It just takes browser's current request, and hands it off to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.

Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface
- RequestDispatcher.SendRedirect( ) works on the browser.
- The SendRedirect( ) allows you to redirect trip to the Client.
- The SendRedirect( ) allows you to redirect to any URL.
- After executing the SendRedirect( ) the control will not return back to same method.
- The Client receives the Http response code 302 indicating that temporarly the client is being redirected to the specified location , if the specified location is relative , this method converts it into an absolute URL before redirecting.
- The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen.





Forward( ) : javax.Servlet.RequestDispatcher interface.

- RequestDispatcher.forward( ) works on the Server.
- The forward( ) works inside the WebContainer.
- The forward( ) restricts you to redirect only to a resource in the same web-Application.
- After executing the forward( ), the control will return back to the same method from where the forward method was called.
- The forward( ) will redirect in the application server itself, it doesn't come back to the client.
- The forward( ) is faster than Sendredirect( ) .

Monday, October 17, 2011

Search from addres bar in firefox

There is an easy way to turn your address bar into a Google search box. You want to type into your address bar about:config. Next, type into the filter keyword.URL. Once you have found it there, modify the string in there and replace it with: http://www.google.com/search?btnG=Google+Search&q= From now on, when you type in a word or phrase into the address bar and hit enter, it will launch a Google search for it rather than giving you Google’s top result for that word or phrase

Adding new datasource to iReport in Netbeans

iReport is an important tools for reporting in java applications. In Netbeans, we may face problem to add new data source for iReport. Here is the step by step procedure to add a database driver for iReport. 1) go to "Tools / Options" menu and select iReport 2) verify that database JDBC driver is present: - Choose "Classpath" tab - Click "Add JAR" and then locate the desired (mysql.jdbc).Driver - Click "OK" 3) click "Connections / Datasources" icon in toolbar 4) click "New" and set up a "Database JDBC Connection" using driver from step 2 5) click "Test" to verify the data source works correctly 6) click "Save" to save the data source

Wednesday, September 7, 2011

Java Desktop Application: To set size of the mainFrame of singleFrameApplication in Netbeans n

It was very critical for me to fix the size of the Form in a SingleFrameApplication through Netbeans. In design view if we rezise the frame, it doesn't affect at the run time. As In teh run time it shows the default size. To resize the page, we need to write some code in a specific location. In the view.java file of application package, we need to modify some info.


this.getFrame().setTitle("Stop Job from Database"); //Ti set the title of the default form

Dimension size = new Dimension(0144, 0144); // these values need to be changed to Octal or Hexadecimal after provding Integer value.

this.getFrame().setSize(size); // to set the size of the frame

Saturday, August 27, 2011

to solve javascript disable browser

If you use javascript code for your application, you should not depend fully on it for various important checking. Beside it, server side checking also should be implemented. Because, if javascript of the web browser is disabled then, all checking will be stopped with it.

But, there is an another option of the disabling problem of javascript. There is a tag <NOSCRIPT>, which is use when javascript is not found in the browser. And message can be showed inside this <NOSCRIPT> tag. Beside showing message it can also be used to hide a page element from the page. An example of code snap of using <NOSCRIPT> tag. <NOSCRIPT> tag should be used inside <HEAD> tag

Code Example of NOSCRIPT


<noscript >
<style type="text/css">
.pagecontainer {display:none;}
</style>
<div style="color: red; text-decoration: blink;font-size: xx-large" align="center">
This page uses Javascript. Your browser either doesn't support Javascript or you have it turned off.
To see this page as it is meant to appear please use a Javascript enabled browser
</div>
</noscript>

Friday, August 26, 2011

javamail: to access mail through java

The JavaMail API is a set of abstract APIs that model a mail system.The JavaMail API provides facilities for reading and sending email. Service providers implement particular protocols. Several service providers are included with the JavaMail API package; others are available separately.


Download Javamail



If a web-based email services provide POP3 or IMAP access, JavaMail can probably be used to access it.


IMAP:IMAP stands for Internet Message Access Protocol. It is a method of accessing electronic mail messages stored on a (possibly shared) mail server. In other words, it permits a "client" email program to access remote message stores as if they were local.


SMTP
SMTP stands for Simple Mail Transfer Protocol. It is used to transfer RFC822-style messages between different mail hosts as well as to submit new messages to a host for delivery. SMTP is in very wide use (it originated in 1982).



MIME
MIME and RFC822 are the standards for describing email messages that are sent across the Internet. The javax.mail.internet subpackage (which is part of the JavaMail APIs) provides a complete implementation of these two packages. MIME is specified by the following RFCs: RFC2045, RFC2046, RFC2047.




POP3

POP3 stands for Post Office Protocol version 3. POP3 is a very limited protocol for accessing a single mailbox. It is much less capable than IMAP. POP3 is very widely used and is defined by RFC1939.


To use javamail with your project, Unzip the distribution zip file and edit your CLASSPATH environment variable to include the mail.jar file that was included with the JavaMail API distribution.

At contect of Netbeans, javamail can be addred asfollowing steps:
Q: How do I add the JavaMail library to my NetBeans Java Project?
A: Use the Library Manager to create a library and add a reference to that library to your project.

1. Inside Netbeans, open the Library Manager (Tools > Libraries from the main menu bar).
2. Select
3. Enter a library name, e.g., "JavaMail", and hit . Do not check server library.
4. Make sure the new library is selected under "Libraries" on the left.
5. Select the "Classpath" tab on the right and choose
6. Using the file browser, select mail.jar from your JavaMail installation (e.g. .../javamail-1.4.3/mail.jar), and hit to accept.
7. Select the "Javadoc" tab and choose
8. Using the file browser, select the folder where the JavaMail javadoc index files are (e.g. .../javamail-1.4.3/docs/javadocs"), and hit to accept.
9. If you downloaded the JavaMail source code, you can set the source code reference on the "Sources" tab. This can be helpful for debugging. Using the file browser, select the source root for the JavaMail sources (".../javamail-1.4.3/mail/src/main/java" for 1.4.3) and hit to accept.

Note: If you are using JDK 1.5.0 or earlier you will need to add the JavaBeans Activation Framework library as well. You can create a separate library in a manner similar to the above, or just add activation.jar (and javadoc/source references if desired) to this library definition.

Now add a reference to this library to your project.

1. Open your project in NetBeans and make sure the "Projects" tab is visible.
2. Right click your project in the project explorer and select "Properties"
3. In the Properties dialog, select "Libraries" in the tree on the left and make sure the "Compile" tab is selected.
4. Click
5. Locate and select the library you created above and click "Add Library". It should be added to the list of compile-time libraries.
6. Click "OK" and you're done.



The JavaMail API package does not include any mail servers. To use the JavaMail API package, you'll need to have access to an IMAP or POP3 mail server (for reading mail) and/or an SMTP mail server (for sending mail). These mail servers are usually provided by your Internet Service Provider or are a part of your organization's networking infrastructure.



JavaMail 1.4 is capable of sending and reading messages using Gmail. All that's required is to properly configure JavaMail. I'll illustrate the proper configuration using the demo programs that come with JavaMail - msgshow.java and smtpsend.java.

Let's assume your Gmail username is "user@gmail.com" and your password is "passwd".

To read mail from your Gmail Inbox, invoke msgshow as follows:

java msgshow -D -T pop3s -H pop.gmail.com -U user -P passwd


By reading the msgshow.java source code, you can see how these command line arguments are used in the JavaMail API. You should first try using msgshow as shown above, and once that's working move on to writing and configuring your own program to use Gmail. The following code fragment shows a simple way to incorporate the needed configuration in your application:

String host = "pop.gmail.com;
String username = "user";
String password = "passwd";
// ...
Store store = session.getStore("pop3s");
store.connect(host, username, password);



To connect to Gmail using the IMAP protocol instead of the POP3 protocol, simply change the host name "pop.gmail.com" to "imap.gmail.com" and change the protocol name "pop3s" to "imaps" in the above instructions.

To send a message through Gmail, invoke smtpsend as follows:

java -Dmail.smtps.host=smtp.gmail.com -Dmail.smtps.auth=true
smtpsend -d -S -M smtp.gmail.com -U user -P passwd -A user@gmail.com


(Note that I split the command over two lines for display, but you should type it on one line.)

A bug in older versions of the smtpsend command causes it to set the incorrect properties when using the -S (SSL) option, so we work around that bug by setting them on the command line. The smtpsend program uses the System properties when creating the JavaMail Session, so the properties set on the command line will be available to the JavaMail Session.

The smtpsend program will prompt for a subject and message body text. End the message body with ^D on UNIX or ^Z on Windows.

Again, you can read the smtpsend.java source code to see how the command line arguments are used in the JavaMail API. The following code fragment shows a simple way to incorporate the needed configuration in your application:


    String host = "smtp.gmail.com;

String username = "user";
String password = "passwd";
Properties props = new Properties();
props.put("mail.smtps.auth", "true");
// ...
MimeMessage msg = new MimeMessage(session);
// set the message content here
Transport t = session.getTransport("smtps");
try {
t.connect(host, username, password);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}









Thursday, August 25, 2011

In JSP, Rendering a dropdrownlist on the basis of another dropdownlist's selection value

Its a little bit difficult to change a drop down list on basis of another selected value of drop down list in jsp. To do so, we need to use help from ajax. And the specific function of the ajax file is called onchange event of the (decision maker) drop down list.


onchange="loadDDLfirst()"

The loadDDLfirst() file is written in a javascript file(i.e, name of the javascript file is ajaxjs.js)




//////////////---Code of ajaxjs.js----///////////////////////
var xmlhttp;

var nm;
function loadDDLfirst()
{

/*To save the name of the District*/

var w = document...selectedIndex;
var selected_text = document...options[w].text;
document..selected_District.value=selected_text;

/////-----------------------------/////
var districtID;
parameterValue = document.getElementById("ddlFirst").value;

xmlhttp=GetXmlHttpObject();

if (xmlhttp==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}

//////////////---End of code of ajaxjs.js----///////////////////////


/* Actually the drop down list is generated at another webpage consisting on the dropdown list. And each time a random no. is added with the url to make identity of the request*/
url ="<webpageurl>?=" + parameterValue + "&idn=" + Math.random() * 100;
xmlhttp.onreadystatechange=getValues;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function getValues()
{
if (xmlhttp.readyState==4)
{
document.getElementById("load_ddl2ND").innerHTML=xmlhttp.responseText;
}
}


load_ddl2ND is the id of the form element where the webpageurl.jsp page will be showed. The webpageurl.jsp contains the code to create the dropdownlist.


<%
///Code to load simple dropdownlist as in normal jsp
%>



Sunday, August 14, 2011

show Image from database in jsp


We can provide a servlet as the source of the image. ans in the servlet we need to some little cook. This code may help you in the regards.

/*
* This Method Returns the right MIME type for a particular format
*


* @param String format ex: xml or HTML etc.
* @return String MIMEtype
*/
private String getMimeType(String format)
{
if(format.equalsIgnoreCase("pdf")) //check the out type
return "application/pdf";
else if(format.equalsIgnoreCase("audio_basic"))
return "audio/basic";
else if(format.equalsIgnoreCase("audio_wav"))
return "audio/wav";
else if(format.equalsIgnoreCase("image_gif"))
return "image/gif";
else if(format.equalsIgnoreCase("image_jpeg"))
return "image/jpeg";
else if(format.equalsIgnoreCase("image_bmp"))
return "image/bmp";
else if(format.equalsIgnoreCase("image_x-png"))
return "image/x-png";
else if(format.equalsIgnoreCase("msdownload"))
return "application/x-msdownload";
else if(format.equalsIgnoreCase("video_avi"))
return "video/avi";
else if(format.equalsIgnoreCase("video_mpeg"))
return "video/mpeg";
else if(format.equalsIgnoreCase("html"))
return "text/html";
else if(format.equalsIgnoreCase("xml"))
return "text/xml";
else
return null;
}

Step Two
Get the reference to the right OutPutStream. Use ServletOutPutStream, where as for character data you'd use PrintWriter, the java.io class that prints objects to a text-output stream. This following snippet is for binary data:


ServletOutputStream sOutStream = response.getOutputStream();

Step Three
Create BufferedInputStream from the InputStream:


BufferedInputStream bis = null;
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);




Step Four
Create BufferedOutPutStream with a new ServletOutPutStream to which you can write:


BufferedOutputStream bos = null;
bos = new BufferedOutputStream(sOutStream);

Step Five
Read in to the bytes array from BufferedInputStream:


byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}

Step Six
Write on to BufferedOutPutStream from the bytes array, which in turn streams to the client. Use the streamBinaryData() method for binary data streaming:


/*
* This Method Handles streaming Binary data
*


* @param String urlstr ex: http;//localhost/test.pdf etc.
* @param String format ex: pdf or audio_wav or msdocuments etc.
* @param ServletOutputStream outstr
* @param HttpServletResponse resp
*/
private void streamBinaryData(String urlstr,String format,
ServletOutputStream outstr, HttpServletResponse resp)
{
String ErrorStr = null;
try{
//find the right MIME type and set it as contenttype
resp.setContentType(getMimeType(format));
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try{
URL url = new URL(urlstr);
URLConnection urlc= url.openConnection();
int length = urlc.getContentLength();
resp.setContentLength(length);
// Use Buffered Stream for reading/writing.
InputStream in = urlc.getInputStream();
bis = new BufferedInputStream(in);
bos = new BufferedOutputStream(outstr);
byte[] buff = new byte[length];
int bytesRead;
// Simple read/write loop.
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
ErrorStr = "Error Streaming the Data";
outstr.print(ErrorStr);
} finally {
if( bis != null ) {
bis.close();
}
if( bos != null ) {
bos.close();
}
if( outstr != null ) {
outstr.flush();
outstr.close();
}
}
}
catch(Exception e){
e.printStackTrace();
}
}

N.B In the up coming post, i will try to note a complete sequence to show image from database.

Friday, August 12, 2011

Servlet Life cycle




* The servlet is initialized by calling the init () method.
* The servlet calls service() method to process a client's request.
* The servlet is terminated by calling the destroy() method.
* Finally, servlet is garbage collected by the garbage collector of the JVM.



The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.



2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.

The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {
// Initialization code...
}



3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.

The service() method :

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.



4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.



Monday, June 20, 2011

Procdure Call using Java(JSP)

Database Procedure Call using Java. It requires 6 basic steps:

Step 1:Define the call to the database procedure.
As with a prepared statement, you use special syntax to define a call to a stored procedure. The procedure definition uses escape syntax, where the appropriate ? defines input and output parameters.

• Procedure with no parameters. ---- { call procedure_name }
• Procedure with input parameters.-- { call procedure_name(?, ?, ...) }
• Procedure with an output parameter.---- { ? call procedure_name }
• Procedure with input and output parameters.{ ? = call procedure_name(?, ?, ...) }




Step 2: Prepare a CallableStatement for the procedure.
You obtain a CallableStatement from a Connection by calling prepareCall.

String procedure = "{ ? = call procedure_name( ?, ? ) }";
CallableStatement statement =
connection.prepareCall(procedure);



Step 3: Register the output parameter types.
Before executing the procedure, you must declare the type of each output parameter.

statement.registerOutParameter(n, type);

Step 4: Provide values for the input parameters.
Before executing the procedure, you must supply the input parameter values.

statement.setString(2, "name");
statement.setFloat(3, 26.0F);



Step 5: Execute the stored procedure.
To execute the database stored procedure, call execute on the CallableStatement.

statement.execute();

Step 6: Access the returned output parameters. Call the corresponding getXxx method, according to the output type.

int value = statement.getInt(1);

Friday, June 17, 2011

Naming Convention

What Is a Naming Convention?

A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).

Why Use Naming Conventions?

Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.

To illustrate the point it's worth mentioning that most software companies will have a document that outlines the naming conventions they want their programmers to follow. A new programmer who becomes familiar with those rules will be able to understand code written by a programmer who might have left the company many years before hand.

Picking a Name for Your Identifier


When choosing a name for an identifier make sure it's meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (e.g., customerName, accountDetails). Don't worry about the length of the name. A longer name that sums up the identifier perfectly is preferable to a shorter name that might be quick to type but ambiguous.
A Few Words About Cases

Using the right letter case is the key to following a naming convention:


*Lowercase is where all the letters in a word are written without any capitalization (e.g., while, if, mypackage).

*Uppercase is where all the letters in a word are written in capitals. When there are more than two words in the name use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).

*CamelCase (also known as Upper CamelCase) is where each new word begins with a capital letter (e.g., CamelCase, CustomerAccount, PlayingCard).


*Mixed case (also known as Lower CamelCase) is the same as CamelCase except the first letter of the name is in lowercase (e.g., hasChildren, customerFirstName, customerLastName).

Standard Java Naming Conventions


The below list outlines the standard Java naming conventions for each identifier type:

* Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:

package pokeranalyzer
package mycalculator

In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:

package com.mycompany.utilities
package org.bobscompany.application.userinterface

* Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:

class Customer
class Account

* Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:

interface Comparable
interface Enumerable

Note that some programmers like to distinguish interfaces by beginning the name with an "I":

interface IComparable
interface IEnumerable

* Methods: Names should be in mixed case. Use verbs to describe what the method does:

void calculateTax()
string getSurname()

* Variables: Names should be in mixed case. The names should represent what the value of the variable represents:

string firstName
int orderNumber

Only use very short names when the variables are short lived, such as in for loops:

for (int i=0; i<20;i++)
{
//i only lives in here
}

* Constants: Names should be in uppercase.

static final int DEFAULT_WIDTH
static final int MAX_HEIGHT



colleted from website

Wednesday, June 15, 2011

Servlet

Servlets are modules of Java code that run in a server application (hence the name "Servlets", similar to "Applets" on the client side) to answer client requests

Java servlets are becoming increasingly popular as an alternative to CGI(Common Gateway Interface) programs. The biggest difference between the two is that a Java applet is persistent. This means that once it is started, it stays in memory and can fulfill multiple requests. In contrast, a CGI-Common Gateway Interface program disappears once it has fulfilled a request.


It acts as a middlelayer between requests coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. some features are as below

• It is regular Java code. There are new APIs, but no new syntax.

• It has unfamiliar import statements. The servlet and JSP APIs are
not part of the Java 2 Platform, Standard Edition (J2SE); they are a
separate specification (and are also part of the Java 2 Platform,
Enterprise Edition—J2EE).

• It extends a standard class (HttpServlet). Servlets provide a rich
infrastructure for dealing with HTTP.

• It overrides the doGet method. Servlets have different methods to
respond to different types of HTTP commands.

Security is also an important issue related to servlet.


Quickly bookmark the link:
A complete guide to customized j2ee trainning

Tuesday, June 14, 2011

Model View Controller (MVC) design paradigm

Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:

* Model: application state
* View: presentation of data
* Controller: routing of the application flow

In another way we can depicts as

The Model represents the business or database code, the View represents the page design code, and the Controller represents the navigational code.The original MVC pattern is like a closed loop: The View talks to the Controller, which talks to the Model, which talks to the View.

Struts Framwork for Netbeans





The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

* Open source
* Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
* Implements the JSP Model 2 Architecture
* Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.



Another Workflow...Collected from sruts for netbeans





Struts Components

The Controller

This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.


The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.


Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.


View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.


ActionForms

These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.


Model Components

The Struts Framework has no built-in support for the Model layer. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies, such as JSP pages, JavaBeans, resource bundles, and XML.

Friday, June 10, 2011

Installation of Netbeans 7 in Ubuntu

Its really easy to install................

Step 1: Copy the Netbeans 7 for Linux(netbeans-7.0-ml-linux.sh) and JDK foo Linux(java_ee_sdk-6u1-jdk-linux.sh) into the desired location.

Step 2: Open the terminal from(Application-->Accessories--> Terminal)

Step 3: Using Command, navigate to the location of two files. Its better to keep both of the files in the Home folder of you, as its the default location. To check the availabilty of the files you can use the command

ls -l

It will shows the list of the files at that location.



Step 4: Then try to install the jdk file using the command

sh jdk-6u21-linux-i586.bin

Step 5: The to install Netbeans, at first make the file executable using the command

sudo chmod +x netbeans-*

Step 6: Then use the command, to install netbeans as

sudo ./netbeans-* --javahome jdk1.6.0_21

for me, it was
sudo ./netbeans-* --javahome jdk1.6.0_21

Step 7: The above command will provide the Netbeans installer to navigate your for the further steps to follow.



After installing, to use netbeans You can use it from Applications -> Programming -> NetBeans & from ubuntu menubar. But sometimes it may occurs problem to you(i.e this may not be appeared at the menu). Then you can use it by command prompt using the command

netbeans


to do so you need to run a simple command just for once after:

ln -s /usr/local/netbeans-6.5/bin/netbeans /usr/local/bin/netbeans

Use sudo before each command if you get the access denied message. Then giving correct password, you will be able to do so.(sudo------------> Super Do)

Then the command will be as

sudo ln -s /usr/local/netbeans-7.0/bin/netbeans /usr/local/bin/netbeans


The above command will make a shortcut at bin folder(common).
After that you will get netbeans just by typing it in the terminal. You may aslo create a shortcut launcher to this link.

Now enjoy Netbeans and Ubuntu together.

Plz let me know your experience..

Saturday, January 29, 2011

AJAX with ASP.NET

Imagine, you want to highlight a TextBox when the user moves the mouse over it. With the postback approach, you’d need to send the entire page back to the web server, regenerate it, and refresh it in the browser—by which point the mouse might be somewhere completely different. This approach is clearly impractical.

Ajax(Asynchronous JavaScript and XML)is programming shorthand for a set of techniques that create more responsive, dynamic pages. One of the hallmarks of Ajax is the ability to refresh part of the page while leaving the rest untouched.Ajax is nothing but JavaScript code that runs in the browser, requesting the new information from the web server when needed and updating the page accordingly.

The key benefit of Ajax is responsiveness, where as the challenges are code complexity and browser support.

TO use AJAX in ASP.net, we need to place a new web control ScriptManager on our page, and it’s the brains of ASP.NET AJAX .

If you’re using ASP.NET AJAX features throughout your website, you might choose to place the ScriptManager in a master page. However, this can occasionally cause problems, because different content pages may want to configure the properties of the ScriptManager differently. In this scenario, the solution is to use the ScriptManager in the master page and the ScriptManagerProxy in your content page. (You can find the ScriptManagerProxy on the same AJAX Extensions tab of the Toolbox.) Each content page can configure the ScriptManagerProxy control in the same way it would configure the ScriptManager.


All the elements and controls are kept between the tags.
When the UpdatePanel renders itself, it copies the content from the ContentTemplate into the page. This seems like a fairly unimportant low-level detail, but it does have one important side effect. If you want to use code to dynamically add controls to an UpdatePanel, you can’t use the UpdatePanel.Controls collection. Instead, you need to add new controls to the UpdatePanels.ContentTemplateContainer.Controls collection.

Friday, January 28, 2011

Registering the ASP.NET File Mappings: To run asp pages in IIS server

When a page is requested from the browser, that comes to the web server. The pages can be of different format i.e html, jsp, asp etc. The server is not the master of all for serving all types of pages.
At this point, one might be wondering how the web server knows when it needs to get the ASP or ASP.NET engine involved. Essentially, the web server looks at the file extension of the requested page (such as .asp or .aspx) to determine the type of content. The web server compares this extension against a list to determine what program owns this file type. For example, the web server’s list indicates that the .aspx extension is owned by the aspnet_isapi.dll component in the corresponding directory. The aspnet_isapi.dll component is known as an ISAPI extension, because it uses the ISAPI (Internet Server API) model to plug into the web server.

The easiest way to make sure you get the right version of aspnet_regiis is to rely on the Visual Studio Command Prompt. The Visual Studio Command Prompt is really just an ordinary Windows command prompt, but it sets the path variable so that the tools you need are at your fingertips. When you type aspnet_regiis.exe in the Visual Studio Command Prompt (without specifying a path), you’ll automatically run the correct version.
To start the Visual Studio Command Prompt, open the Start menu, choose Programs, and then choose Microsoft Visual Studio 2008 -->Visual Studio Tools -->Visual Studio 2008 Command Prompt.

Then for installing type the following
aspnet_regiis.exe -i


and then press enter.

If IIS is installed before installing Visual Studio, IIS is automatically configured for serving ASP pages by using asp engine. If not, then use the above code for configuring.

Monday, January 24, 2011

Add Date picker to ASP page from AjaxControlToolkit

Atfirst make a folder named i.e "Library" in your project folder. Then go to the References of Solution Explorer.

And Right Click-->Add References-->Select Browse--> Select the file from the location--> Add it.
Then add the text box, the target of the Selected Date. And also take a button or image by clicking which we will get our Calender.

The add the following code after the code of Button in the source view of the Form.

asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtBoxName" PopupButtonID="btnName"
Format="dd-MMM-yyyy"/>

Here the Format is used to define the format of your desired date to view.
After that, go to the next line of the FORM tag in your page. If you are using the Master Page as the part of your design. You will have to go to the FORM tag of your master page.Now you will have to add ScriptManager. For doing so, you will add the following line:


asp:ScriptManager ID="ScriptManager1" runat="server"/>


That's enough. You will get the Calender to pick the date.


IN this topic we have used code, but you can get this tool automatically from the Html portion of Toolbox menu. For doing so, you will have to Right Click on the lower part of Toolbox and then add the AjaxControlTool.dll from your made Library Folder. Then you will get these items from the Toolbox menu.


Click to get AjaxControlTool

Sunday, January 23, 2011

How to apply a Master Page to Existing Webpage OR Easily convert An Existing Web Form to a Web Content Form(with a Master Page)

Its our common behavior to change our web site on sparkle of our eyes. And for adding the banner or common things in each page is really difficult to perform. Concept of Master Page has handed over the freedom to us. For master page is the natural way to develop each web pages as the content page of the Master One. But We can ad our already
designed web page as the content page of the Master Page. Different way to say, we can apply Master Page o an existing Web page by following some steps.To convert from a Web Form to Web Content Form, all of the changes will occur in the Web Form’s aspx page.
just follow the following steps:

1.Create a Master Page
2.Apply Master Page via design mode in existing wen page
3.Copy over the Content Containers
4.In your Web Form, move Web Controls and information into the proper Content Containers.

Suppose, we have a web page named frmAddTask.aspx, we want to add the Master Page to this page. A s the part of above steps, we create the Master Page.
Then we need to go to the Design mode of our Web page frmAddTask.aspx, making the right-click we have to choose the properties for this page. From the properties, we select the Master Page option and show the Master Page we have created for this web page. Then in the code of the web page a small but vast change will be effected at the top line of its code view.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="frmAddTask.aspx.cs" Inherits="SMS_IB_Support_tools.UI.frmAddTask" MasterPageFile="~/UI/SMS-IB.Master" %>


Now, the second and final step is to put items into the correct content boxes. The easiest and more error free to do this is to create a new blank Web Content Form, copy the content boxes from the Web Content Page, and paste them into our original Web Form. So right click the Master page in the Solution Explorer and select Add Content Page. Our example will output:

<%@ Page Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" Title="Untitled Page" %>





Copy lines 2-5 above and paste them into frmAddTask.aspx right below the “<%@ Page” directive. The ContentPlaceHolderID called ContentPlaceHolder1 will hold all the information between
in our "frmAddTask.aspx. The rest of the information below can be deleted.
We will must have to follow that, in the existing Web Page FORM tag is appeared. And in the Master Page also the
tag is available. Both of them can not be applied at the same time. So we will have to awakened to use the FORM tag of the master page only. Otherwise, we will get error message.

SOLID Principle

In computer programming, SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Robert C. Martin in the early 2000s which stands for five basic patterns of object-oriented programming and design.




Single Responsibility Principle:
"There should never be more than one reason for a class to change."
If we have calculation logic and database logic and display logic all mixed up within one class it can be difficult to change one part without breaking others. Mixing responsibilities also makes the class harder to understand, harder to test, and increases the risk of duplicating logic in other parts of the design (decreases cohesion, functionality has no clear place to live).

Open Closed Principle:
"Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification."
The idea is that we can use OO techniques like inheritance and composition to change (or extend) the behaviour of a class, without modifying the class itself.Following the OCP should make behaviour easier to change, and also help us avoid breaking existing behaviour while making changes.

Liskov Substitution Principle:
"Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it."
It states that, if S is a subtype of T, then objects of type T in a computer program may be replaced with objects of type S (i.e., objects of type S may be substituted for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.).

Interface Segregation Principle:
"Clients should not be forced to depend upon interfaces that they do not use." The ISP is about keeping interfaces (both interface, and abstract class types of interfaces) small and limited only to a very specific need (a single responsibility even :)). If you have a fat interface then you are imposing a huge implementation burden on anyone that wants to adhere to that contract.

Dependency Inversion Principle:
"A. High level modules should not depend upon low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions."

The DIP says that if a class has dependencies on other classes, it should rely on the dependencies' interfaces rather than their concrete types. The idea is that we isolate our class behind a boundary formed by the abstractions it depends upon. If all the details behind those abstractions change then our class is still safe. This helps keep coupling low and makes our design easier to change.

Sunday, January 9, 2011

Gmail Modes

Many times, we are not able to access Gmail account from our PC for various reason. And that can not be performed for various issues. We can follow the modes depicted below for getting help on requirements.

Gmail Modes


If you can't access Gmail, try some of these URLs:

Safe mode - http://mail.google.com/mail/?labs=0. It disables the experimental features from Gmail Labs, just in case some of them are buggy. You can remove some of the features from Gmail's settings page.

Secure mode - https://mail.google.com/. It encrypts the traffic between your computer and Gmail's servers. Use it from public computers, Wi-Fi networks or to bypass some proxies and web accelerators. There's a Gmail setting that redirects the standard version to the secure mode ("Always use https").

Older version - http://mail.google.com/mail/?ui=1. This version has been replaced in October 2007 by a rearchitectured Gmail, but the old version is a little bit faster.

Basic mode - http://mail.google.com/mail/?ui=html. It's the version that doesn't use JavaScript, so it loads faster and it works well with older browsers. Unfortunately, many Gmail features are missing (contacts autocomplete, chat, spell checker, rich formatting) and each click loads a new page. If you like this version, click on "Set basic HTML as default view" at the top of the page.

Mobile mode - http://mail.google.com/mail/?ui=mobile or http://m.gmail.com. This is a simplified Gmail interface for mobile phones that has even less feature than the basic mode. Use it if no other Gmail mode works for you.

iPhone mode - http://mail.google.com/mail/x/gdlakb-/gp/. A more user-friendly mobile version for iPhone and other mobile phones that use WebKit-based browsers.

iGoogle gadget - http://www.google.com/ig/gmailmax. This is the canvas view for the updated Gmail gadget which can be found in the new iGoogle. Some people found that this interface bypasses most corporate filters that prevent them from accessing Gmail at work.

"No browser checking" mode - http://mail.google.com/mail?nocheckbrowser. If you use a cutting-edge new browser and Gmail serves you the basic HTML mode, try this URL to bypass browser detection.