springMVC课程01

springMVC

一、springMVC体系介绍:

1、javaee体系结构:

2、为什么要使用MVC开发模式?

主要就是为了:解耦和

很多应用程序的问题在于处理业务数据和显示业务数据的视图的对象之间存在紧密耦合。通常,更新业务对象的命令都是从视图本身发起的,使视图对任何业务对象更改都有高度敏感性。而且,当多个视图依赖于同一个业务对象时是没有灵活性的。

Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。

3、springMVC的强大之处:

①.Spring MVC 实现了即用的 MVC 的核心概念。它为控制器和处理程序提供了大量与此模式相关的功能。并且当向 MVC 添加反转控制(Inversion of Control,IoC)时,它使应用程序高度解耦,提供了通过简单的配置更改即可动态更改组件的灵活性。Spring MVC 为您提供了完全控制应用程序的各个方面的力量。

②.Spring 的 Web MVC 模块是围绕 DispatcherServlet 而设计的。DispatcherServlet 给处理程序分派请求,执行视图解析,并且处理语言环境和主题解析,此外还为上传文件提供支持。

③.DispatcherServlet 通过使用处理程序映射来决定哪一个处理程序应当处理传入的请求。处理程序映射只是用于标识使用哪一个处理程序来处理特定 URL 模式的映射。处理程序是只有一种方法 ModelAndView handleRequest(request,response) 的控制器接口的实现。Spring 还有一些可用的高级处理程序实现;其中一个重要的高级处理程序实现是 SimpleFormController,它提供了将命令对象绑定到表单、对其执行验证等功能。

④.您已经在本系列教程的先前教程中使用了 DispatcherServlet 和简单的处理程序。在下一个部分中,将使用 SimpleFormController 并说明 Spring MVC 提供的各种即用功能。

4、springMVC的优势

①、清晰的角色划分:前端控制器(DispatcherServlet)、请求到处理器映射(HandlerMapping)、处理器适配器(HandlerAdapter)、视图解析器(ViewResolver)、处理器或页面控制器(Controller)、验证器( Validator)、命令对象(Command  请求参数绑定到的对象就叫命令对象)、表单对象(Form Object 提供给表单展示和提交到的对象就叫表单对象)。

②、分工明确,而且扩展点相当灵活,可以很容易扩展,虽然几乎不需要;

③、由于命令对象就是一个POJO,无需继承框架特定API,可以使用命令对象直接作为业务对象;

④、和Spring 其他框架无缝集成,是其它Web框架所不具备的;

⑤、可适配,通过HandlerAdapter可以支持任意的类作为处理器;

⑥、可定制性,HandlerMapping、ViewResolver等能够非常简单的定制;

⑦、功能强大的数据验证、格式化、绑定机制;

⑧、利用Spring提供的Mock对象能够非常简单的进行Web层单元测试;

⑨、本地化、主题的解析的支持,使我们更容易进行国际化和主题的切换。

⑩、强大的JSP标签库,使JSP编写更容易。

………………还有比如RESTful风格的支持、简单的文件上传、约定大于配置的契约式编程支持、基于注解的零配置支持等等。

5、springMVC的架构

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

6、 MVC(Model-View-Controller)三元组的概念:

①、Model(模型):数据模型,提供要展示的数据,因此包含数据和行为,可以认为是领域模型或 JavaBean 组件(包含数据和行为),不过现在一般都分离开来:Value Object(数据) 和 服务层(行为)。也就是模型提供了模型数据查询和模型数据的状态更新等功能,包括数据和业务。

领域模型

javaBean组件等价于 域模型层 + 业务逻辑层 + 持久层

②、View(视图):负责进行模型的展示,一般就是我们见到的用户界面,客户想看到的东西。

③、Controller(控制器):接收用户请求,委托给模型进行处理(状态改变),处理完毕后把返回的模型数据返回给视图,由视图负责展示。 也就是说控制器做了个调度员的工作

7、struts2的MVC流程

8、springMVC的运行流程

①、  首先用户发送请求——>DispatcherServlet,前端控制器收到请求后自己不进行处理,而是委托给其他的解析器进行处理,作为统一访问点,进行全局的流程控制;

②、DispatcherServlet——>HandlerMapping,HandlerMapping将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、多个HandlerInterceptor拦截器)对象,通过这种策略模式,很容易添加新的映射策略;

③、  DispatcherServlet——>HandlerAdapter,HandlerAdapter将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,从而很容易支持很多类型的处理器;

④、  HandlerAdapter——>处理器功能处理方法的调用,HandlerAdapter将会根据适配的结果调用真正的处理器的功能处理方法,完成功能处理;并返回一个ModelAndView对象(包含模型数据、逻辑视图名);

⑤、  ModelAndView的逻辑视图名——> ViewResolver, ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术;

⑥、  View——>渲染,View会根据传进来的Model模型数据进行渲染,此处的Model实际是一个Map数据结构,因此很容易支持其他视图技术;

⑦、返回控制权给DispatcherServlet,由DispatcherServlet返回响应给用户,到此一个流程结束。

9、组件说明:

u DispatcherServlet:前端控制器

用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。

u HandlerMapping:处理器映射器

HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。

u Handler:处理器

Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。

由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。

u HandlAdapter:处理器适配器

通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.16 { margin: 0pt; margin-bottom: .0001pt; text-indent: 21.0000pt; text-align: justify; font-family: Calibri; font-size: 10.5000pt }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
table.MsoNormalTable { font-family: "Times New Roman"; font-size: 10.0000pt }
div.Section0 { }

u View Resolver:视图解析器

View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。

u View:视图

springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。

一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。


说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。

需要用户开放的组件有handler、view

二、springMVC基本配置

1、组件扫描器(打开spring的注解开关)

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

使用组件扫描器省去在spring容器配置每个controller类的繁琐。使用<context:component-scan>自动扫描标记@controller的控制器类,配置如下:

<!-- 扫描controller注解,多个包中间使用半角逗号分隔 -->

<context:component-scan base-package="cn.itcast.springmvc.controller"/>

2、RequestMappingHandlerMapping

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

注解式处理器映射器,对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method。

从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。

配置如下:

<!--注解映射器 -->

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

注解描述:

@RequestMapping:定义请求url到处理器功能方法的映射

3、RequestMappingHandlerAdapter

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

注解式处理器适配器,对标记@ResquestMapping的方法进行适配。

从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。

配置如下:

<!--注解适配器 -->

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

4、<mvc:annotation-driven>

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

springmvc使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter,可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。

5、视图解析器

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
table.MsoNormalTable { font-family: "Times New Roman"; font-size: 10.0000pt }
div.Section0 { }

在springmvc.xml文件配置如下:


<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.JstlView" />

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

</bean>

InternalResourceViewResolver:支持JSP视图解析

viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar 包。此属性可以不设置,默认为JstlView。

prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为:

前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,则最终返回的jsp视图地址 “WEB-INF/jsp/hello.jsp”

6、DispatcherServlet核心代码分析、

p.MsoNormal { margin: 0pt; margin-bottom: .0001pt; text-align: justify; font-family: "Times New Roman"; font-size: 10.5000pt }
span.10 { font-family: "Times New Roman" }
span.15 { font-family: "Times New Roman" }
p.MsoFooter { margin: 0pt; margin-bottom: .0001pt; text-align: left; font-family: "Times New Roman"; font-size: 9.0000pt }
p.MsoHeader { margin: 0pt; margin-bottom: .0001pt; border-bottom: 1.0000pt solid windowtext; padding: 0pt 0pt 1pt 0pt; text-align: center; font-family: "Times New Roman"; font-size: 9.0000pt }
span.msoIns { text-decoration: underline; color: blue }
span.msoDel { text-decoration: line-through; color: red }
div.Section0 { }

//前端控制器分派方法

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {

HttpServletRequest processedRequest = request;

HandlerExecutionChain mappedHandler = null;

int interceptorIndex = -1;

try {

ModelAndView mv;

boolean errorView = false;

try {

//检查是否是请求是否是multipart(如文件上传),如果是将通过MultipartResolver解析

processedRequest = checkMultipart(request);

//步骤2、请求到处理器(页面控制器)的映射,通过HandlerMapping进行映射

mappedHandler = getHandler(processedRequest, false);

if (mappedHandler == null || mappedHandler.getHandler() == null) {

noHandlerFound(processedRequest, response);

return;

}

//步骤3、处理器适配,即将我们的处理器包装成相应的适配器(从而支持多种类型的处理器)

HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());

// 304 Not Modified缓存支持

//此处省略具体代码

// 执行处理器相关的拦截器的预处理(HandlerInterceptor.preHandle)

//此处省略具体代码

// 步骤4、由适配器执行处理器(调用处理器相应功能处理方法)

mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

// Do we need view name translation?

if (mv != null && !mv.hasView()) {

mv.setViewName(getDefaultViewName(request));

}

// 执行处理器相关的拦截器的后处理(HandlerInterceptor.postHandle)

//此处省略具体代码

}

catch (ModelAndViewDefiningException ex) {

logger.debug("ModelAndViewDefiningException encountered", ex);

mv = ex.getModelAndView();

}

catch (Exception ex) {

Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);

mv = processHandlerException(processedRequest, response, handler, ex);

errorView = (mv != null);

}

//步骤5 步骤6、解析视图并进行视图的渲染

//步骤5 由ViewResolver解析View(viewResolver.resolveViewName(viewName, locale))

步骤6 视图在渲染时会把Model传入(view.render(mv.getModelInternal(), request, response);)

if (mv != null && !mv.wasCleared()) {

render(mv, processedRequest, response);

if (errorView) {

WebUtils.clearErrorRequestAttributes(request);

}

}

else {

if (logger.isDebugEnabled()) {

logger.debug("Null ModelAndView returned to DispatcherServlet with name ‘" + getServletName() +

"‘: assuming HandlerAdapter completed request handling");

}

}

// 执行处理器相关的拦截器的完成后处理(HandlerInterceptor.afterCompletion)

//此处省略具体代码

catch (Exception ex) {

// Trigger after-completion for thrown exception.

triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex)            throw ex;

}

catch (Error err) {

ServletException ex = new NestedServletException("Handler processing failed", err);

// Trigger after-completion for thrown exception.

triggerAfterCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);

throw ex;

}

finally {

// Clean up any resources used by a multipart request.

if (processedRequest != request) {

cleanupMultipart(processedRequest);

}

}

}

三、入门程序:

创建一个web工程,加入spring的jar包和springmvc的jar包

1、首先在web.xml里面配置springmvc的加载

  1. <servlet>
  2. <servlet-name>springmvc</servlet-name>
  3. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4. <!-- 初始化加载springmvc配置文件 -->
  5. <!-- 方法一:
  6. 命名规范:<servlet-name>-servlet.xml=========>springmvc-servlet.xml
  7. 路径规范:/WEB-INF/springmvc-servlet.xml(必须把配置文件放在WEB-INF路径下)
  8. -->
  9. </servlet>
  10. <servlet-mapping>
  11. <servlet-name>springmvc</servlet-name>
  12. <url-pattern>*.do</url-pattern>
  13. </servlet-mapping>

2、springmvc-servlet.xml的配置:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd ">
  8. <!-- 开启spring注解扫描 -->
  9. <context:component-scan base-package="com.itcast"></context:component-scan>
  10. <!-- 处理器映射器:寻找执行类controller,返回controller对象 -->
  11. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" ></bean>
  12. <!-- 处理器适配器 :执行controller对象方法,返回执行结果-->
  13. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" ></bean>
  14. <!-- 返回物理视图就不用配置视图解析器 -->
  15. <!-- 逻辑视图使用视图解析器 -->
  16. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
  17. <property name="prefix" value="WEB-INF/jsp/" ></property>
  18. <property name="suffix" value=".jsp" ></property>
  19. </bean>
  20. </beans>

注意:如果使用的是物理视图就不用配置视图解析器

如返回的是逻辑视图,需要使用视图解析器

3、测试程序:

  1. @Controller
  2. public class UserController {
  3. /**
  4. * 需求:springmvc入门案例
  5. * 组件:
  6. * 1.web.xml : 控制层 DispatherServlet
  7. * 2,处理器映射器: RequestMappingHandlerMapping
  8. * 3,处理器适配器:RequestMappingHandlerAdapter
  9. * 4,创建controller执行类
  10. * 5,@RequestMapping:请求映射 根据浏览器请求进行匹配映射
  11. */
  12. @RequestMapping("hello")
  13. public ModelAndView showHello(){
  14. //创建模型和视图对象
  15. ModelAndView mv = new ModelAndView();
  16. //设置数据
  17. mv.addObject("hello","张三丰好帅");
  18. //指定返回试图页面,直接设计物理视图
  19. //mv.setViewName("/WEB-INF/jsp/hello.jsp");
  20. mv.setViewName("hello");//逻辑视图,用视图解析器
  21. return mv;
  22. }
  23. }

4、扩展:

①、自定义配置文件的文件名和路径

springmvc的配置文件的默认路径为WEB-INF目录下,文件名格式是:<servlet-name>-servlet.xml

怎么自定义呢?

<servlet>

<servlet-name>springmvc</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 方法二 加载自定义配置文件 -->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

②、返回字符串视图
  1. /**
  2. * 需求:返回string类型的逻辑视图
  3. * springmvc:封装参数方法:所有参数都放置方法中,这些参数将会自动被创建对象
  4. * model:model其实是request域
  5. */
  6. @RequestMapping("hello2")
  7. public String showHello2(Model model){
  8. //放入数值
  9. model.addAttribute("hello", "峨嵋派周芷若");
  10. //返回逻辑视图
  11. return "hello";
  12. }
③、注解驱动使用

用注解驱动代替处理映射器和处理适配器的配置,支持json格式和对象进行相互转换

<mvc:annotation-driven></mvc:annotation-driven>

5、参数的接收

封装参数方法:所有参数都放置方法中,这些参数将会自动被创建对象

①、跳转参数页面
  1. /**
  2. * 需求:跳转参数封装页面
  3. */
  4. @RequestMapping("param")
  5. public String showParam(){
  6. //返回逻辑视图:页面名称
  7. return "param";
  8. }
②、int类型参数的传递
  1. <form action="${pageContext.request.contextPath}/receiveInt.do">
  2. <input type="text" name="id" id="id" >
  3. <input type="submit" value="提交表单" >
  4. </form>
  1. /**
  2. * 需求:接受int类型参数
  3. * springmvc参数封装方法:
  4. * 基于方法进行封装,参数变量都写在方法中,参数将会自动被创建对象,接受页面 参数
  5. */
  6. @RequestMapping("receiveInt")
  7. public String receiveInt(int id){
  8. System.out.println(id);
  9. //封装成功
  10. return "success/success";
  11. }
③、boolean类型参数的传递
  1. <form action="${pageContext.request.contextPath}/receiveBoolean.do">
  2. trueFlag:<input type="radio" name="flag" value="true" >
  3. <br>falseFlag:<input type="radio" name="flag" value="false" >
  4. <br><input type="submit" value="提交表单" >
  5. </form>
  1. /**
  2. * 需求:接受boolean类型参数
  3. */
  4. @RequestMapping("receiveBoolean")
  5. public String receiveBoolean(boolean flag){
  6. System.out.println(flag);
  7. //封装成功
  8. return "success/success";
  9. }
④、接收String类型参数(中文乱码的解决)
  1. <form action="${pageContext.request.contextPath}/receiveStr.do">
  2. 姓名:<input type="text" name="username" id="username" >
  3. <br><input type="submit" value="提交表单" >
  4. </form>

没有解决中文乱码问题的基本代码:

  1. @RequestMapping("receiveStr")
  2. public String receiveStr(String username){
  3. System.out.println(username);
  4. //封装成功
  5. return "success/success";
  6. }

此程序有中文乱码问题,怎么解决?

u   get请求传来的数据

1、第一种方案:

修改tomcat服务器编码(server.xml)

<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

2、第二种方案:

重新对参数进行解码,编码(对于post请求同样适用)

  1. @RequestMapping("receiveStr")
  2. public String receiveStr(String username){
  3. try {
  4. username=new String(username.getBytes("iso8859-1"), "utf-8");
  5. } catch (UnsupportedEncodingException e) {
  6. // TODO Auto-generated catch block
  7. e.printStackTrace();
  8. }
  9. System.out.println(username);
  10. //封装成功
  11. return "success/success";
  12. }

u   post请求传来的数据

由spring提供编码过滤器(只能解决post提交的请求

具体做法:在web.xml里面配置编码过滤器

  1. <!-- 编码过滤器 -->
  2. <filter>
  3. <filter-name>characterEncoding</filter-name>
  4. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  5. <init-param>
  6. <param-name>encoding</param-name>
  7. <param-value>utf-8</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>characterEncoding</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>
⑤、数组类型参数接收
  1. <form action="${pageContext.request.contextPath}/receiveArray.do" method="post" >
  2. <input type="checkbox" name="ids" value="1" >篮球
  3. <br><input type="checkbox" name="ids" value="2" >足球
  4. <br><input type="checkbox" name="ids" value="3" >乒乓球
  5. <br><input type="submit" value="提交表单" >
  6. </form>
    1. /**
  1. * 接收数组参数类型
  2. * 批量删除
  3. */
  4. @RequestMapping("receiveArray")
  5. public String receiveArray(Integer[] ids){
  6. System.out.println(Arrays.toString(ids));
  7. //封装成功
  8. return "success/success";
  9. }
⑥、pojo类型传递(Date类型的格式)
  1. <form action="${pageContext.request.contextPath}/receiveUser.do" method="post" >
  2. 姓名:<input type="text" name="username" id="username">
  3. <br>性别:<input type="text" name="sex" id="sex">
  4. <br>年龄:<input type="text" name="age" id="age">
  5. <br>生日:<input type="text" name="birthday" id="birthday">
  6. <br>地址:<input type="text" name="address" id="address">
  7. <br><input type="submit" value="提交表单" >
  8. </form>
  1. /**
  2. * 需求:接受pojo类型参数
  3. */
  4. @RequestMapping("receiveUser")
  5. public String receiveUser(User user){
  6. System.out.println(user);
  7. //封装成功
  8. return "success/success";
  9. }
u默认的Date格式为1998/02/02
⑦、传递包装类型参数
  1. <form action="${pageContext.request.contextPath}/receiveVo.do" method="post" >
  2. 姓名:<input type="text" name="user.username" id="username">
  3. <br>性别:<input type="text" name="user.sex" id="sex">
  4. <br>年龄:<input type="text" name="user.age" id="age">
  5. <br>生日:<input type="text" name="user.birthday" id="birthday">
  6. <br>地址:<input type="text" name="user.address" id="address">
  7. <br><input type="submit" value="提交表单" >
  8. </form>
  1. /**
  2. * 需求:接受包装类型参数
  3. * 包装类型包装user对象
  4. */
  5. @RequestMapping("receiveVo")
  6. public String receiveVo(QueryVo queryVo){
  7. System.out.println(queryVo.getUser());
  8. //封装成功
  9. return "success/success";
  10. }
⑧、集合参数的接收

要有一个包装类把集合装进去

在QueryVo类型声明一个List<User> uList;属性

  1. <form action="${pageContext.request.contextPath}/receiveList.do" method="post" >
  2. 姓名:<input type="text" name="uList[0].username" id="username">
  3. <br>地址:<input type="text" name="uList[0].address" id="address">
  4. <br>姓名:<input type="text" name="uList[1].username" id="username">
  5. <br>地址:<input type="text" name="uList[1].address" id="address">
  6. <br><input type="submit" value="提交表单" >
  7. </form>
  1. /**
  2. * 需求:接受集合类型参数
  3. * 集合类型包装user对象
  4. */
  5. @RequestMapping("receiveList")
  6. public String receiveList(QueryVo queryVo){
  7. System.out.println(queryVo.getuList());
  8. //封装成功
  9. return "success/success";
  10. }
⑨、自定义参数的封装

时间类型默认传入格式是1321/02/02,如果要修改成其他的格式,那么就需要另外的配置

1、第一种方案:使用注解    @initBinder

  1. /**
  2. * 需求:时间类型参数,如果和当前系统时间类型不匹配,传递不成功
  3. * 解决方案:使用注解
  4. */
  5. @InitBinder
  6. public void dateRegister(WebDataBinder binder){//true表示可以为空
  7. binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
  8. }

这个注解会自动被调用

缺点:每个类都要配置

2、使用代码转换器的方案

①、声明一个Converter的实现类

  1. package com.itcast.utils;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import org.springframework.core.convert.converter.Converter;
  6. public class DateConvert implements Converter<String, Date>{
  7. public Date convert(String source) {
  8. // TODO Auto-generated method stub
  9. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  10. //转换
  11. Date parse=null;
  12. try {
  13. parse = sdf.parse(source);
  14. } catch (ParseException e) {
  15. // TODO Auto-generated catch block
  16. e.printStackTrace();
  17. }
  18. return parse;
  19. }
  20. }

②、把代码配置到springmvc的配置中的注解驱动中

  1. <mvc:annotation-driven conversion-service="conversion" ></mvc:annotation-driven>
  2. <bean id="conversion" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" >
  3. <property name="converters">
  4. <bean class="com.itcast.utils.DateConvert" ></bean>
  5. </property>
  6. </bean>

四、springmvc和mybatis整合

1、web.xml的配置

  1. <!-- 1,编码过滤器 -->
  2. <filter>
  3. <filter-name>characterEncoding</filter-name>
  4. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  5. <init-param>
  6. <param-name>encoding</param-name>
  7. <param-value>utf-8</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>characterEncoding</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>
  14. <!-- 2,加载spring配置文件 -->
  15. <listener>
  16. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  17. </listener>
  18. <context-param>
  19. <param-name>contextConfigLocation</param-name>
  20. <param-value>classpath:applicationContext-*.xml</param-value>
  21. </context-param>
  22. <!-- 3,加载springmvc配置文件 -->
  23. <servlet>
  24. <servlet-name>springmvc</servlet-name>
  25. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  26. <!-- 初始化加载springmvc配置文件 -->
  27. <init-param>
  28. <param-name>contextConfigLocation</param-name>
  29. <param-value>classpath:springmvc.xml</param-value>
  30. </init-param>
  31. <load-on-startup>1</load-on-startup>
  32. </servlet>
  33. <servlet-mapping>
  34. <servlet-name>springmvc</servlet-name>
  35. <url-pattern>*.do</url-pattern>
  36. </servlet-mapping>

2、dao层配置:

配置mybatis和数据层

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10. <!-- 1,数据源 -->
  11. <!-- 整合持久层框架 -->
  12. <context:property-placeholder location="classpath:jdbc.properties"/>
  13. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  14. <property name="driverClassName" value="${jdbc.driver}"></property>
  15. <property name="url" value="${jdbc.url}"></property>
  16. <property name="username" value="${jdbc.username}"></property>
  17. <property name="password" value="${jdbc.password}"></property>
  18. </bean>
  19. <!-- 2,sqlSessionFactory工厂 -->
  20. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  21. <property name="dataSource" ref="dataSource"></property>
  22. <property name="typeAliasesPackage" value="com.itheima.domain"></property>
  23. <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
  24. </bean>
  25. <!-- 3,Mapper接口代理开发扫描 -->
  26. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  27. <property name="basePackage" value="com.itheima.mapper"></property>
  28. </bean>
  29. </beans>

配置映射文件    ItemMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <!-- mapper:映射文件开始标签,标签中封装所有sql语句 namespace: 1,命名空间,唯一标识一个映射文件,名称自定义 2,如果是接口代理开发,namespace有特殊含义,不能随便定义 -->
  6. <mapper namespace="com.itheima.mapper.ItemMapper">
  7. <!-- 需求:查询所有商品,展示商品列表 -->
  8. <select id="findAllItems" resultType="item">
  9. select * from items
  10. </select>
  11. </mapper>

接口:

  1. public interface ItemMapper {
  2. /**
  3. * 需求:查询所有商品,列表展示
  4. *
  5. */
  6. public List<Item> findAllItems();
  7. }

3、service层配置

配置事务:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:aop="http://www.springframework.org/schema/aop"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
  8. xmlns:mvc="http://www.springframework.org/schema/mvc"
  9. xsi:schemaLocation="http://www.springframework.org/schema/beans
  10. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  17. http://code.alibabatech.com/schema/dubbo
  18. http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  19. http://www.springframework.org/schema/context
  20. http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  21. <!-- 一,把service交给spring管理 -->
  22. <context:component-scan base-package="com.itheima.service"></context:component-scan>
  23. <!-- 二,事物管理 -->
  24. <!-- 1,事物管理平台 -->
  25. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  26. <property name="dataSource" ref="dataSource"></property>
  27. </bean>
  28. <!-- 2,事物管理策略,通知 -->
  29. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  30. <tx:attributes>
  31. <tx:method name="save*" propagation="REQUIRED"/>
  32. <tx:method name="delete*" propagation="REQUIRED"/>
  33. <tx:method name="update*" propagation="REQUIRED"/>
  34. <tx:method name="*" propagation="REQUIRED"/>
  35. </tx:attributes>
  36. </tx:advice>
  37. <!-- 3,事物切面 -->
  38. <aop:config>
  39. <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service.*.*(..))"/>
  40. </aop:config>
  41. </beans>

配置ItemService

  1. @Service
  2. public class ItemServiceImpl implements ItemService{
  3. @Autowired
  4. private ItemMapper itemMapper;
  5. @Override
  6. public List<Item> findAllItems() {
  7. List<Item> list = itemMapper.findAllItems();
  8. return list;
  9. }
  10. }

4、controller层配置

配置ItemController

  1. @Controller
  2. public class ItemController {
  3. //注入service服务对象
  4. @Autowired
  5. private ItemService itemService;
  6. /**
  7. * 需求:查询所有商品,列表展示
  8. * 请求:itemsList.do
  9. */
  10. @RequestMapping("itemsList")
  11. public String itemsList(Model model){
  12. //调用service服务方法,查询商品数据
  13. List<Item> itemList = itemService.findAllItems();
  14. //页面回显
  15. model.addAttribute("itemsList", itemList);
  16. return "itemsList";
  17. }
  18. }

配置springmvc.xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  10. <!-- 1,扫描,把controller交给spring管理 -->
  11. <context:component-scan base-package="com.itheima.controller"></context:component-scan>
  12. <!-- 2,注解驱动 -->
  13. <mvc:annotation-driven/>
  14. <!-- 3,视图解析器 -->
  15. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  16. <!-- 前缀 -->
  17. <property name="prefix" value="/WEB-INF/jsp/"></property>
  18. <!-- 后缀 -->
  19. <property name="suffix" value=".jsp"></property>
  20. </bean>
  21. </beans>

注意:@AutoWired和@Resource(name="")都不需要set方法,直接就能注入

null

时间: 2024-08-04 21:50:48

springMVC课程01的相关文章

Scala课程01

Scala课程01 简介 由于本人刚毕业,也是从事软件开发相关的工作.想再学习一下关于大数据.移动互联网.云计算相关的技术.为我的未来打好基础.并且从零开始学习大数据相关的知识,脚踏实地的走好每一步,听行业前辈说毕业生刚工作的三年是非常关键的,所有我每天抽出一点时间学习大数据相关知识, 也算是给我我未来买一份保险吧!也有从事大数据相关的工作的打算,也是未来规划的一部分吧!少年! 关于Scala介绍 Scala首先是一门编程语言,并且非常纯粹的面向对象编程语言,语法也非常简洁,相对java.Sca

SpringMVC 教程01

<!-- \WebContent\WEB-INF\dispatcherServlet-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-inst

Springmvc系列01 Helloworld

0.springmvc请求流程图 1.使用的jia包及要写的配置文件如图 2.web.xml 配置前端控制器 <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchem

【SpringMVC学习01】宏观上把握SpringMVC框架

springmvc是一个基于mvc的web框架,是spring框架的一个模块,所以springmvc和spring无需通过中间整合层进行整合.我们先来看下spring的一个架构模型,看springmvc在spring框架中所处的位置: 从图中可以看出,springmvc是spring的一个web框架,所以上图中描述的是spring web mvc,它和struts2的功能差不多,下面我们来深入到springmvc内部,看它的干了些啥,先看一个图: 这个图描述了springmvc的整个执行的流程,

springMVC入门-01

这一系列是在看完网上SpringMVC(基于spring3.0)入门视频之后的个人总结,仅供参考,其中会添加一些个人的见解. 1.搭建SpringMVC所需jar包: org.springframework.aop-3.1.3.RELEASE.jarorg.springframework.asm-3.1.3.RELEASE.jarorg.springframework.aspects-3.1.3.RELEASE.jarorg.springframework.beans-3.1.3.RELEASE

springMVC课程02

1.在springmvc中,json数据里面的data参数里面必须用双引号,才能传到后台一json对象,然后才能被@RequestBody转成javabean对象,并且要在外面用单引号括起来(传json整个数据的时候)--在springmvc里面用的多------ 如果不加单引号,传递过去的就是一个参数键值对,而不是一个完整的json对象 contentType:'application/json;charset=utf-8', data:'{"name":"黑妹牙膏&quo

springmvc笔记-01

今天刚开始学习springMVC,因为工作要用到,就自己找了些例子学习,但是按照例子配置完成后启动就开始报错:-(, 具体错误:Could not open ServletContext resource [/WEB-INF/classes/spring-servlet.xml] 我的web.xml: <!-- The front controller of this spring web application,         responsible for handling all app

SpringMVC 学习之旅--第一天:@RequestMapping

@RequestMapping:请求映射 SpringMVC第01天: 使用@controller定义controllersSpring mvc将特定url的请求分发到controller类来进行处理在spring 3.0中,通过@controller标注即可将class定义为一个controller类.为使spring能找到定义为controller的bean,需要在spring-context配置文件中增加如下定义:扫描器 1 <context:component-scan base-pac

springMVC1 springmvc的基础知识

springmvc第一天 springmvc的基础知识 springmvc课程安排: 第一天: 基础知识 springmvc框架(重点) mvc在b/s系统中应用方式 springmvc框架原理(DispatcherServlet前端控制器(类似于struts的过滤器).处理器映射器.处理器适配器.视图解析器) springmvc入门程序 需求:商品列表查询 常用的处理器映射器,处理器适配器 注解的处理器映射器,处理器适配器用于注解开发(重点) 3 注解开发基础 常用的注解使用 参数绑定 自定义