SpringMVC
1.MVC介绍
mvc全类名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,它是一种软件设计典范,是一种软件框架设计分层模式。
Model:是应用程序中处于处理应用程序数据逻辑的部分
View:是应用程序中处理数据显示的部分。
Controller:是应用程序中处理用户交互的部分。
最典型的MVC就是:JSP+Servlet+javabean模式。
2.MVC发展历史
- Model 1(jsp+javabean)
- Model 2(jsp+servlet+javabean)
目前市场上的MVC框架
- 3.1SpringMVC(主流MVC框架):是spring框架的一部分(子框架),是实现对servlet技术进行封装。
- 3.2Struts
- 3.3Jfinal
1.SpringMVC运行原理(执行过程)
整理流程
具体步骤:
1、 首先用户发送请求到前端控制器,前端控制器根据请求信息(如 URL)来决定选择哪一个页面控制器进行处理并把请求委托给它,即以前的控制器的控制逻辑部分;图中的 1、2 步骤;
2、 页面控制器接收到请求后,进行功能处理,首先需要收集和绑定请求参数到一个对象,这个对象在 Spring Web MVC 中叫命令对象,并进行验证,然后将命令对象委托给业务对象进行处理;处理完毕后返回一个 ModelAndView(模型数据和逻辑视图名);图中的 3、4、5 步骤;
3、 前端控制器收回控制权,然后根据返回的逻辑视图名,选择相应的视图进行渲染,并把模型数据传入以便视图渲染;图中的步骤 6、7;
4、 前端控制器再次收回控制权,将响应返回给用户,图中的步骤 8;至此整个结束。
核心流程
具体步骤:
第一步:发起请求到前端控制器(DispatcherServlet)
第二步:前端控制器请求HandlerMapping查找 Handler (可以根据xml配置、注解进行查找)
第三步:处理器映射器HandlerMapping向前端控制器返回Handler,HandlerMapping会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象,多个HandlerInterceptor拦截器对象),通过这种策略模式,很容易添加新的映射策略
第四步:前端控制器调用处理器适配器去执行Handler
第五步:处理器适配器HandlerAdapter将会根据适配的结果去执行Handler
第六步:Handler执行完成给适配器返回ModelAndView
第七步:处理器适配器向前端控制器返回ModelAndView (ModelAndView是springmvc框架的一个底层对象,包括 Model和view)
第八步:前端控制器请求视图解析器去进行视图解析 (根据逻辑视图名解析成真正的视图(jsp)),通过这种策略很容易更换其他视图技术,只需要更改视图解析器即可
第九步:视图解析器向前端控制器返回View
第十步:前端控制器进行视图渲染 (视图渲染将模型数据(在ModelAndView对象中)填充到request域)
第十一步:前端控制器向用户响应结果
(此处参考https://www.cnblogs.com/leskang/p/6101368.html)
在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。此外Controller 不会直接依赖于HttpServletRequest 和HttpServletResponse 等HttpServlet 对象,它们可以通过Controller 的方法参数灵活的获取到。
2.需求:
用户提交一个请求,服务端处理器接收到请求后,给出一条信息,在相应页面中显示该条信息
package com.bjsxt.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; //后端控制器 public class MyController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = new ModelAndView(); System.out.println("进入到后端控制器方法!"); mv.addObject("msg", "Hello SpringMVC!"); mv.setViewName("/jsp/welcome.jsp"); return mv; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册后端控制器 --> <bean id="/my.do" class="com.bjsxt.handlers.MyController"></bean> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${msg} </body> </html>
配置式开发
3.开发步骤
3.1导入jar包
3.2配置web.xml,注册SpringMVC前端控制器(中央调度器)
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
3.3编写SpringMVC后端控制器
package com.bjsxt.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; //后端控制器 public class MyController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = new ModelAndView(); System.out.println("进入到后端控制器方法!"); mv.addObject("msg", "Hello SpringMVC!"); mv.setViewName("/jsp/welcome.jsp"); return mv; } }
3.4编写springmvc配置文件,注册后端控制器(注意id写法格式)
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册后端控制器 --> <bean id="/my.do" class="com.bjsxt.handlers.MyController"></bean> </beans>
3.5编写跳转资源页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${msg} </body> </html>
4.web.xml中urlpattern配置问题
4.1配置/和配置/*的区别
- /:拦截静态资源
- /*:会报错,所有资源都会拦截包括zip资源。
4.2静态资源无法访问解决方案(三种)
第一种方案:
web.xml中配置
第二种解决方案:
- 在springmvc.xml下直接加入:<mvc:default-servlet-handler/>
第三种
- 在springmvc.xml下直接加入:
- <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> //该路径下的所有资源都能访问到
web.xml
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册后端控制器 --> <bean id="/my.do" class="com.bjsxt.handlers.MyController"></bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
controller
package com.bjsxt.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; //后端控制器 public class MyController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = new ModelAndView(); System.out.println("进入到后端控制器方法!"); mv.addObject("msg", "Hello SpringMVC!"); mv.setViewName("/jsp/welcome.jsp"); return mv; } }
注解式开发
1.搭建环境
- 1.1 后端控制器无需实现接口,添加相应注解
- 1.2 springmvc配置文件无需注册controller
- 1.3 springmvc配置文件中添加组件扫描器、注解驱动
<mvc:annotation-driven /> 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持
(Jackson)等等。
2.涉及常用注解
- @Controller、@RequestMapping(类体上【命名空间】、方法上)、@Scope
<mvc:annotation-driven>:提供数据绑定支持,xml读写,json支持。
controller
package com.bjsxt.handlers; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hadleRequest") public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = new ModelAndView(); System.out.println("进入到后端控制器方法!"); mv.addObject("msg", "Hello SpringMVC!"); mv.setViewName("/jsp/welcome.jsp"); return mv; } }
springmvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
web.xml
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.视图解析器(前缀、后缀)
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public String hello(){ return "welcome"; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
4.处理器方法常用的参数(五类)
(这些参数可以放在controller的形参里面,拿来直接用)
4.1 HttpServletRequest
4.2 HttpServletResponse
4.3 HttpSession
4.4 用于承载数据的Model、Map、ModelMap【代码示例】
4.5 请求中所携带的请求参数
下面是关于传递参数到jsp的几种方式的代码。
接收值--四种方法:
第一种:参数直接写在controller参数列表中
@RequestMapping("/test1.action")
public ModelAndView test1(String name){
System.out.println(name);
return null;
}
第二种:request
@RequestMapping("/test2.action")
public ModelAndView test2(HttpServletRequest request){
System.out.println(request.getParameter("name"));
return null;
}
第三种:指定传参
@RequestMapping("/test3.action")
public ModelAndView test3(@RequestParam("name3") String name){
System.out.println(name);
return null;
}
第四种:通过对象(jsp页面的name里面的值必须和实体类的属性一致,才能用对象接收)
@RequestMapping("/test4.action")
public ModelAndView test4(User user){
System.out.println(user);
return null;
}
传值--三种方法:
第一种:request
@RequestMapping("/test5.action")
public String test5(HttpServletRequest request,User user){
request.setAttribute("message", user.getName());
return null;
}
第二种:ModelAndView
@RequestMapping("/test6.action")
public ModelAndView test6(User user){
System.out.println(user);
ModelAndView mv = new ModelAndView();
mv.addObject("message", user.getName() );
mv.setViewName("/index1.jsp");
return mv;
}
第三种:Model
@RequestMapping("/test7.action")
public String test7(User user,Model model){
System.out.println(user);
model.addAttribute("message", user.getName() + " hello");
return "/index1.jsp";
}
第四种map
@Controller public class MapController { /** * 映射路径:/map * * 这里username是从View传到Controller,可写可不写。 */ @RequestMapping("/map") public String index(String username, Map<String, Object> map) { System.out.println("Hello Spring MVC map " + username); map.put("name", username + "六的一批"); return "index"; } } 前端接收很简单,新建一个index.jsp,这里index命名要对应上面return "index",这样控制器才能找到页面. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Controller向View传值</title> </head> <body> <h1>hello SpringMVC!!!</h1> <h1>Map传参</h1> <h2>username(key:name)-->${name }</h2> </body> </html>
第五种使用@ModelAttribute注解
方法1:@modelAttribute在函数参数上使用,在页面端可以通过HttpServletRequest传到页面中去
@RequestMapping(value="/reciveData3",method=RequestMethod.GET) public ModelAndView StartPage3(@ModelAttribute("user") User user) { user.setPassword("123456"); user.setUserName("ZhangSan"); return new ModelAndView("reciveControllerData"); }
方法2:@ModelAttribute在属性上使用
@RequestMapping(value="/reciveData4",method=RequestMethod.GET) public ModelAndView StartPage4() { sthname="LiSi"; return new ModelAndView("reciveControllerData"); } /*一定要有sthname属性,并在get属性上取加上@ModelAttribute属性*/ private String sthname; @ModelAttribute("name") public String getName(){ return sthname; }
第六种modelmap
@RequestMapping(value="/reciveData2",method=RequestMethod.GET) public ModelAndView StartPage2(ModelMap map) { User user=new User(); user.setPassword("123456"); user.setUserName("ZhangSan"); map.put("user", user); return new ModelAndView("reciveControllerData"); }
4、 使用@ModelAttribute注解
/*直接用httpServletRequest的Session保存值。
* */
@RequestMapping(value="/reciveData5",method=RequestMethod.GET) public ModelAndView StartPage5(HttpServletRequest request) { User user=new User(); user.setPassword("123456"); user.setUserName("ZhangSan"); HttpSession session=request.getSession(); session.setAttribute("user", user); return new ModelAndView("reciveControllerData"); }
5.接收请求参数
5.1 逐个接收 (涉及注解@RequestParam)
前提:处理器名和index.jsp的值必须一致,才能接收。
解决办法:
public ModelAndView hello(@RequestParam("username") String name,int age)
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public ModelAndView hello(@RequestParam("username") String name,int age){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", name); modelAndView.addObject("age", age); modelAndView.setViewName("welcome"); return modelAndView; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
welcome
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 欢迎页面!${username}--${age} </body> </html>
5.2 以对象形式整体接收
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public ModelAndView hello(Star star){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", star.getUsername()); modelAndView.addObject("age", star.getAge()); modelAndView.setViewName("welcome"); return modelAndView; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/hello" method="POST"> <input type="text" name="username"></br> <input type="text" name="age"></br> <input type="submit" value="提交"> </form> </body> </html>
5.3 域属性参数的接收
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/hello" method="POST"> 用户名:<input type="text" name="username"></br> 年龄:<input type="text" name="age"></br> 伴侣名称:<input type="text" name="parter.name"></br> <input type="submit" value="提交"> </form>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public ModelAndView hello(Star star){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", star.getUsername()); modelAndView.addObject("age", star.getAge()); modelAndView.addObject("partnerName", star.getParter().getName()); modelAndView.setViewName("welcome"); return modelAndView; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
5.4 数组或集合参数的接收
package com.bjsxt.handlers; import java.util.List; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //数组接收参数 /* @RequestMapping("/hello") public void hello(String[] interest){ for (String string : interest) { System.out.println(string); } } */ //集合接收参数 @RequestMapping("/hello") public void hello1(@RequestParam List<String> interest){ for (String string : interest) { System.out.println(string); } } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/hello" method="POST"> <input type="checkbox" name="interest" value="a1">a1</br> <input type="checkbox" name="interest" value="a2">a2</br> <input type="checkbox" name="interest" value="a3">a3</br> <input type="submit" value="提交"> </form> </body> </html>
5.5 restfull风格,传参(涉及注解@ PathVariable)
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //restful风格传参 @RequestMapping("/{name}/{age}/hello") public void hello1(@PathVariable String name,@PathVariable int age){ System.out.println(name+age); } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
5.6 接收json字符串(涉及注解@RequestBody,注册mvc注解驱动,导入jackson包)
controller
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //接收json字符串并封装成对象 @RequestMapping("/hello") public void hello1(@RequestBody Star star){ System.out.println(star); } }
partner
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
star
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
springmvc.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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> </beans>
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function(){ $("#myButton").click(function(){ var data1={username:"zhangsan",age:23}; $.ajax({ url:"${pageContext.request.contextPath}/springmvc/hello", type: "POST", contentType:"application/json", data:JSON.stringify(data1), }) }) }) </script> <title>Insert title here</title> </head> <body> <button id="myButton">点击我呀!</button> </body> </html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 欢迎页面!${username}--${age}--${partnerName} </body> </html>
6.获取请求头中参数(涉及注解@RequestHeader)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="${pageContext.request.contextPath}/springmvc/hello">点击我呀!</a> </body> </html>
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //接收json字符串并封装成对象 @RequestMapping("/hello") public void hello1(@RequestHeader String host,@RequestHeader String cookie){ System.out.println(host + " ----------"+cookie); } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> </beans>
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
处理器方法的返回值
7.1 ModelAndView
7.2 String
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/springmvc/hello" method="POST"> 姓名:<input type="text" name="username"><br/> 年龄:<input type="text" name="age"><br/> <input type="submit" value="提交"><br/> </form> </body> </html>
package com.bjsxt.handlers; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //接收json字符串并封装成对象 @RequestMapping("/hello") public String hello1(String username,int age,Model model,Map<String, Object> map,ModelMap modelMap){ System.out.println(username + " ----------"+age); model.addAttribute("username", username); map.put("age", age); modelMap.addAttribute("gender", "female"); return "welcome"; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> </beans>
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 欢迎页面!${username}--${age}--${gender} </body> </html>
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //接收json字符串并封装成对象 @RequestMapping(value="/hello",produces="text/html;charset=utf-8") @ResponseBody public String hello1(){ return "china:瓷器"; } }
7.3 void
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.7.2.min.js"></script> <script type="text/javascript"> $(function(){ $("#myButton").click(function(){ $.ajax({ url:"${pageContext.request.contextPath}/springmvc/hello", type: "POST", success: function(data){ var data1 = eval("("+data+")"); alert(data1.flavor); } }) }) }) </script> <title>Insert title here</title> </head> <body> <button id="myButton">点击我呀!</button> </body> </html>
package com.bjsxt.handlers; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.bjsxt.pojo.Star; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ //接收json字符串并封装成对象 @RequestMapping(value="/hello",produces="text/html;charset=utf-8") public void hello1(HttpServletResponse response) throws IOException{ String json="{\"name\":\"weilong\",\"flavor\":\"hot\"}"; response.getWriter().print(json); } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
7.4 Object(涉及注解@ResponseBody ,注册mvc注解驱动,导入jackson2.5包)
8.请求转发与重定向
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/hello" method="POST"> <input type="text" name="username"></br> <input type="text" name="age"></br> <input type="submit" value="提交"> </form> </body> </html>
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public ModelAndView hello(String username,int age){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", username); modelAndView.addObject("age", age); modelAndView.setViewName("redirect:some"); return modelAndView; } @RequestMapping("/some") public ModelAndView some(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("welcome"); return modelAndView; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
package com.bjsxt.handlers; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/hello") public ModelAndView hello(String username,int age){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("username", username); modelAndView.addObject("age", age); modelAndView.setViewName("redirect:/jsp/welcome.jsp"); return modelAndView; } }
9.文件上传(注册mvc注解驱动、文件上传解析器,导入相关jar包)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/fileUpload" method="POST" enctype="multipart/form-data"> <input type="file" name="img"></br> <input type="submit" value="上传"> </form> </body> </html>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
package com.bjsxt.handlers; import java.io.File; import java.io.IOException; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/fileUpload") public String fileUpload(MultipartFile img){ String path="d:/"; String fileName = img.getOriginalFilename(); File file = new File(path, fileName ); try { img.transferTo(file); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "welcome"; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="springmvc/fileUpload" method="POST" enctype="multipart/form-data"> <input type="file" name="imgs"></br> <input type="file" name="imgs"></br> <input type="file" name="imgs"></br> <input type="submit" value="上传"> </form> </body> </html>
package com.bjsxt.handlers; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpSession; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/fileUpload") public String fileUpload(@RequestParam MultipartFile[] imgs,HttpSession session){ String path=session.getServletContext().getRealPath("/"); for (MultipartFile img : imgs) { String fileName = img.getOriginalFilename(); File file = new File(path, fileName ); try { img.transferTo(file); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return "welcome"; } }
10.文件下载
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="${pageContext.request.contextPath}/springmvc/fileDowload">点击下载</a> </body> </html>
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>springmvc-01-primary</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 静态资源无法访问第一种解决方案 --> <!-- <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> --> <!-- 注册springmvc前端控制器(中央调度器) --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定springmvc配置文件的路径以及名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
package com.bjsxt.handlers; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.springframework.context.annotation.Scope; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller //该注解表将当前类交给spring容器管理 @Scope("prototype") @RequestMapping("/springmvc") //该注解起到限定范围的作用 public class MyController{ @RequestMapping("/fileDowload") public ResponseEntity<byte[]> dowload() throws IOException{ //指定下载文件 File file = new File("d:/美女.png"); InputStream is = new FileInputStream(file); //创建字节数组,并且设置数组大小为预估的文件字节数 byte[] body = new byte[is.available()]; //将输入流中字符存储到缓存数组中 is.read(body); //获取下载显示的文件名,并解决中文乱码 String name = file.getName(); String downLoadFileName = new String(name.getBytes("UTF-8"),"ISO-8859-1"); //设置Http响应头信息,并且通知浏览器以附件的形式进行下载 HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Disposition", "attachment;filename="+downLoadFileName); //设置Http响应状态信息 HttpStatus status = HttpStatus.OK; ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, httpHeaders, status); return responseEntity; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
11.拦截器(实现HandlerInterceptor接口;注册拦截器<mvc:interceptors>)
package com.bjsxt.handlers; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller @Scope("prototype") @RequestMapping("/springmvc") public class MyController{ @RequestMapping("/hello") public String hello1(String username,int age,Model model,Map<String, Object> map,ModelMap modelMap){ System.out.println(username + " ----------"+age); model.addAttribute("username", username); map.put("age", age); modelMap.addAttribute("gender", "female"); return "welcome"; } @RequestMapping("/hello2") public String hello2(String username,int age,Model model,Map<String, Object> map,ModelMap modelMap){ System.out.println(username + " 2222----------2222"+age); model.addAttribute("username", username); map.put("age", age); modelMap.addAttribute("gender", "female"); return "welcome"; } }
package com.bjsxt.interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; //自定义拦截器 public class FirstInterceptor implements HandlerInterceptor { //该方法执行时机:处理器方法执行之前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("拦截器preHandle()执行!"); return true; } //该方法执行时机:处理器方法执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("拦截器postHandle()执行!"); } //该方法执行时机:所有工作处理完成之后,响应给浏览器客户端之前执行 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("拦截器afterCompletion()执行!"); } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 注册拦截器 --> <mvc:interceptors> <mvc:interceptor> <!-- <mvc:mapping path="/springmvc/hello"/> --> <mvc:mapping path="/**"/> <!-- <mvc:exclude-mapping path="/springmvc/hello2"/> --> <bean id="" class="com.bjsxt.interceptors.FirstInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> </beans>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/springmvc/hello2" method="POST"> 姓名:<input type="text" name="username"><br/> 年龄:<input type="text" name="age"><br/> <input type="submit" value="提交"><br/> </form> </body> </html>
package com.bjsxt.interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; //自定义拦截器 public class FirstInterceptor implements HandlerInterceptor { //该方法执行时机:处理器方法执行之前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("First拦截器preHandle()执行!"); return true; } //该方法执行时机:处理器方法执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("First拦截器postHandle()执行!"); } //该方法执行时机:所有工作处理完成之后,响应给浏览器客户端之前执行 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("First拦截器afterCompletion()执行!"); } }
package com.bjsxt.interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class SecondInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("Second的preHandle()执行!"); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("Second的postHandle()执行!"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("Second的afterCompletion()执行!"); } }
package com.bjsxt.handlers; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; //后端控制器 @Controller @Scope("prototype") @RequestMapping("/springmvc") public class MyController{ @RequestMapping("/hello2") public String hello2(String username,int age,Model model,Map<String, Object> map,ModelMap modelMap){ System.out.println(username + " 2222----------2222"+age); model.addAttribute("username", username); map.put("age", age); modelMap.addAttribute("gender", "female"); return "welcome"; } }
package com.bjsxt.pojo; public class Parter { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.bjsxt.pojo; public class Star { private String username; private int age; //域属性,也称为对象属性 private Parter parter; public Parter getParter() { return parter; } public void setParter(Parter parter) { this.parter = parter; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Star [username=" + username + ", age=" + age + ", parter=" + parter + "]"; } }
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注册组件扫描器 --> <context:component-scan base-package="com.bjsxt.handlers"></context:component-scan> <!-- 注册注解驱动 --> <mvc:annotation-driven/> <!-- 注册视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 注册拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean id="" class="com.bjsxt.interceptors.FirstInterceptor"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean id="" class="com.bjsxt.interceptors.SecondInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> <!-- 静态资源无法访问第二种解决方案 --> <!-- <mvc:default-servlet-handler/> --> <!-- 静态资源无法访问第三种解决方案 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> </beans>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/springmvc/hello2" method="POST"> 姓名:<input type="text" name="username"><br/> 年龄:<input type="text" name="age"><br/> <input type="submit" value="提交"><br/> </form> </body> </html>
看源码了解拦截器方法执行顺序。
12.Spring和SpringMVC父子容器关系
在Spring整体框架的核心概念中,容器是核心思想,就是用来管理Bean的整个生命周期的,
而在一个项目中,容器不一定只有一个,Spring中可以包括多个容器,而且容器有上下层关
系,目前最常见的一种场景就是在一个项目中引入Spring和SpringMVC这两个框架,那么它
其实就是两个容器,Spring是父容器,SpringMVC是其子容器,并且在Spring父容器中注册
的Bean对于SpringMVC容器中是可见的,而在SpringMVC容器中注册的Bean对于Spring父容器
中是不可见的,也就是子容器可以看见父容器中的注册的Bean,反之就不行
/**