Tuesday, 25 February 2014

Calling Javascript method from Java class

We can also call javascript method from Java file .

1. First create a JS file
    Now lets create a js file myJS.js and put below line in the file

var functionDemo = function() { return "hello user"; };

and save this file in C drive (You can save it in any directory but you have to mention it in the java file)

2. Create a java class which will call this method

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class JavascriptFunctionCallingFromJava {    

    public static void main(String[] args)
            throws ScriptException, NoSuchMethodException {
    String jsString=null;
    try {
InputStreamReader fd=new FileReader("C:\\myJS.js");
BufferedReader br=new BufferedReader(fd);
try {
jsString=br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} catch (FileNotFoundException e) {
e.printStackTrace();
}
        ScriptEngine se = new ScriptEngineManager().getEngineByName("javascript");        // Retrieving the Javascript engine
        if ( Compilable.class.isAssignableFrom(se.getClass()) ) {
            Compilable c = (Compilable) se;
            CompiledScript cs = c.compile(jsString);//We can compile javascript
            cs.eval();
        } else {
            se.eval(jsString);
        }
        if ( Invocable.class.isAssignableFrom(se.getClass()) ) {
            Invocable i = (Invocable) se;
            System.out.println("What our functionDemo in myJS.js returns is:"
                + i.invokeFunction("functionDemo"));
        } else {
            System.out.println( "calling method not supported");
        }
    }
}

Output :
What our functionDemo in myJS.js returns is:hello


Monday, 24 February 2014

First web application in Struts 2

Hi all, as we all know that usually first application is HelloWorld. So lets make our first web  application in Struts 2 .

So the requirements before creating the web application are given below

1. Eclipse
2. Tomcat
3. Struts library files.

Steps for creating web application in struts 2 using Eclipse is given below:

1. Create dynamic web project :-
                                                       Launch Eclipse, and select menu item  File-> New-> Dynamic Web Project.

1.a. Enter Project Name MyFirstStrutsApp


                                                      
and click Finish button.

2. Add Struts jar files in WEB-INF/lib folder.
                                                                          we need some jar files for making the application which are given below:

commons-fileupload-2.x.x.jar
commons-io-2.x.x.jar
commons-lang-2.x.x.jar
freemarker-2.x.x.jar
ognl-2.x.x
struts2-core-2.x.x.jar
xwork-core-2.x.x.jar

3.Change web.xml 
                               Add controller filter in web.xml file so it can handle all the request .

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MyFirstStrutsApp</display-name>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

</web-app>

4. Create index.jsp file under WEB-INF folder

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<s:set name="theme" value="'simple'" scope="page" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <s:form action="HelloWorld" >
            <s:submit/>            
        </s:form>
    </body>
</html>

5. Create success.jsp 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello World</title>
    </head>
    <body>
        <h1><s:property value="message" /></h1>
    </body>
</html>

6.Create struts.xml in src folder

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
    <action name="HelloWorld" class="com.techArcher.HelloWorld" >
<result>JSP/success.jsp</result>
        </action>
    </package>
</struts>


7. Now create HelloWorld Action class in com.techArcher package







HelloWorld.java

package com.techArcher;

public class HelloWorld {
private String message;
public String execute()
{
message="Hello User";
return "success";
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

8.Now start the server

and enter 
http://localhost:8080/MyFirstStrutsApp/HelloWorld.action






Friday, 21 February 2014

Struts include element

So here in struts configuration file we have a <include> element which is used to make this file easier to maintain for large applications.
It is advisable to divide in smaller files and use <include> element .
We use this element to reference the file and these each file will ideally include
1.doctype
2.Package and struts root element.

<struts>     
<include file="struts1.xml" />
<include file="struts2.xml" />
<include file="struts3.xml" />
</struts>

So each included file should include a package ,
valid doctype.

Wednesday, 19 February 2014

what is struts configuration file(struts.xml) ?

Struts Configuration Files

A Struts application uses a number of configuration files but the primary two are :-
1.struts.xml 
2.struts.properties.

In struts.xml you define all aspects of your application
  • Actions
  • Interceptors for each action.
  • Possible results for each action.
Interceptors and result types used in an action must be registered before they can be used.

Struts configuration files support inheritance and default configuration files are included in the struts2-core- VERSION.jar file.

struts-default.xml
                              It is default configuration file,which registers some default interceptors and result types, So you dont need to register them again and again for each action in your struts.xml file which makes it clean and short.

default.properties
                               The default.properties file, packaged in the same JAR, contains settings that apply to all Struts applications. As a result, unless you need to override the default values, you don't need to have a struts.properties file. Let's now look at struts.xml and struts.properties in more detail.

The struts.xml File

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 ... 
</struts>

here <struts> is root element, there are many other element which comes between <struts> and </struts>

About package Element is Struts ?

The package Element

All the actions are grouped into packages(modules) because Struts has been designed with modularity in mind. A typical struts.xml file can have one or many packages: 

<struts> 
<package name="package-1" namespace="namespace-1" extends="struts-default"> 
<action name="..."/>
<action name="..."/>
 ...
</package> 
<package name="package-2" namespace="namespace-2"  extends="struts-default">
<action name="..."/> 
<action name="..."/> 
... 
</package>
 ... 
<package name="package-n" namespace="namespace-n" extends="struts-default">
<action name="..."/>
<action name="..."/>
 ... 
</package>
</struts>

Attribute                                Mandatory                         Default Value
  name                                      Yes                                     ___
  namespace                             No                                     "/"
  extends                                  No(but important)             ___(but usually struts-default)

Note:-
If the namespace attribute has a non-default value:-
* Then namespace must be added to the URI that invokes the actions in the package.
For example, with default namespace, URI is as below 
/context/actionName.action

but with non-default namespace, URI is 
/context/namespace/actionName.action

**  A package element almost always extends the struts-default package defined in struts-default.xml.
 By doing so, all actions in the package can use the result types and interceptors registered in struts-default.xml.

Why filter is used as Dispatcher or Controller?

In Struts FilterDispatcher is used as a common controller,As filters have also life cycle method similar to those of Servlets.

These are life cycle methods of a filter.
  •  init. Called once by the web container just before the filter is put into service.
  •  doFilter. Called by the web container each time it receives a request with a URL that matches the filter's URL Pattern
  • destroy. Called by the web container before the filter is taken out of service, i.e. when the application is shut down.
With a filter you can conveniently choose to serve all the resources in your application, including static ones. With a servlet, your controller only handles access to the dynamic part of the application.

Note that the url-pattern element in the web.xml file :
<servlet> 
<servlet-name>Controller</servlet-name> 
<servlet-class>...</servlet-class> 
</servlet>
 <servlet-mapping> 
<servlet-name>Controller</servlet-name>
 <url-pattern>*.action</url-pattern> 
</servlet-mapping>

With such a setting, requests for static resources are not handled by the servlet controller, but by the container. You wouldn't want to handle static resources in your servlet controller because that would mean extra work.

A filter is different. A filter can opt to let through requests for static contents. To pass on a request, call the filterChain.doFilter method in the filter's doFilter method.

Consequently, employing a filter as the controller allows you to block all requests to the application, including request for static contents. You will then have the following setting in your deployment descriptor:

 <filter> 
<filter-name>filterDispatcher</filter-name>
 <filter-class>...</filter-class> 
</filter> 
<filter-mapping>
 <filter-name>filterDispatcher</filter-name>
 <url-pattern>/*</url-pattern> 
</filter-mapping>

What is the advantage of being able to block static requests? One thing for sure, you can easily protect your static files from curious eyes.
 The following code will send an error message if a user tries to view a JavaScript file:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
HttpServletRequest req = (HttpServletRequest) request; 
HttpServletResponse res = (HttpServletResponse) response; 
String uri = req.getRequestURI(); 
if (uri.indexOf("/css/") != -1 && req.getHeader("referer") == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN);
 } 
else { // handle this request }}

It will not protect your code from the most determined people, but users can no longer type in the URL of your static file to view it. By the same token, you can protect your images so that no one can link to them at your expense.


Back to Struts home

How Struts Works?

The following events happen when the Client browser issues an HTTP request.
The ActionServlet receives the request.
The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.



When the ActionServlet receives the request it does the following tasks.
Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
Decides which action class to invoke to process the request.
Validate the data entered by the user.
The action class process the request with the help of the model component. The model interacts with the database and process the request.
After completing the request processing the Action class returns an ActionForward to the controller.
Based on the ActionForward the controller will invoke the appropriate view.
The HTTP response is rendered back to the user by the view component.

Why filter is used as a Controller not Servlet?

Back to Struts home

What is Struts framework?

Struts is a open source framework which make building of the web applications easier based on the java Servlet and JavaServer pages technologies.

Struts framework was created by Craig R. McClanahan and donated to the Apache Software Foundation in 2000. The Project now has several committers, and many developers are contributing to overall to the framework.

Developing web application using struts frame work is fairly complex, but it eases things after it is setup. It encourages software development following the MVC design pattern. Many web applications are JSP-only or Servlets-only. With JSP and Servlets, Java code is embedded in the HTML code and the Java code calls println methods to generate the HTML code respectively. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association.

Struts is based on Model-View-Controller (MVC) design paradigm, it is an implementation of JSP Model 2 Architecture. For more of Model-View-Controller (MVC) click here.

Consists of 8 Top-Level Packages and approx 250 Classes and Interfaces.

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. This definition implies that Struts is a framework, rather than a library, but Struts also contains an extensive tag library and utility classes that work independently of the framework.


Struts MVC Architecture

Controller

The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations.The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.

Model

A model represents an applicationç—´ data and contains the logic for accessing and manipulating that data. Any data that is part of the persistent state of the application should reside in the model objects. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. Model services are accessed by the controller for either querying or effecting a change in the model state. The model notifies the view when a state change occurs in the model.The JSP file reads information from the ActionForm bean using JSP tags.

View

The view is responsible for rendering the state of the model. The presentation semantics are encapsulated within the view, therefore model data can be adapted for several different kinds of clients.The view modifies itself when a change in the model is communicated to the view. A view forwards user input to the controller.The view is simply a JSP file. There is no flow logic, no business logic, and no model information.

Back to Struts home 

Tuesday, 18 February 2014

Why Model 2 is preferred over Model 1?

When JSP was introduced and after a huge success it was thought to be the end of servlets. But JSP did not displace the Servlets.

Actually today real world application are using Servlets as well as JSPs .So why still Servlets are used not obsolete after arrival of JSPs. So lets understand the two design Models upon which you can build your Java Web Application.


First design model is called Model 1,introduced after the invention of JSP ,Servlets are not normally used in this model.
Navigating from one JSP to another is done by clicking a link on the page


The second design model is named Model 2. You will learn shortly why Model 1 is not recommended and why Model 2 is the way to go.

The Problems with Model 1


Model 1 applications have a series of JSPs where the user navigates from one page to another. This is the model you employ when you first learn JSP because it is simple and easy.
  • The Model 1 design model is page-centric.
  •  The main trouble with Model 1 applications is that they are hard to maintain and inflexible.
  •  This architecture does not promote the division of labor between the page designer and the web developer because the developer is involved in both page authoring and business logic coding.
  • Navigation problem. If you change the name of a JSP that is referenced by other pages, you must change the name in many locations.
  •  There is more temptation to use scriptlets in JSPs because JavaBeans are limited and custom tags are hard to write. However, as explained above, mixing Java code and HTML in JSPs is a bad thing
  •  If you can discipline yourself to not write Java code in JSPs, you'll end up spending more time developing your application because you have to write custom tags for most of your business logic. It's faster to write Java code in Java classes.

Model 2


The second design model is simply called Model 2. This is the recommended architecture to base your Java web applications on. Model 2 is another name for the Model-View-Controller (MVC) design pattern. In Model 2, there are three main components in an application: the model, the view, and the controller.
Note:-The term Model 2 was first used in the JavaServer Pages Specification version 0.92.
In Model 2, you have one entry point for all pages and usually a servlet or a filter acts as the main controller and JSPs are used as presentation. 
Compared to Model 1 applications, Model 2 applications enjoy the following benefits.
• more rapid to build
• easier to test
• easier to maintain
• easier to extend

Back to Struts home

Why Servlet and JSP were not good enough for Java Web application?

Some reasons for developement of MVC Framework


Introduction to Servlet

Servlet technology and JavaServer Pages (JSP) are the main technologies for developing Java web applications.
In 1996 , When Servlet was introduced by Sun Microsystems , Servlet technology was considered superior to the reigning Common Gateway Interface (CGI) because servlets stay in memory after responding to the first requests so no re-instantiation  is required and hence better response time as compared to CGI.

Problem with servlet


The problem with servlets is it is very cumbersome and error-prone to send HTML tags to the browser because HTML output must be enclosed in Strings, like in the following code. 

PrintWriter out = response.getWriter(); 
out.println("<html><head><title>Testing</title></head>"); 
out.println("<body style=\"background:#ffdddd\">"); ...

This is hard to program. Even small changes in the presentation, such as a change to the background color, will require the servlet to be recompiled.


Introduction of JSP

So sun introduce JSP(Java Server Pages),which allows Java code and HTML tags to intertwine in easy to edit pages.

Changes in HTML output require no recompilation. 

A Java code fragment in a JSP is called a scriptlet.
Even though mixing scriptlets and HTML seems practical at first thought, it is actually a bad idea for the following reasons:






Problem with JSP

• Interweaving scriptlets and HTML results in hard to read and hard to maintain applications.
• Writing code in JSPs diminishes the opportunity to reuse the code. 
•  Of course, you can put all Java methods in a JSP and include this page from other JSPs that need to use the methods. However, by doing so you're moving away from the object-oriented paradigm. For one thing, you will lose the power of inheritance.
• It is harder to write Java code in a JSP than to do it in a Java class. Let's face it, your IDE is designed to analyze Java code in Java classes, not in JSPs.
• It is easier to debug code if it is in a Java class.
• It is easier to test business logic that is encapsulated in a Java class.
• Java code in Java classes is easier to refactor.

In fact, separation of business logic (Java code) and presentation (HTML tags) is such an important issue.

Tuesday, 4 February 2014

What are daemon Threads in java??

Daemon Thread:-
                            There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM termintates this thread automatically.


lets discuss this with an example....

public class UserThreadClass{

    public static void main(String[] args) {
        new DaemonThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }

}
class DaemonThread extends Thread {

    public DaemonThread() {
        setDaemon(true) ;   // When false, (i.e. when it's a user thread),
                // the Daemon  thread continues to run.
                // When true, (i.e. when it's a daemon thread),
                // the Daemon thread terminates when the main 
                // thread terminates.
    }

    public void run() {
        int count=0 ;
        while (count<5) {
            System.out.println("Hello from Daemon "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}

Try to run this program with setDaemon(true) and again with setDaemon(false) in both cases you will see the difference in execution.
when setDaemon is true then main thread will terminate when its all lines of code execution completed ,JVM also kill DaemonThread .

But when it is set to false, JVM will not terminate the Daemon thread till its run method executed completely.

Setup log4j with Struts 2 in eclipse

Apache log4j is a Java-based logging utility. It was originally written by Ceki Gülcü and is now a project of the Apache Software Foundation. log4j is one of several Java logging frameworks.

Steps for setting up log4j with Struts 2 are given below:

1. Download the log4j jar file from here .

2. Add log4j.jar into your project build path.

3. Add log4j.jar into your WEB-INF/lib folder.


4.Add log4j.properties into your classpath (e.i. where you put struts.xml).

and put below line of code in log4j.properties

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\logFile.txt
log4j.appender.file.MaxFileSize=10MB
# Set the the backup index
log4j.appender.file.MaxBackupIndex=10
# Set the append to false, should not overwrite
log4j.appender.file.Append=false
# Set the threshold to debug mode
log4j.appender.file.Threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

# Root logger option
log4j.rootLogger=DEBUG, file, stdout

5.Now you can use your Logger in your Action class

private static final Logger logger=Logger.getLogger(ClassName.class.getName());

log4j.appender.file.MaxFileSize=10MB  ggiviis used to create the logfile of 10MB after that another file will be automatically create if threshold exceeds , How many files can be created is configured via 
log4j.appender.file.MaxBackupIndex=10  so here total size is 10.

Sunday, 2 February 2014

Java coding questions

1. What would be the output of the below code....

public static void main(String[] args)
{
int i=0;
Integer wrapperInt=null;
i=wrapperInt;
System.out.println(i);
}
Please reply If you know you can reply... if not you can ask me...


2.Why we use this keyword in below code...

public class Demo{
private int a;
private int b;

Demo(int a,int b)
{
this.a=a;
this.b=b
}
}

Why we used this.a and this.b ?