1.web.xml 配置:

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

这样,所有的.htm的请求,都会被DispatcherServlet处理;

初始化 DispatcherServlet 时,该框架在 web 应用程序WEB-INF 目录中寻找一个名为[servlet-名称]-servlet.xml的文件,并在那里定义相关的Beans,重写在全局中定义的任何Beans,像上面的web.xml中的代码,对应的是dispatcher-servlet.xml;当然也可以使用<init-param>元素,手动指定配置文件的路径;dispatcher-servlet.xml 配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!--
使Spring支持自动检测组件,如注解的Controller
-->
<context:component-scan base-package="com.minx.crm.web.controller"/> <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>

2.spring mvc处理方法支持如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void

ModelAndView

@RequestMapping("/show1")
public ModelAndView show1(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("/demo2/show");
mav.addObject("account", "account -1");
return mav;
}

通过ModelAndView构造方法可以指定返回的页面名称,也可以通过setViewName()方法跳转到指定的页面 , 使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。 调用addObject()方法将值设置到一个名为ModelMap的类属性,ModelMap是LinkedHashMap的子类, 具体请看类。

Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类。

model.addAttribute("pojo", pojo);

Map

@RequestMapping("/demo2/show")
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value-1");
map.put("key2", "value-2");
return map;
}

在jsp页面中可直通过${key1}获得到值, map.put()相当于request.setAttribute方法。 写例子时发现,key值包括 - . 时会有问题.

View 可以返回pdf excel等,暂时没详细了解。

String 指定返回的视图页面名称,结合设置的返回地址路径加上页面名称后缀即可访问到。

注意:如果方法声明了注解@ResponseBody ,则会直接将返回值输出到页面。 例如:

@RequestMapping(value = "/something", method = RequestMethod.GET)
@ResponseBody
public String helloWorld() {
return"Hello World";
}

上面的结果会将文本"Hello World "直接写到http响应流。

@RequestMapping("/welcome")
public String welcomeHandler() {
return"center";
}

对应的逻辑视图名为“center”,URL= prefix前缀+视图名称 +suffix后缀组成。
void  如果返回值为空,则响应的视图页面对应为访问地址

@RequestMapping("/welcome")
publicvoid welcomeHandler() {}

此例对应的逻辑视图名为"welcome"。

小结:

1.使用 String 作为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具有很大的灵活性,而模型数据又可以通过 ModelMap 控制。 2.使用void,map,Model 时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成。 3.使用String,ModelAndView返回视图名称可以不受请求的url绑定,ModelAndView可以设置返回的视图名称。

Model model,HttpServletRequest request, ModelMap map声明变量

request.getSession().setAttribute("test", "haiwei2Session"); request.setAttribute("test", "haiwei1request"); map.addAttribute("test", "haiweiModelMap"); model.addAttribute("test", "haiweiModel");
我通过${test}这个方式取值,优先取Model和ModelMap的,Model和ModelMap是同一个东西,谁最后赋值的就取谁的,然后是request,最后是从session中获取

第一个Controller:

package com.minx.crm.web.controller;  

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}
package com.minx.crm.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/index")
public String index() {
return "index";
}
}

@Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径(/index.htm),return "index"标记返回视图(index.jsp);

注:如果@RequestMapping注解在类级别上,则表示一相对路径,在方法级别上,则标记访问的路径;

从@RequestMapping注解标记的访问路径中获取参数:

Spring MVC 支持RESTful风格的URL参数,如:

@Controller
public class IndexController { @RequestMapping("/index/{username}")
public String index(<span style="color: rgb(255, 0, 0);">@PathVariable</span>("username") String username) {
System.out.print(username);
return "index";
}
}
@Controller
public class IndexController { @RequestMapping("/index/{username}")
public String index(@PathVariable("username") String username) {
System.out.print(username);
return "index";
}
}

在@RequestMapping中定义访问页面的URL模版,使用{}传入页面参数,使用@PathVariable 获取传入参数,即可通过地址:http://localhost:8080/crm/index/tanqimin.htm 访问;

根据不同的Web请求方法,映射到不同的处理方法:

使用登陆页面作示例,定义两个方法分辨对使用GET请求和使用POST请求访问login.htm时的响应。可以使用处理GET请求的方法显示视图,使用POST请求的方法处理业务逻辑;

@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login2(HttpServletRequest request) {
String username = request.getParameter("username").trim();
System.out.println(username);
return "login2";
}
}
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login2(HttpServletRequest request) {
String username = request.getParameter("username").trim();
System.out.println(username);
return "login2";
}
}

在视图页面,通过地址栏访问login.htm,是通过GET请求访问页面,因此,返回登陆表单视图login.jsp;当在登陆表单中使用POST请求提交数据时,则访问login2方法,处理登陆业务逻辑;

防止重复提交数据,可以使用重定向视图:

return "redirect:/login2"  
return "redirect:/login2"

可以传入方法的参数类型:

<strong>@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}</strong>
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}

可以传入HttpServletRequest、HttpServletResponse、HttpSession,值得注意的是,如果第一次访问页面,HttpSession没被创建,可能会出错;

其中,String username = request.getParameter("username");可以转换为传入的参数:

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
String username = request.getParameter("username");
System.out.println(username);
return null;
} 使用@RequestParam 注解获取GET请求或POST请求提交的参数; 获取Cookie的值:使用@CookieValue :
获取printwriter:
可以直接在Controller的方法中传入PrintWriter对象,就可以在方法中使用:
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, <span style="color: rgb(255, 0, 0);">@RequestParam</span>("username") String username) {
out.println(username);
return null;
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, @RequestParam("username") String username) {
out.println(username);
return null;
}

获取表单中提交的值,并封装到POJO中,传入Controller的方法里:

POJO如下(User.java):

public class User{
private long id;
private String username;
private String password; …此处省略getter,setter...
}
public class User{
private long id;
private String username;
private String password; …此处省略getter,setter...
}

通过表单提交,直接可以把表单值封装到User对象中:

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, User user) {
out.println(user.getUsername());
return null;
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, User user) {
out.println(user.getUsername());
return null;
}

可以把对象,put 入获取的Map对象中,传到对应的视图:

<strong>@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
model.put("user",user);
return "view";
}</strong>
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
model.put("user",user);
return "view";
}

在返回的view.jsp中,就可以根据key来获取user的值(通过EL表达式,${user }即可);

Controller中方法的返回值:

void:多数用于使用PrintWriter输出响应数据;

String 类型:返回该String对应的View Name;

任意类型对象:

返回ModelAndView:

自定义视图(JstlView,ExcelView):

拦截器(Inteceptors):

<strong>public class MyInteceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)
throws Exception {
}
}</strong>
public class MyInteceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)
throws Exception {
return false;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)
throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)
throws Exception {
}
}

拦截器需要实现HandleInterceptor接口,并实现其三个方法:

preHandle:拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,Object o表示下一个拦截器;

postHandle:控制器的方法已经执行完毕,转换成视图之前的处理;

afterCompletion:视图已处理完后执行的方法,通常用于释放资源;

在MVC的配置文件中,配置拦截器与需要拦截的URL:

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/index.htm" />
<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/index.htm" />
<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

国际化:

在MVC配置文件中,配置国际化属性文件:

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="message">
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basename="message">
</bean>

那么,Spring就会在项目中搜索相关的国际化属性文件,如:message.properties、message_zh_CN.properties

在VIEW中,引入Spring标签:<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>,使用<spring:message code="key" />调用,即可;

如果一种语言,有多个语言文件,可以更改MVC配置文件为:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>message01</value>
<value>message02</value>
<value>message03</value>
</list>
</property>
</bean>

SpingMVC ModelAndView, Model,Control以及参数传递的更多相关文章

  1. SpingMVC ModelAndView, Model,Control以及参数传递总结

    1.web.xml 配置: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <servlet>     <servlet-name>dispatcher& ...

  2. SpringMVC学习 -- ModelAndView , Model , ModelMap , Map 及 @SessionAttributes 的使用

    输出模型数据: ModelAndView:处理方法返回值类型为 ModelAndView 时 , 其中包含视图和模型信息.方法体即可通过该对象添加模型数据 , 即 SpringMVC 会把 Model ...

  3. springMVC:modelandview,model,controller,参数传递

    转载:http://blog.csdn.net/wm5920/article/details/8173480 1.web.xml 配置: copy   <> ></> & ...

  4. Spring框架中ModelAndView、Model、ModelMap区别

    原文地址:http://www.cnblogs.com/google4y/p/3421017.html SPRING框架中ModelAndView.Model.ModelMap区别   注意:如果方法 ...

  5. SpringMVC ModelAndView、Map、Model、ModelMap

    目标方法返回值可以是ModelAndView .Map.Model.ModelMap类型,但最根本还都是ModelAndView. 其中可以包含试图和模型信息. SpringMVC 会把ModelAn ...

  6. spring mvc EL ModelAndView的 Model 值 在jsp中不显示

    问题:spring mvc开发过程中, 经常会给model addAttribute, 然后通过EL在jsp中显示,比如 ${msg}, 但是有时候会出现jsp最后显示的还是${msg},而不是msg ...

  7. SPRING框架中ModelAndView、Model、ModelMap区别及详细分析

    转载内容:http://www.cnblogs.com/google4y/p/3421017.html 1. Model Model 是一个接口, 其实现类为ExtendedModelMap,继承了M ...

  8. Spring框架中ModelAndView、Model、ModelMap区别 (转)

    原文地址:http://www.cnblogs.com/google4y/p/3421017.html SPRING框架中ModelAndView.Model.ModelMap区别   注意:如果方法 ...

  9. Spring MVC:Model、View、ModelAndView

    个人理解:View为服务器上的某个文件容器,可以为JSP,FTL等动态页面文件,甚至是媒体文件等等,单单是一个文件.Model的作用是存储动态页面属性,动态页面文件即View可以在Model中获取动态 ...

随机推荐

  1. java中final的理解

    final修饰变量表示变量初始化后就不能再改变. 一.对于基础类型来说,用final修饰后其值不可以改变. 1. final int a; a = 5; 2.final int a = 5; 二.对于 ...

  2. android Sqlite select * from myDatabase没有内容的问题

    没什么好说的,但是却在初学的时候弄了很久,百度google查了很多资料.后来才发现,竟然是少了个分号结束符的原因. 开始怀疑人生了...

  3. 修复FreeBSD上的ufs文件系统

    昨天在两台FreeBSD上配置好Heartbeat服务(两台机器是用网线连通的,做为Heartbeat的两个节点),启动服务时Heartbeat检测到crmd守护进程没起来,于是它就尝试重启两台机器以 ...

  4. 转:Android开发:使用JNI读取应用签名

    博文转自http://www.tuicool.com/articles/UVjme2r,感谢博主的分享 为了防止被反编译,打算把关键代码写到so里(比如加解密),在so里加上判断APk包签名是否一致的 ...

  5. Sort merge join、Nested loops、Hash join(三种连接类型)

    目前为止,典型的连接类型有3种: Sort merge join(SMJ排序-合并连接):首先生产driving table需要的数据,然后对这些数据按照连接操作关联列进行排序:然后生产probed ...

  6. linux yum命令详解-转

    yum(全称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及SUSE中的Shell前端软件包管理器.基於RPM包管理,能够从指定的服务器自动下载RP ...

  7. lnmp平台菜鸟入门级笔记

                  LNMP平台搭建 Mysql安装  MySQL安装 回复收藏  分享    1 下载MySQL数据库l到/usr/local/src/[root@xin tmp]# cd ...

  8. pt-online-schema-change 修改主键导致数据删除失败的问题调查

    pt-online-schema-change在线DDL工具可以做到DDL操作不锁表,不影响线上操作.对于线上超过100W的大表,一般情况下都用这个工具做DDL,最重要的考虑点还是“不影响线上操作” ...

  9. 【MySQL】锁入门

    要做的完全掌握MySQL/InnoDB的加锁规则,甚至是其他任何数据库的加锁规则,需要具备以下的一些知识点 了解数据库的一些基本理论知识:数据的存储格式 (堆组织表 vs 聚簇索引表):并发控制协议 ...

  10. Supervisor 安装

    在linux或者unix操作系统中,守护进程(Daemon)是一种运行在后台的特殊进程,它独立于控制终端并且周期性的执行某种任务或等待处理某些发生的事件.由于在linux中,每个系统与用户进行交流的界 ...