Pages

Java Tutorials

Java Tutorials
Java Tutorials

Tuesday, 12 November 2013

Basic MVC Architecture

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:
·         Model - The lowest level of the pattern which is responsible for maintaining data.
·         View - This is responsible for displaying all or a portion of the data to the user.
·         Controller - Software Code that controls the interactions between the Model and View.
MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here the Controller receives all requests for the application and then works with the Model to prepare any data needed by the View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows.

The model

The model is responsible for managing the data of the application. It responds to the request from the view and it also responds to instructions from the controller to update itself.

The view

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

The controller

The controller is responsible for responding to user input and perform interactions on the data model objects. The controller receives the input, it validates the input and then performs the business operation that modifies the state of the data model.
Struts2 is a MVC based framework. In the coming chapters, let us see how we can use the MVC methodology within Struts2.


Struts 2 Architecture
From a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-View-Controller pattern in Struts2 is realized with following five core components:
·         Actions
·         Interceptors
·         Value Stack / OGNL
·         Results / Result types
·         View technologies
Struts 2 is slightly different from a traditional MVC framework in that the action takes the role of the model rather than the controller, although there is some overlap.
The above diagram depicts the Model, View and Controller to the Struts2 high level architecture. The controller is implemented with a Struts2 dispatch servlet filter as well as interceptors, the model is implemented with actions, and the view as a combination of result types and results. The value stack and OGNL provide common thread, linking and enabling integration between the other components.
Apart from the above components, there will be a lot of information that relates to configuration. Configuration for the web application, as well as configuration for actions, interceptors, results, etc.
This is the architectural overview of the Struts 2 MVC pattern. We will go through each component in more detail in the subsequent chapters.

Request life cycle:

Based on the above digram, one can explain the user's request life cycle in Struts 2 as follows:
·         User sends a request to the server for requesting for some resource (i.e pages).
·         The FilterDispatcher looks at the request and then determines the appropriate Action.
·         Configured interceptors functionalities applies such as validation, file upload etc.
·         Selected action is executed to perform the requested operation.
·         Again, configured interceptors are applied to do any post-processing if required.
·         Finally the result is prepared by the view and returns the result to the user.

Struts 2 Configuration Files

This chapter will take you through basic configuration required for a Struts 2 application. Here we will see what will be configured in few important configuration files : web.xml, struts.xml, struts-config.xml and struts.properties
Honestly speaking you can survive using web.xml and struts.xml configuration files and you have seen in previous chapter that our example worked using these two files, but for your knowledge let me explain other files as well.

The web.xml file:

The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container. It is not strictly a Struts2 configuration file, but it is a file that needs to be configured for Struts2 to work.
As discussed earlier, this file provides an entry point for any web application. The entry point of Struts2 application will be a filter defined in deployment descriptor (web.xml). Hence we will define an entry of FilterDispatcher class in web.xml. The web.xml file needs to be created under the folder WebContent/WEB-INF.
This is the first configuration file you will need to configure if you are starting without the aid of a template or tool that generates it (such as Eclipse or Maven2). Following is the content of web.xml file which we used in our last example.
<?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_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
   
   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>
 
   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
 
</web-app>
Note that we map the Struts 2 filter to /*, and not to /*.action which means that all urls will be parsed by the struts filter. We will cover this when we will go through the Annotations chapter.

The struts.xml file:

The struts.xml file contains the configuration information that you will be modifying as actions are developed. This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes.
The first thing to note is the DOCTYPE. All struts configuration file need to have the correct doctype as shown in our little example. <struts> is the root tag element, under which we declare different packages using <package> tags. Here <package> allows separation and modularization of the configuration. This is very useful when you have a large project and project is divided into different modules.
Say, if your project has three domains - business_applicaiton, customer_application and staff_application, you could create three packages and store associated actions in the appropriate package. The package tag has the following attributes:
Attribute
Description
name (required)
The unique identifier for the package
extends
Which package does this package extend from? By default, we use struts-default as the base package.
abstract
If marked true, the package is not available for end user consumption.
namesapce
Unique namespace for the actions
The constant tag along with name and value attributes will be used to override any of the following properties defined in default.properties, like we just set struts.devMode property. Setting struts.devMode property allows us to see more debug messages in the log file.
We define action tags corresponds to every URL we want to access and we define a class with execute() method which will be accessed whenever we will access corresponding URL.
Results determine what gets returned to the browser after an action is executed. The string returned from the action should be the name of a result. Results are configured per-action as above, or as a "global" result, available to every action in a package. Results have optional name and type attributes. The default name value is "success".
Struts.xml file can grow big over time and so breaking it by packages is one way of modularizing it, but struts offers another way to modularize the struts.xml file. You could split the file into multiple xml files and import them in the following fashion.
The other configuration file that we haven't covered is the struts-default.xml. This file contains the standard configuration settings for Struts and you would not have to touch these settings for 99.99% of your projects. For this reason, we are not going into too much detail on this file. If you are interested, take a look into the at the default.properties file available in struts2-core-2.2.3.jar file.

The struts-config.xml file:

The struts-config.xml configuration file is a link between the View and Model components in the Web Client but you would not have to touch these settings for 99.99% of your projects. The configuration file basically contains following main elements:
SN
Interceptor & Description
1
struts-config
This is the root node of the configuration file.
2
form-beans
This is where you map your ActionForm subclass to a name. You use this name as an alias for your ActionForm throughout the rest of the struts-config.xml file, and even on your JSP pages.
3
global forwards
This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This avoids hardcoding URLs on your web pages.
4
action-mappings
This is where you declare form handlers and they are also known as action mappings.
5
controller
This section configures Struts internals and rarely used in practical situations.
6
plug-in
This section tells Struts where to find your properties files, which contain prompts and error messages

The struts.properties file

This configuration file provides a mechanism to change the default behavior of the framework. Actually all of the properties contained within the struts.properties configuration file can also be configured in the web.xml using the init-param, as well using the constant tag in the struts.xml configuration file. But if you like to keep the things separate and more struts specific then you can create this file under the folder WEB-INF/classes.
The values configured in this file will override the default values configured in default.properties which is contained in the struts2-core-x.y.z.jar distribution. There are a couple of properties that you might consider changing using struts.properties file:


Thursday, 7 November 2013

Object Oriented Systems UPTU lab Assignment With Solution

OOPS Lab Assignment (ECS-354)

S.No.
Program
1.
 Write a program in java which prints your name using command line arguments.

class cmdarguments
{
        public static void main(String args[])
        {
                String str;
               
                  str=args[0];
                     
                        System.out.println("Your name is "+str);
                             
       }
}

2.
Write a program in java which enters three number using command line arguments and print sum and average of the number

class sumnavg
{
        public static void main(String args[])
        {
                int a,b,c,sum,avg;
               
                        a=Integer.parseInt(args[0]);
                        b=Integer.parseInt(args[1]);
                        c= Integer.parseInt(args[2]);
                                sum=a+b+c;
                                avg=sum/3;
                        System.out.println("sum is "+sum);
                                System.out.println("Average is "+avg);
        }
}






3.
Write a program in java which enter the number using DataInputStream and check whether the entered number is even or odd.

import java.io.*;
class oddeven
{
        public static void main(String args[])throws IOException
        {
                int a ;
                                DataInputStream d=new DataInputStream(System.in);
                                System.out.println("Enter the number");
                                a=Integer.parseInt(d.readLine());
                                if(a%2==0)
                                System.out.println("Number is even"+a);
                                else
                    System.out.println("Number is odd"+a);   
        }
}


4.
Write a Program in java which creates the array of size 5; find the sum and average of the five numbers.

import java.io.*;
class arraysumavg
{
        public static void main(String args[])throws IOException
        {
                int a[] =new int[5],sum=0 ;
                                DataInputStream d=new DataInputStream(System.in);
                                System.out.println("Enter the number in array");
                                for (int i=0;i<5;i++)
                                {
                                System.out.println("Enter the"+(i+1)+"number");          
                                a[i]=Integer.parseInt(d.readLine());
                                }
                                for (int i=0;i<5;i++)
                                {
                                               
                                sum=sum+a[i];
                                }
                                System.out.println("Sum of the number is"+sum);
                 System.out.println("Average of the number is"+sum/5);
                  
        }
}

5.
Write a program in java which input the String “Ajay Kumar Maurya” and checks whether the string ends with Maurya or not.

public class endstringtest{

   public static void main(String args[]){
      String Str = new String("Ajay Kumar Maurya");
      boolean retVal;

      retVal = Str.endsWith( "Maurya" );
      System.out.println("Returned Value = " + retVal );

     
   }
}

6.
Write a program in java which input the string “Ajay Kumar Maurya” and
       I.            Find the length of the string.
     II.            Check whether the string contains the substring “jay”.
  III.            Concatenate Mr at the starting of the name.(Mr. Ajay Kumar Maurya).

import java.io.*;

public class stringtest
{
   public static void main(String args[])
   {
      String Str = new String("Ajay Kumar Maurya");
      System.out.print("Length of the string is \t" );
      System.out.println(Str.length());
      System.out.print("Return Value :" );
      System.out.println(Str.matches("(.*)jay(.*)"));
      Str="Mr.".concat(Str);
      System.out.println("New string is "+Str);
   }
}

7.
Write a program in java which handles the runtime exception using try catch block.

class trycatch
{
        public static void main(String args[])
        {
                int a,b,c;
                try
                {
                        a=Integer.parseInt(args[0]);
                        b=Integer.parseInt(args[1]);
                        c=a/b;
                        System.out.println("result is "+c);
                }
                catch(Exception x1)
                {
                        System.out.println("pl check the data");
                        System.out.println("error type is "+x1.getMessage());                               
                }
                finally
                {
                        System.out.println("working with java");
                }
        }
}

8.
Write a program in java which creates a class name works having three methods input, sum and show. Create the object of the class and invoke the methods of the class on the created object

class works
{
        int a,b,c;
        void input()
        {
                a=30;
                b=33;
        }
        void sum()
        {
                c=a+b;
        }
        void show()
        {
                System.out.println("fist no "+a);
                System.out.println("second no "+b);
                System.out.println("sum no "+c);
        }
}
class democlass
{
        public static void main(String args[])
        {
                works x=new works();
                x.input();
                x.sum();
                x.show();
              
        }
}


9.
Write a program in java having class good1, class good2 extends good1 and good3 extends good2.Check that all the methods are accessible in inherited class.good1 having method data,good2 having method sum and good3 having method show.

class good1
{
        int a,b,c;
        void data()
        {
                a=30;
                b=33;
        }
}
class good2 extends good1
{
        void sum()
        {
                c=a+b;
        }
}
class good3 extends good2
{
        void show()
        {
                System.out.println("sum is "+c);
        }
        good3()
        {
                System.out.println("testing class in java");
        }
}
class p5
{
        public static void main(String args[])
        {
                good3 g=new good3();
                g.data();
                g.sum();
                g.show();

        }
}

10.
Write a Program in java to implement method overriding. 

import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI()
 {

JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);

frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {

{

createAndShowGUI();

};
}
}
11
Write a Program in Java to implement an interface.

interface Animal {

   public void eat();
   public void travel();
}
Save the above program as Animal.java and compile

public class Mammal implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   }

  

   public static void main(String args[]){
      Mammal m = new Mammal();
      m.eat();
      m.travel();
               
   }
}

12
Write a Program in Java to create a Swing Application Display your name using label.

import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI()
 {

JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Abhishek Kesharwani");
frame.getContentPane().add(label);

frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {

{

createAndShowGUI();

};
}
}
13
Write a Program in Java to create a user define Package.

package mypkg;
public class works
{
         int a,b,c;
        void input()
        {
                a=30;
                b=33;
        }
         void sum()
        {
                c=a+b;
        }
         void show()
        {
                System.out.println("fist no "+a);
                System.out.println("second no "+b);
                System.out.println("sum no "+c);
        }
}

import mypkg.*;
class packagedemo
{
public static void main(String [] args)
{
works x=new works();
x.input();
x.sum();
x.show();
}
}
14
Write a program in java which creates two threads, Main thread and Child Thread and print the even no using Main Thread and odd no using Child Thread.

// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
               
      start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 19; i > 0; i=i-2) {
            System.out.println("Child Thread: " + i);
                                                // Let the thread sleep for a while.
            Thread.sleep(2000);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}

public class demothread {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 20; i > 0; i=i-2) {
           
            System.out.println("Main Thread: " + i);
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting."); 
   }
}

15
Write a program in java which creates an Applet and display your name in an html page using that Applet.

import java.applet.*;
import java.awt.*;
public class web5 extends Applet
{
                public void paint(Graphics g)
                {
                                g.drawString("Shashank Bhushan Vimal",100,100);
                }
}

16
Write a program in java which creates an Applet and draw a rectangle inside the applet. Display that applet in an html page.

import java.applet.*;
import java.awt.*;
public class App extends Applet
{
                public void paint(Graphics g)
                {
                                g.drawString("Abhishek Kesharwani",100,100);
                                g.drawRect(0,0,400,400);
                               
                }
}
17
Write a program in java to create a dsn(Data Source Name) named ucer and database student in ms access contains table school having columns name and city. Save the value of name and city in the school database using JDBC.

import java.io.*;
import java.sql.*;
import java.sql.Connection.*;
import java.sql.PreparedStatement.*;
class save
{
        public static void main(String args[])
        {
                String n,c;
                Connection cn;
                PreparedStatement pst;
                                int x;
                try
                {
                                                InputStreamReader ir=new InputStreamReader(System.in);
                                                BufferedReader br=new BufferedReader(ir);
                                                System.out.println("enter name & city");
                                                n=br.readLine();
                                                c=br.readLine();


                                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                cn=DriverManager.getConnection("jdbc:odbc:ucer","","");

                pst=cn.prepareStatement("insert into school(name,city) values(?,?)");
                                                pst.setString(1,n);          
                                                pst.setString(2,c);           
                                                x=pst.executeUpdate();
                                                if(x==1)
                                                {
                                                                System.out.println("Record has been saved");
                                                }
                                               
                }
                catch(Exception xx)
                                {
                                                System.out.println("please check the data "+xx.getMessage());
                                }
        }
}

18
Write a program in java to create a dsn(Data Source Name)  named ucer and database student in ms access contains table school having columns name and city. Display the value of name and city in the school database using JDBC.

import java.io.*;
import java.sql.*;
import java.sql.Statement.*;
import java.sql.ResultSet.*;
class show
{
                public static void main(String args[])
                {
                                String n,c;
                                Connection cn;
                                Statement st;
                                ResultSet rs;
                                try         
                                {
                                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                cn=DriverManager.getConnection("jdbc:odbc:ucer","","");
                                st=cn.createStatement();
                                rs=st.executeQuery("select * from school");
                                while(rs.next())
                                {
                                                n=rs.getString(1);
                                                c=rs.getString(2);
                                                System.out.println("name "+n+" city "+c);
                                }

                                }
                                catch(Exception xx)
                                {
                                System.out.println("check data"+xx.getMessage());
                                }
                }
}

19
Write a program in java to create a dsn(Data Source Name)  named ucer and database student in ms access contains table school having columns name and city .Delete the particular value of name and city in the school database using JDBC.(take the value from the database)

import java.io.*;
import java.sql.*;
class del
{
                public static void main(String args[])
                {
                                String n;
                                int x;
                                Connection k;
                                PreparedStatement pp;
                                try         
                                {
                                n=args[0];
                                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                k=DriverManager.getConnection("jdbc:odbc:ucer","","");
                pp=k.prepareStatement("delete from school where name=?");
                                pp.setString(1,n);
                                x=pp.executeUpdate();
                                if(x==1)
                                {
                                                System.out.println("record has been deleted");
                                }
               
                                }
                                catch(Exception xx)
                                {
                                System.out.println("check data"+xx.getMessage());
                                }
                }
}


20
Write a program in java to implement Network programming using Socket and Server socket .Client send the number to Server and server return its square to the client.

Client Program

import java.net.*;
import java.io.*;
class Client
{
   public static void main(String []args)
   {
       Socket c;
       BufferedReader brc,brs;
       PrintWriter out;
       String msg;
       try
       {
           c=new Socket("127.0.0.1",2000);
        System.out.println("Connection Established");          
        out=new PrintWriter(c.getOutputStream(),true);
        brc=new BufferedReader(new InputStreamReader(c.getInputStream()));
        brs=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Connection Stream fetched");
      


         System.out.print("Enter Any Number ");
         msg=brs.readLine();
         out.println(msg);
         msg=brc.readLine();

        System.out.println("Message Received :"+msg);
        c.close();
       }catch(Exception e){}
   }
}

Server Program

import java.net.*;
import java.io.*;
class Server
{
  public static void main(String []args)
  {
      ServerSocket s;
     PrintWriter out;
     BufferedReader brc;
    Socket c;
    String msg;
    int a,b;
    try
    {
        s=new ServerSocket(2000);
        System.out.println("SERVER is UP and RUNNING");
for(int x=0;x<5;x++)
{
        c=s.accept();
        System.out.println("Connection Received");
        brc=new BufferedReader(new InputStreamReader(c.getInputStream()));
        out=new PrintWriter(c.getOutputStream(),true);
        System.out.println("Stream Fetched for R/W");
       

       msg=brc.readLine();
        System.out.println("Client Info Received");
       a=Integer.parseInt(msg);
       b=a*a;
       msg=String.valueOf(b);
       out.println(msg);

        System.out.println("Square of "+a +" has been sent to client");      
}
       s.close();
    }catch(Exception e){}
  }
}