Why DB connections are not written directly in JSP’s?


The main purpose of JSP is to separate the business logic & presentation logic. DB connections deal with pure java code. If write this kind of code in JSP, servlet container converts the JSP to servlet using JSP compiler which is the time consuming process so this is better to write code which deals with DB connections, Authentication and Authorization etc. in the java bean and use the <jsp:bean> tag to perform the action

Difference between and tags?


Both forward and include are action tags, below are their differences

  • jsp:forward redirects the servlet Request and Servlet Response to another resource specified in the tag. The path of the resource is ‘relative path’. The output generated by current JSP will be discarded.
  • jsp:include processes the resource as part of the current jsp. It include the output generated by resource, which is specified in the Tag to the current JSP

In both the cases single Request process multiple resources.

What is a singleton class?How do you writer it? Tell examples?


A class which must create only one object (ie. One instance) irrespective of any number of object creations based on that class.

Steps to develop single ton class:-

1.Create a Private construcor, so that outside class can not access this constructor. And declare a private static reference of same class

2.Write a public Factory method which creates an object. Assign this object to private static Reference and return the object

Sample Code:-

class SingleTon

{

private static SingleTon st=null;

private SingleTon()

{

System.out.println(“\nIn constructor”);

}

public static SingleTon stfactory()

{

if(st==null) st=new SingleTon();

return st;

}

}

 

 

For complete Example of Singleton design pattern click here

Struts 2


The core features of the struts 2 framework:

  1. Pluggable framework architecture that allows request life cycles to be customized for each action.
  2. Flexible validation framework that allows validation rules to be decoupled from action code.
  3. Hierarchical approach to internationalization that simplifies localizing applications.
  4. Integrated dependency injection engine that manages component life cycle and dependencies. (By default, the framework utilizes Spring for dependency injection.)
  5. Modular configuration files that use packages and namespaces to simplify managing large projects with hundreds of actions.
  6. Java 5 annotations that reduce configuration overhead. (Java 1.4 is the minimum platform.)

Struts 2 request Processing:

Each and every request made using struts 2 framework fallows the same request processing as below:

  1. Initially the web browser requests for request. (Ex: /index.acion or /myreport.pdf .. etc)
  2. The filter dispatcher looks at the request and determines the appropriate action.
  3. The interceptors automatically apply common functionality to the request, like work flow, validation, and file upload handling.
  4. The action method executes, usually storing and/or retrieving information from a database.
  5. The request renders the output to the browser, be it HTML, images, pdf, or something else.

The features added in struts2 over the struts1:

  1. Programming the abstract classes instead of interfaces is one of the design problem of struts1 framework that has been resolved in struts2.
  2. Most of the struts2 classes are based on interfaces and most of its core interfaces are HTTP independent.
  3. Unlike ActionForwards, Struts2 results provide flexibility to create multiple type of outputs.
  4. Actions in struts1 have dependencies on the servlet API since HttpServlertRequest and HttpServletResponse objects are passed to the execute() Method. But in struts2 any Java class with execute() method can be used as an Action Class. Actions to be neutral to the underlying framework
  5. ActionForms feature is no more known to the struts2 framework. Simple Java Bean flavored actions are used to put properties directly.
  6. Struts2 actions are HTTP independent and framework neutral. This enables to test struts2 applications very easily with out resorting mock objects.
  7. Struts2 tags enables to add style sheet driven markup capabilities.  ie. You can create consistent pages with less code. Struts2 tag markup can be altered by changing an underlying stylesheet.
  8. Struts tags are more capable and result oriented.
  9. Both JSP and Free maker tags are fully supported.
  10. Java 5 annotations can be used as an alternative to XML and Java properties configuration.
  11. Struts 2 check boxes do not require special handling for false values.
  12. Many changes can be done on fly without restarting the web container.
  13. Struts1 lets to customize the request processor per module. Struts2 lets to customize request handling per action if desired.
  14. Struts 2 Actions are spring aware. Just need to add spring beens.
  15. Struts2 extensions can be added by dropping in jar. No need of any addition XML or properties files. Metadata is expressed through convention and annotations.

Ajax support in Struts2:

  1. AJAX client side validation
  2. Remote form submission support (works with the submit tag as well)
  3. An advanced div template that provides dynamic reloading of partial HTML
  4. An advanced template that provides the ability to load and evaluate JavaScript remotely
  5. An AJAX-only tabbed Panel implementation
  6. A rich pub-sub event model
  7. Interactive auto complete tag

Struts1 and Struts2 at a glance:

Struts 1 vs. Struts 2

  1. Action                                    Action
  2. ActionForm                        Action or POJO
  3. ActionForward                  Result
  4. struts-config.xml              struts.xml
  5. ActionServlet                     FilterDispatcher
  6. RequestProcessor             Interceptors
  7. validation.xml                    Action-validation.xml

JavaMail API usage


  • Below program consits of Steps to send email using javax.mail
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestMail {
public static void main(String args[]) throws Exception {
String host = "localhost";
String from = "nani@gmail.com";
String to = "nani@gmail.com";
String user = "mallik";
String password = "mallik";
String content = "Change your password.";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session =Session.getDefaultInstance(properties);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail");
message.setText(content);

Transport.send(message);
System.out.println("Message Send Successfully..." + content);

}
}
  • Below program consits of Steps to reading email using javax.mail
import java.io.*;
import java.util.*;
import javax.mail.*;

public class ReadMail {
public static void main(String args[]) throws Exception {
String host = "localhost";
String user = "nani";
String password = "nani";
Properties properties = System.getProperties();
Session session = Session.getDefaultInstance (properties);
Store store = session.getStore("pop3");
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);

Message[] message = folder.getMessages();

for (int i = 0; i < message.length; i++) {
System.out.println("----- Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i]. getSentDate());
System.out.println("From : " + message[i]. getFrom()[0]);
System.out.println("Subject : " + message[i]. getSubject());
System.out.print("Message : ");
InputStream stream = message[i]. getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
}
folder.close(true);
store.close();
}
}
  • Below program consits of Steps to sending email with attachment using javax.mail
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class AttachExample {
public static void main (String args[]) throws Exception {
String host = "localhost";
String from = "nani@gmail.com";
String to[] = new String[]{"nani@gmail.com","gopikanthk"};
String filename = "testAttach.txt";
// Get system properties
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
System.out.println(session.getProperties());
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));

InternetAddress[] toAddress = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++){
toAddress[i] = new InternetAddress(to[i]);
System.out.println("to address are--------"+toAddress[i]);
}
message.setRecipients(Message.RecipientType.TO, toAddress);
String a=null;
System.out.println("recipent type to----");
message.setSubject("Hello JavaMail Attachment");
System.out.println("After the subject---------");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("Here's the file");
System.out.println("After the content of the message----");
Multipart multipart = new MimeMultipart();

multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();

DataSource source = new FileDataSource(filename);

messageBodyPart.setDataHandler(new DataHandler(source));
System.out.println("After the data handler----");
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
try{
  System.out.println("In try block-------");
  Transport.send(message);
  System.out.println("messages sent successfully.........");
} catch(SendFailedException sfe) {
  message.setRecipients(Message.RecipientType.TO, sfe.getValidUnsentAddresses());
  Transport.send(message);
}
}
}

Log4j


→ Log4j has three main components: loggers, appenders and layouts. These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.

→ Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule:

Named Hierarchy :

A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

→ For example, the logger named “com.foo” is a parent of the logger named “com.foo.Bar”. Similarly, “java” is a parent of “java.util” and an ancestor of “java.util.Vector”. This naming scheme should be familiar to most developers.
The root logger resides at the top of the logger hierarchy. It is exceptional in two ways:
1.it always exists,
2.it cannot be retrieved by name.

Invoking the class static Logger.getRootLogger method retrieves it. All other loggers are instantiated and retrieved with the class static Logger.getLogger method. This method takes the name of the desired logger as a parameter. Some of the basic methods in the Logger class are listed below.

package org.apache.log4j;

public class Logger {

// Creation & retrieval methods:
public static Logger getRootLogger();
public static Logger getLogger(String name);

// printing methods:
public void trace(Object message);
public void debug(Object message);
public void info(Object message);
public void warn(Object message);
public void error(Object message);
public void fatal(Object message);

// generic printing method:
public void log(Level l, Object message);
}

Loggers may be assigned levels. The set of possible levels, that is:

TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

Logging requests are made by invoking one of the printing methods of a logger instance. These printing methods are debug, info, warn, error, fatal and log.

A logging request is said to be enabled if its level is higher than or equal to the level of its logger. Otherwise, the request is said to be disabled. A logger without an assigned level will inherit one from the hierarchy. This rule is summarized below.

Basic Selection Rule
A log request of level p in a logger with (either assigned or inherited, whichever is appropriate) level q, is enabled if p >= q.

This rule is at the heart of log4j. It assumes that levels are ordered. For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL.

Configuration of the log4j environment is typically done at application initialization. The preferred way is by reading a configuration file.

AJAX


What is Ajax?
Asynchronous JavaScript and XML.
Ajax is not a new programming language but a new way to use existing standards.

Basic requirements to learn Ajax:
HTML or XHTML and Java Script.

Ajax applications are browser and platform independent.
Advantages:
These applications make the user to communicate asynchronously between browser and server.

With AJAX, a JavaScript can communicate directly with the server, with the XMLHttpRequest object. With this object, a JavaScript can trade data with a web server, without reloading the page.

AJAX uses asynchronous data transfer (HTTP requests) between the browser and the web server, allowing web pages to request small bits of information from the server instead of whole pages.

The AJAX technique makes Internet applications smaller, faster and more user-friendly.