Monday 23 May 2016

MVC Validations Framework

Create main page

Let us write main page JSP file index.jsp, which will be used to collect Employee related information mentioned above.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Employee Form</title>
</head>

<body>
   <s:form action="empinfo" method="post">
      <s:textfield name="name" label="Name" size="20" />
      <s:textfield name="age" label="Age" size="20" />
      <s:submit name="submit" label="Submit" align="center" />
   </s:form>
</body>
</html>
The index.jsp makes use of Struts tag, which we have not covered yet but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag.

Create Views

We will use JSP file success.jsp which will be invoked in case defined action returns SUCCESS.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success</title>
</head>
<body>
   Employee Information is captured successfully.
</body>
</html>

Create Action

So let us define a small action class Employee, and then add a method calledvalidate() as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed.
package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{
   private String name;
   private int age;
   
   public String execute() 
   {
       return SUCCESS;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }

   public void validate()
   {
      if (name == null || name.trim().equals(""))
      {
         addFieldError("name","The name is required");
      }
      if (age < 28 || age > 65)
      {
         addFieldError("age","Age must be in between 28 and 65");
      }
   }
}
As shown in the above example, the validation method checks whether the 'Name' field has a value or not. If no value has been supplied, we add a field error for the 'Name' field with a custom error message. Secondly, we check if entered value for 'Age' field is in between 28 and 65 or not, if this condition does not meet we add an error above the validated field.

Configuration Files

Finally, let us put everything together using the struts.xml configuration file as follows:
<?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>
   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="empinfo" 
         class="com.tutorialspoint.struts2.Employee"
         method="execute">
         <result name="input">/index.jsp</result>
         <result name="success">/success.jsp</result>
      </action>

   </package>

</struts>
Following is the content of web.xml file:
<?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>

Actions In mvc

Create Action

The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.
Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows:
public interface Action {
   public static final String SUCCESS = "success";
   public static final String NONE = "none";
   public static final String ERROR = "error";
   public static final String INPUT = "input";
   public static final String LOGIN = "login";
   public String execute() throws Exception;
}
Let us take a look at the action method in the Hello World example:
package com.tutorialspoint.struts2;

public class HelloWorldAction{
   private String name;

   public String execute() throws Exception {
      return "success";
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows:
package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      if ("SECRET".equals(name))
      {
         return SUCCESS;
      }else{
         return ERROR;  
      }
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}
In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string "SECRET", we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows:
<?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>
      <constant name="struts.devMode" value="true" />
      <package name="helloworld" extends="struts-default">
         <action name="hello" 
            class="com.tutorialspoint.struts2.HelloWorldAction"
            method="execute">
            <result name="success">/HelloWorld.jsp</result>
            <result name="error">/AccessDenied.jsp</result>
         </action>
      </package>
</struts>

Create a View

Let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File. This file will be called in case return result is SUCCESS which is a String constant "success" as defined in Action interface:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   Hello World, <s:property value="name"/>
</body>
</html>
Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant "error". Following is the content ofAccessDenied.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
   You are not authorized to view this page.
</body>
</html>
We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the execute method of the HelloWorldAction class and render the HelloWorld.jsp view.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h1>Hello World From Struts2</h1>
   <form action="hello">
      <label for="name">Please enter your name</label><br/>
      <input type="text" name="name"/>
      <input type="submit" value="Say Hello"/>
   </form>
</body>
</html>
That's it, there is no change required web.xml file, so let us use same web.xml which we had created in Examples chapter. Now we are ready to run our Hello World application using Struts 2 framework.

MVC Architecture

Struts MVC

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.

Wednesday 18 May 2016

Objective Mvc Interview Question And Ans


Question 1: What does MVC stand for>

Answer: Model-View-Controller.

Question 2: What are three main components or aspects of MVC?

Answer: Model-View-Controller

Question 3: Which namespace is used for ASP.NET MVC? Or which assembly is used to define the MVC framework?
Answer: System.Web.Mvc

Question 4: What is the default view engine in ASP.NET MVC?
Answer: Web Form(ASPX) and Razor View Engine.

Question 5: Can we remove the default View Engine?
Answer: Yes, by using the following code:

protected void Application_start()
{
       ViewEngines.Engines.Clear();
}

Question 6: Can we have a Custom View Engine?
Answer: Yes, by implementing the IViewEngine interface or by inheriting from the VirtualPathProviderViewEngine abstract class.

Question 7: Can we use a third-party View Engine?
Answer: Yes, ASP.NET MVC can have Spark, NHaml, NDjango, Hasic, Brail, Bellevue, Sharp Tiles, String Template, Wing Beats, SharpDOM and so on third-party View Engine.

Question 8: What are View Engines?
Answer: View Engines are responsible for rendering the HTML from your views to the browser.

Question 9: What is Razor Engine?
Answer: The Razor view engine is an advanced view engine from Microsoft, packaged with MVC 3. Razor uses an @ character instead of aspx's <% %> and Razor does not require you to explicitly close the code-block.

Question 10: What is scaffolding?
Answer: Quickly generating a basic outline of your software that you can then edit and customize.

Question 11: What is the name of Nuget scaffolding package for ASP.NET MVC3 scaffolding?
Answer: MvcScaffolding

Question 12: Can we share a view across multiple controllers?
Answer: Yes, it is possible to share a view across multiple controllers by putting a view into the shared folder.

Question 13: What is unit testing?
Answer: The testing of every smallest testable block of code in an automated manner. Automation makes things more accurate, faster and reusable.

Question 14: Is unit testing of MVC application possible without running the controller?
Answer: Yes, by the preceding definition.

Question 15: Can you change the action method name?
Answer: Yes, we can change the action method name using the ActionName attribute. Now the action method will be called by the name defined by the ActionName attribute.

[ActionName("DoAction")]
Public ActionResult DoSomething()
{
Return View();
}  
Question 16: How to prevent a controller method from being accessed by an URL?
Answer: By making the method private or protected but sometimes we need to keep this method public. This is where the NonAction attribute is relevant.

Question 17: What are the features of MVC5?
Answer:
  • Scaffolding
  • ASP.NET Identity
  • One ASP.NET
  • Bootstrap
  • Attribute Routing
  • Filter Overrides
Question 18: What are the various types of filters in an ASP.NET MVC application?
Answer:
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters
Question 19: If there is no match in the route table for the incoming request's URL, which error will result?
Answer: 404 HTTP status code

Question 20: How to enable Attribute Routing?
Answer: By adding a Routes.MapMvcAttributeRoutes() method to the RegisterRoutes() method of the RouteConfig.cs file.

I think 20 questions are enough for one day.

Your comments and suggestions are always welcomed.

Mvc Interview Question and Ans One Side

To prevent a public controller method from being implicitly bound to an action name, which attribute is used?

NOTE: This is objective type question, Please click question title for correct answer.
Can we have multiple AcceptVerbs attribute for a public controller method?

NOTE: This is objective type question, Please click question title for correct answer.

What are the advantages of using asp.net mvc ?

The main advantages of using asp.net mvc are as follows: 

i) One of the main advantage is that it will be easier to manage the complexity as the application is divided into model,view and controller. 
ii) It gives us the full control over the behavior of an application as it does not use view state or server-based forms. 
iii) It provides better support for test-driven development (TDD). 
iv) You can design the application with a rich routing infrastructure as it uses a Front Controller pattern that processes Web application requests through a single controller.
Explain about Razor View Engine ?

This Razor View engine is a part of new rendering framework for ASP.NET web pages. 
ASP.NET rendering engine uses opening and closing brackets to denote code (<% %>), whereas Razor allows a cleaner, implied syntax for determining where code blocks start and end. 

Example: 

In the classic renderer in ASP.NET: 
<ul>

<% foreach (var userTicket in Model)

  { %>

    <li><%: userTicket.Value %></li>

<%  } %>

</ul> 


By using Razor: 

<ul>

@foreach (var userTicket in Model)

{

  <li>@userTicket.Value</li>

}

</ul>
Does the unit testing of an MVC application is possible without running controllers in an ASP.NET process ?

In an MVC application, all the features are based on interface. So, it is easy to unit test a MVC application. 
And it is to note that, in MVC application there is no need of running the controllers for unit testing.
Which namespace is used for ASP.NET MVC ?

System.Web.Mvc namespace contains all the interfaces and classes which supports ASP.NET MVC framework for creating web applications.
Can we share a view across multiple controllers ?

Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. 
By doing like this, you can automatically make the view available across multiple controllers.
What is the use of a controller in an MVC applicatio ?

A controller will decide what to do and what to display in the view. It works as follows: 

i) A request will be received by the controller 
ii) Basing on the request parameters, it will decide the requested activities 
iii) Basing on the request parameters, it will delegates the tasks to be performed 
iv) Then it will delegate the next view to be shown
Mention some of the return types of a controller action method ?

An action method is used to return an instance of any class which is derived from ActionResult class. 
Some of the return types of a controller action method are: 
i) ViewResult : It is used to return a webpage from an action method 
ii) PartialViewResult : It is used to send a section of a view to be rendered inside another view. 
iii) JavaScriptResult : It is used to return JavaScript code which will be executed in the user’s browser. 
iv) RedirectResult : Based on a URL, It is used to redirect to another controller and action method. 
v) ContentResult : It is an HTTP content type may be of text/plain. It is used to return a custom content type as a result of the action method. 
vi) JsonResult : It is used to return a message which is formatted as JSON. 
vii) FileResult : It is used to send binary output as the response. 
viii) EmptyResult : It returns nothing as the result.
Explain about 'page lifecycle' of ASP.NET MVC ?

The page lifecycle of an ASP.NET MVC page is explained as follows: 

i) App Initialisation 
In this stage, the aplication starts up by running Global.asax’s Application_Start() method. 
In this method, you can add Route objects to the static RouteTable.Routes collection. 
If you’re implementing a custom IControllerFactory, you can set this as the active controller factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property. 

ii) Routing 
Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL pattern. 
MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers configured in the Routes table. 

iii) Instantiate and Execute Controller 
At this stage, the active IControllerFactory supplies an IController instance. 

iv) Locate and invoke controller action 
At this stage, the controller invokes its relevant action method, which after further processing, calls RenderView(). 

v) Instantiate and render view 
At this stage, the IViewFactory supplies an IView, which pushes response data to the IHttpResponse object.

MVC means ?

MVC stands for Model View Controller. 
It divides an application into 3 component roles which is based on a framework methodology. 
These component roles are discussed briefly as follows: 

i) Models : These component roles are used to maintain the state which is persisted inside the Database. 

Example: we might have a Product class that is used to represent order data from the Products table inside SQL. 

ii) Views : These component roles are used to display the user interface of the application, where this UI is created off of the model data. 

Example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object. 

iii) Controllers : These component roles are used for various purposes like handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. 

Note: 

In a MVC application, the views are used only for displaying the information whereas the controllers are used for handling and responding to user input and interaction.
Which assembly is used to define the MVC framework and Why ?

The MVC framework is defined through System.Web.Mvc assembly. 
This is because this is the only assembly which contains classes and interfaces that support the ASP.NET Model View Controller (MVC) framework for creating Web applications.
How can we plug an ASP.NET MVC into an existing ASP.NET application ?

We can combine ASP.NET MVC into an existing ASP.NET application by following the below procedure: 

First of all, you have to add a reference to the following three assemblies to your existing ASP.NET application: 

i) System.Web.Routing 
ii) System.Web.Abstractions 
iii) System.Web.Mvc 

The ASP.NET MVC folder should be created after adding these assembly references. 
Add the folder Controllers, Views, and Views | Shared to your existing ASP.NET application. 
And then you have to do the necessary changes in web.config file. 
For this you can refer to the below link: 

http://www.packtpub.com/article/mixing-aspnet-webforms-and-aspnet-mvc

Explain about NonActionAttribute ?

It is already known that all the public methods of a controller class are basically treated as action methods. 
If you dont want this default behaviour, then you can change the public method with NonActionAttribute. Then, the default behaviour changes.
Explain about the formation of Router Table in ASP.NET MVC ?

The Router Table is formed by following the below procedure: 

In the begining stage, when the ASP.NET application starts, the method known as Application_Start() method is called. 
The Application_Start() will then calls RegisterRoutes() method. 
This RegisterRoutes() method will create the Router table.
How to avoid XSS Vulnerabilities in ASP.NET MVC ?

To avoid xss vulnerabilities, you have to use the syntax as '<%: %>' in ASP.NET MVC instead of using the syntax as '<%= %>' in .net framework 4.0. 
This is because it does the HTML encoding. 

Example: 

<input type="text" value="<%: value%>" />
Explain the advantages of using routing in ASP.NET MVC ?

Without using Routing in an ASP.NET MVC application, the incoming browser request should be mapped to a physical file.The thing is that if the file is not there, then you will get a page not found error. 
By using Routing, it will make use of URLs where there is no need of mapping to specific files in a web site. 
This is because, for the URL, there is no need to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.
What are the things that are required to specify a route ?

There are 3 things that are required to specify a route. 

i) URL Pattern : You can pass the variable data to the request handler without using a query string. This is done by including placeholders in a URL pattern. 
ii) Handler : This handler can be a physical file of 2 types such as a .aspx file or a controller class. 
iii) Name for the Route : This name is an optional thing.
In an MVC application, what are the segments of the default route ?

There are 3 segments of the default route in an MVC application.They are: 

The 1st segment is the Controller Name. 
Example: search 

The 2nd segment is the Action Method Name. 
Example: label 

The 3rd segment is the Parameter passed to the Action method. 
Example: Parameter Id - MVC
What are the settings to be done for the Routing to work properly in an MVC application ?

The settings must be done in 2 places for the routing to work properly.They are: 

i) Web.Config File : In the web.config file, the ASP.NET routing has to be enabled. 
ii) Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.