Category Archives: MVC

Spring MVC 3 深入总结

一、前言:

大家好,Spring3 MVC是非常优秀的MVC框架,由其是在3.0版本号公布后,如今有越来越多的团队选择了Spring3 MVC了。Spring3 MVC结构简单,应了那句话简单就是美,并且他强大不失灵活,性能也非常优秀。

官方的下载网址是:http://www.springsource.org/download   (本文使用是的Spring 3.0.5版本号)

 

Struts2也是比較优秀的MVC构架,长处非常多比方良好的结构。但这里想说的是缺点,Struts2因为採用了值栈、OGNL表达式、struts2标签库等,会导致应用的性能下降。Struts2的多层拦截器、多实例action性能都非常好。能够參考我写的一篇关于Spring MVC与Struts2与Servlet比較的文章 http://elf8848.iteye.com/admin/blogs/698217

 

Spring3 MVC的长处:

1、Spring3 MVC的学习难度小于Struts2,Struts2用不上的多余功能太多。呵呵,当然这不是决定因素。

2、Spring3 MVC非常easy就能够写出性能优秀的程序,Struts2要处处小心才干够写出性能优秀的程序(指MVC部分)

3、Spring3 MVC的灵活是你无法想像的,Spring的扩展性有口皆碑,Spring3 MVC当然也不会落后,不会因使用了MVC框架而感到有不论什么的限制。

 

Struts2的众多长处:略…   (呵呵,是不是不公平?)

 

众多文章开篇时总要吹些牛,吸引一下读者的眼球,把读者的胃口调起来,这样大家才有兴趣接着往后看。本文也没能例外。只是保证你看了之后不会懊悔定有收获。

 

 

二、核心类与接口:

 

先来了解一下,几个重要的接口与类。如今不知道他们是干什么的没关系,先混个脸熟,为以后认识他们打个基础。

 

DispatcherServlet   — 前置控制器

 

HandlerMapping接口 — 处理请求的映射

HandlerMapping接口的实现类:

SimpleUrlHandlerMapping  通过配置文件,把一个URL映射到Controller

DefaultAnnotationHandlerMapping  通过注解,把一个URL映射到Controller类上

 

HandlerAdapter接口 — 处理请求的映射

AnnotationMethodHandlerAdapter类,通过注解,把一个URL映射到Controller类的方法上

 

Controller接口 — 控制器

因为我们使用了@Controller注解,加入了@Controller注解注解的类就能够担任控制器(Action)的职责,

所以我们并没实用到这个接口。

 

 

 

HandlerInterceptor 接口–拦截器

无图,我们自己实现这个接口,来完毕拦截的器的工作。

 

 

ViewResolver接口的实现类

UrlBasedViewResolver类 通过配置文件,把一个视图名交给到一个View来处理

InternalResourceViewResolver类,比上面的类,增加了JSTL的支持

 

View接口

JstlView类

 

LocalResolver接口

 

HandlerExceptionResolver接口 –异常处理

SimpleMappingExceptionResolver实现类

 

 

ModelAndView类

无图。

 

 

 

 

 

三、核心流程图

 

本图是我个人画的,有不严谨的地方,大家对付看吧。总比没的看强。

 

 
四、DispatcherServlet说明

 

使用Spring MVC,配置DispatcherServlet是第一步。

DispatcherServlet是一个Servlet,所以能够配置多个DispatcherServlet。

DispatcherServlet是前置控制器,配置在web.xml文件里的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,根据某某规则分发到目标Controller(我们写的Action)来处理。

 

“某某规则”:是依据你使用了哪个HandlerMapping接口的实现类的不同而不同。

 

先来看第一个样例:

Xml代码
  1. <web-app>
  2.     <servlet>
  3.         <servlet-name>example</servlet-name>
  4.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  5.         <load-on-startup>1</load-on-startup>
  6.     </servlet>
  7.     <servlet-mapping>
  8.         <servlet-name>example</servlet-name>
  9.         <url-pattern>*.form</url-pattern>
  10.     </servlet-mapping>
  11. </web-app>

<load-on-startup>1</load-on-startup>是启动顺序,让这个Servlet随Servletp容器一起启动。

<url-pattern>*.form</url-pattern> 会拦截*.form结尾的请求。

 

<servlet-name>example</servlet-name>这个Servlet的名字是example,能够有多个DispatcherServlet,是通过名字来区分的。每个DispatcherServlet有自己的WebApplicationContext上下文对象。同一时候保存的ServletContext中和Request对象中,关于key,以后说明。

 

在DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF目录下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件里定义的bean。

 

 

第二个样例:

Xml代码
  1. <servlet>
  2.     <servlet-name>springMVC</servlet-name>
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4.     <init-param>
  5.         <param-name>contextConfigLocation</param-name>
  6.         <param-value>classpath*:/springMVC.xml</param-value>
  7.     </init-param>
  8.     <load-on-startup>1</load-on-startup>
  9. </servlet>
  10. <servlet-mapping>
  11.     <servlet-name>springMVC</servlet-name>
  12.     <url-pattern>/</url-pattern>
  13. </servlet-mapping>

指明了配置文件的文件名称,不使用默认配置文件名称,而使用springMVC.xml配置文件。

当中<param-value>**.xml</param-value> 这里能够使用多种写法
1、不写,使用默认值:/WEB-INF/<servlet-name>-servlet.xml
2、<param-value>/WEB-INF/classes/springMVC.xml</param-value>
3、<param-value>classpath*:springMVC-mvc.xml</param-value>
4、多个值用逗号分隔
Servlet拦截匹配规则能够自已定义,Servlet拦截哪种URL合适?

当映射为@RequestMapping(“/user/add”)时:
1、拦截*.do,比如:/user/add.do,弊端:全部的url都要以.do结尾。不会影响訪问静态文件。
2、拦截/app/*,比如:/app/user/add,弊端:请求的url都要包括/app,@RequestMapping(“/user/add”)中不需要包括/app。
3、拦截/,比如:/user/add,弊端:对jpg,js,css静态文件的訪问也被拦截不能正常显示。后面有解决的方法。
4、拦截/*,能够走到Action中,但转发到jsp时再次被拦截,不能訪问到jsp。

 

 

五、双亲上下文的说明

 

假设你使用了listener监听器来载入配置,一般在Struts+Spring+Hibernate的项目中都是使用listener监听器的。例如以下

Java代码
  1. <listener>
  2.   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  3. </listener>

Spring会创建一个全局的WebApplicationContext上下文,称为根上下文 ,保存在 ServletContext中,key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性的值。能够使用工具类取出上下文:WebApplicationContextUtils.getWebApplicationContext(ServletContext);

 

DispatcherServlet是一个Servlet,能够同一时候配置多个,每一个 DispatcherServlet有一个自己的 WebApplicationContext上下文,这个上下文继承了 根上下文 中全部东西。 保存在 ServletContext中,key是”org.springframework.web.servlet.FrameworkServlet.CONTEXT”+Servlet名称。当一个Request对象产生时,会把这个WebApplicationContext上下文保存在Request对象中,key是DispatcherServlet.class.getName() + “.CONTEXT”。能够使用工具类取出上下文:RequestContextUtils.getWebApplicationContext(request);

 

Spring中的 ApplicationContext实例能够被限制在不同的作用域(scope)中。
在web MVC框架中,每一个 DispatcherServlet有它自己的WebApplicationContext ,这个context继承了根 WebApplicationContext 的全部bean定义。
这些继承的bean也能够在每一个serlvet自己的所属的域中被覆盖(override),覆盖后的bean 能够被设置上仅仅有这个servlet实例自己使用的属性。

 

总结:不使用listener监听器来载入spring的配置,改用DispatcherServlet来载入spring的配置,不要双亲上下文,仅仅使用一个DispatcherServlet,事情就简单了,什么麻烦事儿也没有了。

 

 

六、springMVC-mvc.xml 配置文件片段解说 (未使用默认配置文件名称)

 

Xml代码
  1.    <!– 自己主动扫描的包名 –>
  2.    <context:component-scan base-package=”com.app,com.core,JUnit4″ ></context:component-scan>
  3.    <!– 默认的注解映射的支持 –>
  4.    <mvc:annotation-driven />
  5.    <!– 视图解释类 –>
  6.    <bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
  7.     <property name=”prefix” value=”/WEB-INF/jsp/”/>
  8.     <property name=”suffix” value=”.jsp”/><!–可为空,方便实现自已的根据扩展名来选择视图解释类的逻辑  –>
  9.     <property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView” />
  10.    </bean>
  11. <!– 拦截器 –>
  12.    <mvc:interceptors>
  13.     <bean class=”com.core.mvc.MyInteceptor” />
  14. </mvc:interceptors>
  15.     <!– 对静态资源文件的訪问  方案一 (二选一) –>
  16.     <mvc:default-servlet-handler/>
  17.     <!– 对静态资源文件的訪问  方案二 (二选一)–>
  18. <mvc:resources mapping=”/images/**” location=”/images/” cache-period=”31556926″/>
  19. <mvc:resources mapping=”/js/**” location=”/js/” cache-period=”31556926″/>
  20. <mvc:resources mapping=”/css/**” location=”/css/” cache-period=”31556926″/>

 

<context:component-scan/> 扫描指定的包中的类上的注解,经常使用的注解有:

@Controller 声明Action组件
@Service    声明Service组件    @Service(“myMovieLister”)
@Repository 声明Dao组件
@Component   泛指组件, 当不好归类时.
@RequestMapping(“/menu”)  请求映射
@Resource  用于注入,( j2ee提供的 ) 默认按名称装配,@Resource(name=”beanName”)
@Autowired 用于注入,(srping提供的) 默认按类型装配
@Transactional( rollbackFor={Exception.class}) 事务管理
@ResponseBody
@Scope(“prototype”)   设定bean的作用域

 

<mvc:annotation-driven /> 是一种简写形式,全然能够手动配置替代这样的简写形式,简写形式能够让初学都高速应用默认配置方案。<mvc:annotation-driven /> 会自己主动注冊DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
后面,我们处理响应ajax请求时,就使用到了对json的支持。
后面,对action写JUnit单元測试时,要从spring IOC容器中取DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,来完毕測试,取的时候要知道是<mvc:annotation-driven />这一句注冊的这两个bean。

 

<mvc:interceptors/> 是一种简写形式。通过看前面的大图,知道,我们能够配置多个HandlerMapping。<mvc:interceptors/>会为每个HandlerMapping,注入一个拦截器。事实上我们也能够手动配置为每个HandlerMapping注入一个拦截器。

 

<mvc:default-servlet-handler/> 使用默认的Servlet来响应静态文件。

 

<mvc:resources mapping=”/images/**” location=”/images/” cache-period=”31556926″/> 匹配URL  /images/**  的URL被当做静态资源,由Spring读出到内存中再响应http。
七、怎样訪问到静态的文件,如jpg,js,css?

怎样你的DispatcherServlet拦截 *.do这种URL,就不存在訪问不到静态资源的问题。假设你的DispatcherServlet拦截“/”,拦截了全部的请求,同一时候对*.js,*.jpg的訪问也就被拦截了。

 

目的:能够正常訪问静态文件,不要找不到静态文件报404。

方案一:激活Tomcat的defaultServlet来处理静态文件

Xml代码
  1. <servlet-mapping>
  2.     <servlet-name>default</servlet-name>
  3.     <url-pattern>*.jpg</url-pattern>
  4. </servlet-mapping>
  5. <servlet-mapping>
  6.     <servlet-name>default</servlet-name>
  7.     <url-pattern>*.js</url-pattern>
  8. </servlet-mapping>
  9. <servlet-mapping>
  10.     <servlet-name>default</servlet-name>
  11.     <url-pattern>*.css</url-pattern>
  12. </servlet-mapping>
  13. 要配置多个,每种文件配置一个

要写在DispatcherServlet的前面, 让 defaultServlet先拦截,这个就不会进入Spring了,我想性能是最好的吧。

Tomcat, Jetty, JBoss, and GlassFish  默认 Servlet的名字 — “default”
Google App Engine 默认 Servlet的名字 — “_ah_default”
Resin 默认 Servlet的名字 — “resin-file”
WebLogic 默认 Servlet的名字  — “FileServlet”
WebSphere  默认 Servlet的名字 — “SimpleFileServlet”

 
方案二: 在spring3.0.4以后版本号提供了mvc:resources
mvc:resources 的用法:

Xml代码
  1. <!– 对静态资源文件的訪问 –>
  2. <mvc:resources mapping=”/images/**” location=”/images/” />

/images/**映射到ResourceHttpRequestHandler进行处理,location指定静态资源的位置.能够是web application根文件夹下、jar包里面,这样能够把静态资源压缩到jar包中。cache-period 能够使得静态资源进行web cache

假设出现以下的错误,可能是没有配置<mvc:annotation-driven />的原因。
报错WARNING: No mapping found for HTTP request with URI [/mvc/user/findUser/lisi/770] in DispatcherServlet with name ‘springMVC’

 

使用<mvc:resources/>元素,把mapping的URI注冊到SimpleUrlHandlerMapping的urlMap中,
key为mapping的URI pattern值,而value为ResourceHttpRequestHandler,
这样就巧妙的把对静态资源的訪问由HandlerMapping转到ResourceHttpRequestHandler处理并返回,所以就支持classpath文件夹,jar包内静态资源的訪问.
另外须要注意的一点是,不要对SimpleUrlHandlerMapping设置defaultHandler.由于对static uri的defaultHandler就是ResourceHttpRequestHandler,
否则无法处理static resources request.

 

 

方案三 ,使用<mvc:default-servlet-handler/>

 

Xml代码
  1. <mvc:default-servlet-handler/>

 

会把”/**” url,注冊到SimpleUrlHandlerMapping的urlMap中,把对静态资源的訪问由HandlerMapping转到org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler处理并返回.
DefaultServletHttpRequestHandler使用就是各个Servlet容器自己的默认Servlet.

 

 

补充说明:多个HandlerMapping的运行顺序问题:

DefaultAnnotationHandlerMapping的order属性值是:0

< mvc:resources/ >自己主动注冊的 SimpleUrlHandlerMapping的order属性值是: 2147483646

 

<mvc:default-servlet-handler/>自己主动注冊 的SimpleUrlHandlerMapping 的order属性值是: 2147483647

 

spring会先运行order值比較小的。当訪问一个a.jpg图片文件时,先通过 DefaultAnnotationHandlerMapping 来找处理器,一定是找不到的,我们没有叫a.jpg的Action。再 按order值升序找,因为最后一个 SimpleUrlHandlerMapping 是匹配 “/**”的,所以一定会匹配上,再响应图片。

 

訪问一个图片,还要走层层匹配。真不知性能怎样?改天做一下压力測试,与Apache比一比。

 

最后再说明一下,怎样你的DispatcherServlet拦截 *.do这种URL,就不存上述问题了。

 
八、请求怎样映射到详细的Action中的方法?
方案一:基于xml配置映射,能够利用SimpleUrlHandlerMapping、BeanNameUrlHandlerMapping进行Url映射和拦截请求。
配置方法略。

方案二:基于注解映射,能够使用DefaultAnnotationHandlerMapping。

Xml代码
  1. <bean class=”org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”>  </bean>

 

但前面我们配置了<mvc:annotation-driven />,他会自己主动注冊这个bean,就不需要我们显示的注冊这个bean了。
以上都能够注入interceptors,实现权限控制等前置工作。
我们使用第2种,基于注解来使用spring MVC

 

 

并在action类上使用:
@Controller
@RequestMapping(“/user”)

九、Spring中的拦截器:
Spring为我们提供了:
org.springframework.web.servlet.HandlerInterceptor接口,

org.springframework.web.servlet.handler.HandlerInterceptorAdapter适配器,
实现这个接口或继承此类,能够很方便的实现自己的拦截器。

有下面三个方法:

Action之前运行:
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler);

生成视图之前运行
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView);

最后运行,可用于释放资源
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)

分别实现预处理、后处理(调用了Service并返回ModelAndView,但未进行页面渲染)、返回处理(已经渲染了页面)
在preHandle中,能够进行编码、安全控制等处理;
在postHandle中,有机会改动ModelAndView;
在afterCompletion中,能够依据ex是否为null推断是否发生了异常,进行日志记录。
參数中的Object handler是下一个拦截器。

十、怎样使用拦截器?
自己定义一个拦截器,要实现HandlerInterceptor接口:

Java代码
  1. public class MyInteceptor implements HandlerInterceptor {
  2.     略。。。
  3. }

 

Spring MVC并没有总的拦截器,不能对全部的请求进行前后拦截。
Spring MVC的拦截器,是属于HandlerMapping级别的,能够有多个HandlerMapping ,每一个HandlerMapping能够有自己的拦截器。
当一个请求按Order值从小到大,顺序运行HandlerMapping接口的实现类时,哪一个先有返回,那就能够结束了,后面的HandlerMapping就不走了,本道工序就完毕了。就转到下一道工序了。
拦截器会在什么时候运行呢? 一个请求交给一个HandlerMapping时,这个HandlerMapping先找有没有处理器来处理这个请求,怎样找到了,就运行拦截器,运行完拦截后,交给目标处理器。
假设没有找到处理器,那么这个拦截器就不会被运行。
在spring MVC的配置文件里配置有三种方法:
方案一,(近似)总拦截器,拦截全部url

Java代码
  1.    <mvc:interceptors>
  2.     <bean class=”com.app.mvc.MyInteceptor” />
  3. </mvc:interceptors>

为什么叫“近似”,前面说了,Spring没有总的拦截器。

<mvc:interceptors/>会为每一 个HandlerMapping,注入一个拦截器。总有一个HandlerMapping是能够找到处理器的,最多也仅仅找到一个处理器,所以这个拦截器总会被运行的。起到了总拦截器的作用。
方案二, (近似) 总拦截器, 拦截匹配的URL。

Xml代码
  1. <mvc:interceptors >
  2.   <mvc:interceptor>
  3.         <mvc:mapping path=”/user/*” /> <!– /user/*  –>
  4.         <bean class=”com.mvc.MyInteceptor”></bean>
  5.     </mvc:interceptor>
  6. </mvc:interceptors>

就是比 方案一多了一个URL匹配。

 

 

 

方案三,HandlerMappint上的拦截器

Xml代码
  1. <bean class=”org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping”>
  2.  <property name=”interceptors”>
  3.      <list>
  4.          <bean class=”com.mvc.MyInteceptor”></bean>
  5.      </list>
  6.  </property>
  7. </bean>

假设使用了<mvc:annotation-driven />, 它会自己主动注冊DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter 这两个bean,所以就没有机会再给它注入interceptors属性,就无法指定拦截器。

当然我们能够通过人工配置上面的两个Bean,不使用 <mvc:annotation-driven />,就能够 给interceptors属性 注入拦截器了。

 

事实上我也不建议使用<mvc:annotation-driven />,而建议手动写配置文件,来替代 <mvc:annotation-driven />,这就控制力就强了。

 

 

 

 

十一、怎样实现全局的异常处理?

在spring MVC的配置文件里:

Xml代码
  1. <!– 总错误处理–>
  2. <bean id=”exceptionResolver” class=”org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”>
  3.     <property name=”defaultErrorView”>
  4.         <value>/error/error</value>
  5.     </property>
  6.     <property name=”defaultStatusCode”>
  7.         <value>500</value>
  8.     </property>
  9. <property name=”warnLogCategory”>
  10.         <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
  11.     </property>
  12. </bean>

 

这里基本的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。

详细能够配置哪些属性,我是通过查看源代码知道的。

你也能够实现HandlerExceptionResolver接口,写一个自己的异常处理程序。spring的扩展性是非常好的。

 

 

通过SimpleMappingExceptionResolver我们能够将不同的异常映射到不同的jsp页面(通过exceptionMappings属性的配置)。

 

同一时候我们也能够为全部的异常指定一个默认的异常提示页面(通过defaultErrorView属性的配置),假设所抛出的异常在exceptionMappings中没有相应的映射,则Spring将用此默认配置显示异常信息。

注意这里配置的异常显示界面均仅包含主文件名称,至于文件路径和后缀已经在viewResolver中指定。如/error/error表示/error/error.jsp

 

 

显示错误的jsp页面:

Html代码
  1. <%@ page language=”java” contentType=”text/html; charset=GBK”
  2.     pageEncoding=”GBK”%>
  3. <%@ page import=”java.lang.Exception”%>
  4. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
  5. <html>
  6. <head>
  7. <meta http-equiv=”Content-Type” content=”text/html; charset=GBK”>
  8. <title>错误页面</title>
  9. </head>
  10. <body>
  11. <h1>出错了</h1>
  12. <%
  13. Exception e = (Exception)request.getAttribute(“exception”);
  14. out.print(e.getMessage());
  15. %>
  16. </body>
  17. </html>

当中一句:request.getAttribute(“exception”),key是exception,也是在SimpleMappingExceptionResolver类默认指定的,是可能通过配置文件改动这个值的,大家能够去看源代码。

 

參考文章:

http://www.blogjava.net/wuxufeng8080/articles/191150.html

http://fangjunai.blog.163.com/blog/static/1124970520108102013839/

 

 

 

十二、怎样把全局异常记录到日志中?

在前的配置中,当中有一个属性warnLogCategory,值是“SimpleMappingExceptionResolver类的全限定名”。我是在SimpleMappingExceptionResolver类父类AbstractHandlerExceptionResolver类中找到这个属性的。查看源代码后得知:假设warnLogCategory不为空,spring就会使用apache的org.apache.commons.logging.Log日志工具,记录这个异常,级别是warn。

值:“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”,是“SimpleMappingExceptionResolver类的全限定名”。这个值不是随便写的。  由于我在log4j的配置文件里还要增加log4j.logger.org.springframework.web.servlet.handler.SimpleMappingExceptionResolver=WARN,保证这个级别是warn的日志一定会被记录,即使log4j的根日志级别是ERROR。

 

 

 

 

十三、怎样给spring3 MVC中的Action做JUnit单元測试?

使用了spring3 MVC后,给action做单元測试也非常方便,我曾经从来不给action写单元測试的,再在不同了,方便了,所以一定要写。

 

JUnitActionBase类是全部JUnit的測试类的父类

 

Java代码
  1. package test;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.junit.BeforeClass;
  5. import org.springframework.mock.web.MockServletContext;
  6. import org.springframework.web.context.WebApplicationContext;
  7. import org.springframework.web.context.support.XmlWebApplicationContext;
  8. import org.springframework.web.servlet.HandlerAdapter;
  9. import org.springframework.web.servlet.HandlerExecutionChain;
  10. import org.springframework.web.servlet.HandlerMapping;
  11. import org.springframework.web.servlet.ModelAndView;
  12. import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
  13. import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;
  14. /**
  15. * 说明: JUnit測试action时使用的基类
  16. *
  17. * @author  赵磊
  18. * @version 创建时间:2011-2-2 下午10:27:03
  19. */
  20. public class JUnitActionBase {
  21.     private static HandlerMapping handlerMapping;
  22.     private static HandlerAdapter handlerAdapter;
  23.     /**
  24.      * 读取spring3 MVC配置文件
  25.      */
  26.     @BeforeClass
  27.  public static void setUp() {
  28.         if (handlerMapping == null) {
  29.             String[] configs = { “file:src/springConfig/springMVC.xml” };
  30.             XmlWebApplicationContext context = new XmlWebApplicationContext();
  31.             context.setConfigLocations(configs);
  32.             MockServletContext msc = new MockServletContext();
  33.             context.setServletContext(msc);         context.refresh();
  34.             msc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
  35.             handlerMapping = (HandlerMapping) context
  36.                     .getBean(DefaultAnnotationHandlerMapping.class);
  37.             handlerAdapter = (HandlerAdapter) context.getBean(context.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
  38.         }
  39.     }
  40.     /**
  41.      * 运行request对象请求的action
  42.      *
  43.      * @param request
  44.      * @param response
  45.      * @return
  46.      * @throws Exception
  47.      */
  48.     public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response)
  49.  throws Exception {
  50.         HandlerExecutionChain chain = handlerMapping.getHandler(request);
  51.         final ModelAndView model = handlerAdapter.handle(request, response,
  52.                 chain.getHandler());
  53.         return model;
  54.     }
  55. }

 

 

 

 

 

 

这是个JUnit測试类,我们能够new Request对象,来參与測试,太方便了。给request指定訪问的URL,就能够请求目标Action了。

 

Java代码
  1. package test.com.app.user;
  2. import org.junit.Assert;
  3. import org.junit.Test;
  4. import org.springframework.mock.web.MockHttpServletRequest;
  5. import org.springframework.mock.web.MockHttpServletResponse;
  6. import org.springframework.web.servlet.ModelAndView;
  7. import test.JUnitActionBase;
  8. /**
  9. * 说明: 測试OrderAction的样例
  10. *
  11. * @author  赵磊
  12. * @version 创建时间:2011-2-2 下午10:26:55
  13. */
  14. public class TestOrderAction extends JUnitActionBase {
  15.     @Test
  16.     public void testAdd() throws Exception {
  17.     MockHttpServletRequest request = new MockHttpServletRequest();
  18.         MockHttpServletResponse response = new MockHttpServletResponse();
  19.         request.setRequestURI(“/order/add”);
  20.         request.addParameter(“id”, “1002”);
  21.         request.addParameter(“date”, “2010-12-30”);
  22.         request.setMethod(“POST”);
  23.         // 运行URI相应的action
  24.         final ModelAndView mav = this.excuteAction(request, response);
  25.         // Assert logic
  26.         Assert.assertEquals(“order/add”, mav.getViewName());
  27.         String msg=(String)request.getAttribute(“msg”);
  28.         System.out.println(msg);
  29.     }
  30. }

须要说明一下 :由于当前最想版本号的Spring(Test) 3.0.5还不支持@ContextConfiguration的注解式context file注入,所以还须要写个setUp处理下,否则类似于Tiles的载入过程会有错误,由于没有ServletContext。3.1的版本号应该有更好的解决方式,參见: https://jira.springsource.org/browse/SPR-5243 

參考 :http://www.iteye.com/topic/828513

 

 

 

 

十四、转发与重定向

能够通过redirect/forward:url方式转到还有一个Action进行连续的处理。

能够通过redirect:url 防止表单反复提交 。

写法例如以下:

return “forward:/order/add”;

return “redirect:/index.jsp”;

 

 

 

 

 十五、处理ajax请求

 

1、引入以下两个jar包,我用的是1.7.2,好像1.4.2版本号以上都能够,下载地址: http://wiki.fasterxml.com/JacksonDownload

jackson-core-asl-1.7.2.jar

jackson-mapper-asl-1.7.2.jar

 

2、spring的配置文件里要有这一行,才干使用到spring内置支持的json转换。假设你手工把POJO转成json就能够不需要使用spring内置支持的json转换。

<mvc:annotation-driven />

 

3、使用@ResponseBody注解

Java代码
  1. /**
  2.  * ajax測试
  3. * http://127.0.0.1/mvc/order/ajax
  4.  */
  5. @RequestMapping(“/ajax”)
  6. @ResponseBody
  7. public Object ajax(HttpServletRequest request){
  8.     List<String> list=new ArrayList<String>();
  9.     list.add(“电视”);
  10. nbsp;       list.add(“洗衣机”);
  11.     list.add(“冰箱”);
  12.     list.add(“电脑”);
  13.     list.add(“汽车”);
  14.     list.add(“空调”);
  15.     list.add(“自行车”);
  16.     list.add(“饮水机”);
  17.     list.add(“热水器”);
  18.     return list;
  19. }

from:http://www.cnblogs.com/lcchuguo/p/4052521.html?utm_source=tuicool&utm_medium=referral

Understanding Basics of UI Design Pattern MVC, MVP and MVVM

Introduction

This is my first article and I hope you will like it. After reading this article, you will have a good understanding about “Why we need UI design pattern for our application?” and “What are basic differences between different UI patterns (MVC, MVP, MVVP)?”.

In traditional UI development – developer used to create a View using window or usercontrol or page and then write all logical code (Event handling, initialization and data model, etc.) in code behind and hence they were basically making code as a part of view definition class itself. This approach increased the size of my view class and created a very strong dependency between my UI and data binding logic and business operations. In this situation, no two developers can work simultaneously on the same view and also one developer’s changes might break the other code. So everything is in one place is always a bad idea for maintainability, extendibility and testability prospective. So if you look at the big picture, you can feel that all these problems exist because there is a very tight coupling between the following items.

  1. View (UI)
  2. Model (Data displayed in UI)
  3. Glue code (Event handling, binding, business logic)

Definition of Glue code is different in each pattern. Although view and model is used with the same definition in all patterns.

In case of MVC it is controller. In case of MVP it is presenter. In case of MVVM it is view model.

If you look at the first two characters in all the above patterns, it remain same i.e. stands for model and view. All these patterns are different but have a common objective that is “Separation of Duties”

In order to understand the entire article, I request readers to first understand the above entity. A fair idea about these will help you to understand this article. If you ever worked on UI module, you can easily relate these entities with your application.

MVC (model view controller), MVP (model view presenter) and MVVM (model view view model) patterns allow us to develop applications with loss coupling and separation of concern which in turn improve testability, maintainability and extendibility with minimum effort.

MVVM pattern is a one of the best solutions to handle such problems for WPF and Silverlight application. During this article, I will compare MVC, MVP and MVVM at the definition level.

MVP & MVC

Before we dig into MVVM, let’s start with some history: There were already many popular design patterns available to make UI development easy and fast. For example, MVP (model view presenter) pattern is one of the very popular patterns among other design patterns available in the market. MVP is a variation of MVC pattern which is being used for so many decades. Simple definition of MVP is that it contains three components: Model, View and presenter. So view is nothing but a UI which displays on the screen for user, the data it displays is the model, and the Presenter hooks the two together (View and model).

The view relies on a Presenter to populate it with model data, react to user input, and provide input validation. For example, if user clicks on save button, corresponding handling is not in code behind, it’s now in presenter. If you wanted to study it in detail, here is the MSDN link.

In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View basically calls to a Controller along with an action. In web application, each action is a call to a URL and for each such call there is a controller available in the application who respond to such call. Once that Controller has completed its processing, it will return the correct View.

In case of MVP, view binds to the Model directly through data binding. In this case, it’s the Presenter’s job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation. It means while implementing this pattern, we have to write some code in code behind of view in order delegate (register) to the presenter. However, in case of MVC, a view does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. Since controller itself returns view while responding to URL action, there is no need to write any code in view code behind file.

MVC Steps

Step 1: Incoming request directed to Controller.

Step 2: Controller processes request and forms a data Model.

Step 3: Model is passed to View.

Step 4: View transforms Model into appropriate output format.

Step 5: Response is rendered.

So now you have basic understanding of MVC and MVP. Let’s move to MVVM.

MVVM (Model View ViewModel)

The MVVM pattern includes three key parts:

  1. Model (Business rule, data access, model classes)
  2. View (User interface (XAML))
  3. ViewModel (Agent or middle man between view and model)

Model and View work just like MVC and “ViewModel” is the model of the View.

  • ViewModel acts as an interface between model and View.
  • ViewModel provides data binding between View and model data.
  • ViewModel handles all UI actions by using command.

In MVVM, ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects. In simple words, TextBox text property is bound with name property in ViewModel.

In View:

Collapse | Copy Code
<TextBlock Text="{Binding Name}"/>

In ViewModel:

Collapse | Copy Code
public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }

ViewModel reference is set to a DataContext of View in order to set view data binding (glue between view and ViewModel model).

Code behind code of View:

Collapse | Copy Code
public IViewModel Model
        {
            get
            {
                return this.DataContext as IViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }

If property values in the ViewModel change, those new values automatically propagate to the view via data binding and via notification. When the user performs some action in the view for example clicking on save button, a command on the ViewModel executes to perform the requested action. In this process, it’s the ViewModel which modifies model data, View never modifies it. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model doesn’t have any idea about ViewModel and view exists.

Where to Use What in the .NET World

  • Model-View-Controller (MVC) pattern
    • ASP.NET MVC 4 Link
    • Disconnected Web Based Applications
  • Model-View-Presenter (MVP) pattern
    • Web Forms/SharePoint, Windows Forms
  • Model-View-ViewModel (MVVM) pattern
    • Silverlight, WPF Link
    • Data binding

Sources and References

History

  • 18th July, 2011: Initial version
  • 19th July, 2011: Modified content in MVVM section

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

from:http://www.codeproject.com/Articles/228214/Understanding-Basics-of-UI-Design-Pattern-MVC-MVP

(Model view controller)MVC Interview questions and answers

Disclaimer
What is MVC(Model view controller)?
Can you explain the complete flow of MVC?
Is MVC suitable for both windows and web application?
What are the benefits of using MVC?
Is MVC different from a 3 layered architecture?
What is the latest version of MVC?
What is the difference between each version of MVC?
What are routing in MVC?
Where is the route mapping code written?
Can we map multiple URL’s to the same action?
How can we navigate from one view to other view using hyperlink?
How can we restrict MVC actions to be invoked only by GET or POST?
How can we maintain session in MVC?
What is the difference between tempdata,viewdata and viewbag?
What are partial views in MVC?
How did you create partial view and consume the same?
How can we do validations in MVC?
Can we display all errors in one go?
How can we enable data annotation validation on client side?
What is razor in MVC?
Why razor when we already had ASPX?
So which is a better fit Razor or ASPX?
How can you do authentication and authorization in MVC?
How to implement windows authentication for MVC?
How do you implement forms authentication in MVC?
How to implement Ajax in MVC?
What kind of events can be tracked in AJAX?
What is the difference between “ActionResult” and “ViewResult”?
What are the different types of results in MVC?
What are “ActionFilters”in MVC?
Can we create our custom view engine using MVC?
How to send result back in JSON format in MVC?
What is “WebAPI”?
But WCF SOAP also does the same thing, so how does “WebAPI” differ?
With WCF also you can implement REST,So why “WebAPI”?

Disclaimer

By reading these MVC interview question it does not mean you will go and clear MVC interviews. The whole purpose of this article is to quickly brush up your MVC knowledge before you for the MVC interviews.

This article does not teach MVC, it’s a last minute revision sheet before going for MVC interviews.

In case you want to learn MVC from scratch start by reading Learn MVC ( Model view controller) step by step 7 days or you can also start with my step by step MVC ( Model view controller) video series from youtube.

What is MVC(Model view controller)?

MVC is architectural pattern which separates the representation and the user interaction. It’s divided in three broader sections, “Model”, “View” and “Controller”. Below is how each one of them handles the task.

  • The “View” is responsible for look and feel.
  • “Model” represents the real world object and provides data to the “View”.
  • The “Controller” is responsible to take the end user request and load the appropriate “Model” and “View”.

 

Figure: – MVC (Model view controller)

Can you explain the complete flow of MVC?

Below are the steps how control flows in MVC (Model, view and controller) architecture:-

  • All end user requests are first sent to the controller.
  • The controller depending on the request decides which model to load. The controller loads the model and attaches the model with the appropriate view.
  • The final view is then attached with the model data and sent as a response to the end user on the browser.

Is MVC suitable for both windows and web application?

MVC architecture is suited for web application than windows. For window application MVP i.e. “Model view presenter” is more applicable.IfyouareusingWPFandSLMVVMismoresuitableduetobindings.

What are the benefits of using MVC?

There are two big benefits of MVC:-

Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.

Automated UI testing is possible because now the behind code (UI interaction code) has moved to a simple.NET class. This gives us opportunity to write unit tests and automate manual testing.

Is MVC different from a 3 layered architecture?

MVC is an evolution of a 3 layered traditional architecture. Many components of 3 layered architecture are part of MVC.  So below is how the mapping goes.

Functionality 3 layered / tiered architecture Model view controller architecture
Look and Feel User interface. View.
UI logic User interface. Controller
Business logic /validations Middle layer Model.
Request is first sent to User interface Controller.
Accessing data Data access layer. Data access layer.

Figure: – 3 layered architecture

What is the latest version of MVC?

When this note was written, four versions where released of MVC. MVC 1 , MVC 2, MVC 3 and MVC 4. So the latest is MVC 4.

What is the difference between each version of MVC?

Below is a detail table of differences. But during interview it’s difficult to talk about all of them due to time limitation. So I have highlighted important differences which you can run through before the interviewer.

MVC 2 MVC 3 MVC 4
Client-Side Validation Templated Helpers Areas Asynchronous Controllers Html.ValidationSummary Helper Method DefaultValueAttribute in Action-Method Parameters Binding Binary Data with Model Binders DataAnnotations Attributes Model-Validator Providers New RequireHttpsAttribute Action Filter Templated Helpers Display Model-Level Errors RazorReadymade project templatesHTML 5 enabled templatesSupport for Multiple View EnginesJavaScript and AjaxModel Validation Improvements ASP.NET Web APIRefreshed and modernized default project templatesNew mobile project templateMany new features to support mobile apps Enhanced support for asynchronous methods

What are routing in MVC?

Routing helps you to define a URL structure and map the URL with the controller.

For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”,  it goes to the  “Customer” Controller  and invokes “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.

Collapse | Copy Code
routes.MapRoute(
               "View", // Route name
               "View/ViewCustomer/{id}", // URL with parameters
               new { controller = "Customer", action = "DisplayCustomer",
id = UrlParameter.Optional }); // Parameter defaults

Where is the route mapping code written?

The route mapping code is written in the “global.asax” file.

Can we map multiple URL’s to the same action?

Yes , you can , you just need to make two entries with different key names and specify the same controller and action.

How can we navigate from one view to other view using hyperlink?

By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

Collapse | Copy Code
<%= Html.ActionLink("Home","Gotohome") %>

How can we restrict MVC actions to be invoked only by GET or POST?

We can decorate the MVC action by “HttpGet” or “HttpPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HttpGet”. If we try to make Http post on “DisplayCustomer” it will throw an error.

Collapse | Copy Code
[HttpGet]
        public ViewResult DisplayCustomer(int id)
        {
            Customer objCustomer = Customers[id];
            return View("DisplayCustomer",objCustomer);
        }

How can we maintain session in MVC?

Sessions can be maintained in MVC by 3 ways tempdata ,viewdata and viewbag.

What is the difference between tempdata ,viewdata and viewbag?

 

Figure:- difference between tempdata , viewdata and viewbag

Temp data: –Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect,“tempdata” helps to maintain data between those redirects. It internally uses session variables.

View data: – Helps to maintain data when you move from controller to view.

View Bag: – It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

Figure:-dynamic keyword

Session variables: – By using session variables we can maintain data from any entity to any entity.

Hidden fields and HTML controls: – Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Below is a summary table which shows different mechanism of persistence.

Maintains data between ViewData/ViewBag TempData Hidden fields Session
Controller to Controller No Yes No Yes
Controller to View Yes No No Yes
View to Controller No No Yes Yes

What are partial views in MVC?

Partial view is a reusable view (like a user control) which can be embedded inside other view. For example let’s say all your pages of your site have a standard structure with left menu, header and footer as shown in the image below.

Figure:- partial views in MVC

For every page you would like to reuse the left menu, header and footer controls. So you can go and create partial views for each of these items and then you call that partial view in  the  main view.

How did you create partial view and consume the same?

When you add a view to your project you need to check the “Create partial view” check box.

Figure:-createpartialview

Once the partial view is created you can then call the partial view in the main view using “Html.RenderPartial” method as shown in the below code snippet.

Collapse | Copy Code
<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

How can we do validations in MVC?

One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “customer” class with a property “customercode”.

This”CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.

Collapse | Copy Code
public class Customer
{
        [Required(ErrorMessage="Customer code is required")]
        public string CustomerCode
        {
            set;
            get;
        }
}

In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.

Collapse | Copy Code
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>

Later in the controller we can check if the model is proper or not by using “ModelState.IsValid” property and accordingly we can take actions.

 

Collapse | Copy Code
public ActionResult PostCustomer(Customer obj)
{
if (ModelState.IsValid)
{
                obj.Save();
                return View("Thanks");
}
else
{
                return View("Customer");
}
}

 

Below is a simple view of how the error message is displayed on the view.

Figure:- validations in MVC

Can we display all errors in one go?

Yes we can, use “ValidationSummary” method from HTML helper class.

Collapse | Copy Code
<%= Html.ValidationSummary() %>

What are the other data annotation attributes for validation in MVC?

If you want to check string length, you can use “StringLength”.

Collapse | Copy Code
[StringLength(160)]
public string FirstName { get; set; }

In case you want to use regular expression, you can use “RegularExpression” attribute.

Collapse | Copy Code
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

If you want to check whether the numbers are in range, you can use the “Range” attribute.

Collapse | Copy Code
[Range(10,25)]public int Age { get; set; }

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

Collapse | Copy Code
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }

In case you want to get a particular error message , you can use the “Errors” collection.

Collapse | Copy Code
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call “TryUpdateModel” in your controller to check if the object is valid or not.

Collapse | Copy Code
TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use “AddModelError” function.

Collapse | Copy Code
ModelState.AddModelError("FirstName", "This is my server-side error.");

How can we enable data annotation validation on client side?

It’s a two-step process first reference the necessary jquery files.

Collapse | Copy Code
<script src="<%= Url.Content("~/Scripts/jquery-1.5.1.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.validate.unobtrusive.js") %>" type="text/javascript"></script>

Second step is to call “EnableClientValidation” method.

Collapse | Copy Code
<% Html.EnableClientValidation(); %>

What is razor in MVC?

It’s a light weight view engine. Till MVC we had only one view type i.e.ASPX, Razor was introduced in MVC 3.

Why razor when we already had ASPX?

Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.

Collapse | Copy Code
<%=DateTime.Now%>

In Razor it’s just one line of code.

Collapse | Copy Code
@DateTime.Now

So which is a better fit Razor or ASPX?

As per Microsoft razor is more preferred because it’s light weight and has simple syntaxes.

How can you do authentication and authorization in MVC?

You can use windows or forms authentication for MVC.

How to implement windows authentication for MVC?

For windows authentication you need to go and modify the “web.config” file and set authentication mode to windows.

Collapse | Copy Code
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>

Then in the controller or on the action you can use the “Authorize” attribute which specifies which users have access to these controllers and actions. Below is the code snippet for the same. Now only  the users specified in the controller and action can access the same.

Collapse | Copy Code
[Authorize(Users= @"WIN-3LI600MWLQN\Administrator")]
    public class StartController : Controller
    {
        //
        // GET: /Start/
        [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
        public ActionResult Index()
        {
            return View("MyView");
        }
    }

How do you implement forms authentication in MVC?

Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.

Collapse | Copy Code
<authentication mode="Forms">
<forms loginUrl="~/Home/Login"  timeout="2880"/>
</authentication>

We also need to create a controller where we will check the user is proper or not. If the user is proper we will set the cookie value.

Collapse | Copy Code
public ActionResult Login()
{
if ((Request.Form["txtUserName"] == "Shiv") && (Request.Form["txtPassword"] == "Shiv@123"))
{
            FormsAuthentication.SetAuthCookie("Shiv",true);
            return View("About");
}
else
{
            return View("Index");
}
}

All the other actions need to be attributed with “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.

Collapse | Copy Code
[Authorize]
PublicActionResult Default()
{
return View();
}
[Authorize]
publicActionResult About()
{
return View();
}

How to implement Ajax in MVC?

You can implement Ajax in two ways in MVC: –

  • Ajax libraries
  • Jquery

Below is a simple sample of how to implement Ajax by using “Ajax” helper library. In the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getCustomer”. So now the submit action click will be an asynchronous ajax call.

Collapse | Copy Code
<script language="javascript">
function OnSuccess(data1)
{
// Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
    %>
<% using (Ajax.BeginForm("getCustomer","MyAjax",AjaxOpt)) { %>
<input id="txtCustomerCode" type="text" /><br />
<input id="txtCustomerName" type="text" /><br />
<input id="Submit2" type="submit" value="submit"/></div>
<%} %>

In case you want to make ajax calls on hyperlink clicks you can use “Ajax.ActionLink” function as shown in the below code.

Figure:- implement Ajax in MVC

So if you want to create Ajax asynchronous   hyperlink by name “GetDate” which calls the “GetDate” function on the controller , below is the code for the same.  Once the controller responds this data is displayed in the HTML DIV tag by name “DateDiv”.

Collapse | Copy Code
<span id="DateDiv" />
<%:
Ajax.ActionLink("Get Date","GetDate",
new AjaxOptions {UpdateTargetId = "DateDiv" })
%>

Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.

Collapse | Copy Code
public class Default1Controller : Controller
{
       public string GetDate()
       {
           Thread.Sleep(10000);
           return DateTime.Now.ToString();
       }
}

The second way of making Ajax call in MVC is by using Jquery. In the below code you can see we are making an ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$.post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyper link click event as you want.

Collapse | Copy Code
function GetData()
    {
        var url = "/MyAjax/getCustomer";
        $.post(url, function (data)
        {
            $("#txtCustomerCode").val(data.CustomerCode);
            $("#txtCustomerName").val(data.CustomerName);
        }
        )
    }

What kind of events can be tracked in AJAX?

Figure:- tracked in AJAX

What is the difference between “ActionResult” and “ViewResult”?

“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult” ,”JsonResult” , “FileStreamResult” and so on.

“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “DynamicView”. Depending on the flag (“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

Collapse | Copy Code
public ActionResult DynamicView()
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
}

What are the different types of results in MVC?

Collapse | Copy Code
Note: -It’s difficult to remember all the 12 types. But some important ones you can remember for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.

There 12 kinds of results in MVC, at the top is “ActionResult”class which is a base class that canhave11subtypes’sas listed below: –

  1. ViewResult – Renders a specified view to the response stream
  2. PartialViewResult – Renders a specified partial view to the response stream
  3. EmptyResult – An empty response is returned
  4. RedirectResult – Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult – Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult – Serializes a given ViewData object to JSON format
  7. JavaScriptResult – Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult – Writes content to the response stream without requiring a view
  9. FileContentResult – Returns a file to the client
  10. FileStreamResult – Returns a file to the client, which is provided by a Stream
  11. FilePathResult – Returns a file to the client

What are “ActionFilters”in MVC?

“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed.

Figure:- “ActionFilters”in MVC

Action filters are useful in the following scenarios:-

  1. Implement post-processinglogicbeforethe action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:-

  • Inline action filter.
  • Creating an “ActionFilter” attribute.

To create a inline action attribute we need to implement “IActionFilter” interface.The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.

Collapse | Copy Code
public class Default1Controller : Controller , IActionFilter
    {
        public ActionResult Index(Customer obj)
        {
            return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            Trace.WriteLine("Action is executing");
        }
    }

The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.

Collapse | Copy Code
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
     Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
      Trace.WriteLine("Action executing");
}
}

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “Default1Controller” with “MyActionAttribute” class which was created in the previous code.

Collapse | Copy Code
[MyActionAttribute]
public class Default1Controller : Controller
{
 public ActionResult Index(Customer obj)
 {
 return View(obj);
 }
}

Can we create our custom view engine using MVC?

Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to follow 3 steps:-

Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.

Step 1:- We need to create a class which implements “IView” interface. In this class we should write the logic of how the view will be rendered in the “render” function. Below is a simple code snippet for the same.

 

Collapse | Copy Code
public class MyCustomView : IView
    {
        private string _FolderPath; // Define where  our views are stored
        public string FolderPath
        {
            get { return _FolderPath; }
            set { _FolderPath = value; }
        }

        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
           // Parsing logic <dateTime>
            // read the view file
            string strFileData = File.ReadAllText(_FolderPath);
            // we need to and replace <datetime> datetime.now value
            string strFinal = strFileData.Replace("<DateTime>", DateTime.Now.ToString());
            // this replaced data has to sent for display
            writer.Write(strFinal);
        }
    }

 

Step 2 :-We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the folder path and the extension of the view name. For instance for razor the extension is “cshtml” , for aspx the view extension is “.aspx” , so in the same way for our custom view we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is “.myview”.

Collapse | Copy Code
public class MyViewEngineProvider : VirtualPathProviderViewEngine
    {
        // We will create the object of Mycustome view
        public MyViewEngineProvider() // constructor
        {
            // Define the location of the View file
            this.ViewLocationFormats = new string[] { "~/Views/{1}/{0}.myview", "~/Views/Shared/{0}.myview" }; //location and extension of our views
        }
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(viewPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            var physicalpath = controllerContext.HttpContext.Server.MapPath(partialPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine class
            obj.FolderPath = physicalpath; // set the path where the views will be stored
            return obj; // returned this view paresing logic so that it can be registered in the view engine collection
        }
    }

Step 3:- We need to register the view in the custom view collection. The best place to register the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code snippet for the same.

Collapse | Copy Code
protected void Application_Start()
 {
            // Step3 :-  register this object in the view engine collection
            ViewEngines.Engines.Add(new MyViewEngineProvider());
<span class="Apple-tab-span" style="white-space: pre; ">	</span>…..
}

Below is a simple output of the custom view written using the commands defined at the top.

Figure:-customviewengineusingMVC

If you invoke this view you should see the following output.

How to send result back in JSON format in MVC?

In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a simple sample code which returns back “Customer” object in JSON format using “JsonResult”.

Collapse | Copy Code
public JsonResult getCustomer()
{
Customer obj = new Customer();
obj.CustomerCode = "1001";
obj.CustomerName = "Shiv";
 return Json(obj,JsonRequestBehavior.AllowGet);
}

Below is the JSON output of the above code if you invoke the action via the browser.

What is “WebAPI”?

HTTP is the most used protocol.For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile,javascripts,windows  application etc.

For satisfying the broad range of client “REST” was the proposed approach. You can read more about “REST” from WCF chapter.

“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

But WCF SOAP also does the same thing, so how does “WebAPI” differ?

SOAP WEB API
Size Heavy weight because of complicated WSDL structure. Light weight, only the necessary information is transferred.
Protocol Independent of protocols. Only  for HTTP protocol
Formats To parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. Output of “WebAPI” are simple string message,JSON,Simple XML format etc. So writing parsing logic for the same in very easy.
Principles SOAP follows WS-* specification. WEB API follows REST principles. (Please refer about REST in WCF chapter).

With WCF also you can implement REST,So why “WebAPI”?

WCF was brought in to implement SOA, never the intention was to implement REST.”WebAPI'” is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

How to implement “WebAPI” in MVC?

Below are the steps to implement “webAPI” :-

Step1:-Create the project using the “WebAPI” template.

Figure:- implement “WebAPI” in MVC

Step 2:- Once you have created the project you will notice that the controller now inherits from “ApiController” and you can now implement “post”,”get”,”put” and “delete” methods of HTTP protocol.

Collapse | Copy Code
public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }

Step 3:-If you make a HTTP GET call you should get the below results.

Figure:- HTTP

Finally do not forget to visit my video site which covers lots of C# interview questions and answers: –www.questpond.com

from:http://www.codeproject.com/Articles/556995/Model-view-controller-MVC-Interview-questions-and

AutoMapper使用笔记

AutoMapper是一个.NET的对象映射工具。

项目地址:https://github.com/AutoMapper/AutoMapper

帮助文档:https://github.com/AutoMapper/AutoMapper/wiki

主要用途

领域对象与DTO之间的转换、数据库查询结果映射至实体对象。

使用笔记

场景1:源类型BlogEntry,目标类型BlogPostDto,指定属性进行映射(BlogEntry.ID对应于BlogPostDto.PostId)。

代码:

AutoMapper.Mapper.CreateMap<BlogEntry, BlogPostDto>()                 .ForMember(dto => dto.PostId, opt => opt.MapFrom(entity => entity.ID));

场景2:IDataReader映射至实体类

代码:

复制代码
using (IDataReader reader = _db.ExecuteReader(command)) {     if (reader.Read())     {         return AutoMapper.Mapper.DynamicMap<BlogConfig>(reader);     } }
复制代码

 

场景3:列表类型之间的映射,比如:源类型List<BlogSite>,目标类型List<BlogSiteDto>

代码如下:

AutoMapper.Mapper.CreateMap<BlogSite, BlogSiteDto>(); var blogSiteDto = AutoMapper.Mapper.Map<List<BlogSite>, List<BlogSiteDto>>(blogSite);

注:必须要先通过CreateMap建立BlogSite与BlogSiteDto的映射关系。

 

场景4:在映射时为目标实例的属性指定值

代码如下:

var blogSiteDto = new BlogSiteDto(); AutoMapper.Mapper.CreateMap<BlogEntry, BlogPostDto>()                 .ForMember(dto => dto.BlogSiteDto, opt => opt.UseValue(blogSiteDto));

注:BlogSiteDto是BlogPostDto的一个属性。

 

补充:

AutoMapper的配置(比如AutoMapper.Mapper.CreateMap<BlogSite, BlogSiteDto>();)建议放在程序启动时,比如Global.asax的Application_Start, BootStrapper。

from:http://www.cnblogs.com/dudu/archive/2011/12/16/2284828.html