• spring mvc 起步


    1:mvc的核心思想是业务数据抽取同业务数据呈现相分离

    2:HandlerAdapter用来处理handleinterceptor和 ControlInter 生成的handleExecuteChain

       请求 diapatcherServlet 接受请求,--> 交给handleMapper处理,返回一个 handleExecuteChain(包含拦截器和相应的handle) -->先执行注册的拦截器,在交给HandleAdapt 执行相应的handl,返回一个modleAndView.

    3:mode ModelAndView map

    4:为了防止用Maven管理Spring项目时,不同的项目依赖了不同版本的Spring,可以使用Maven BOM来解决者一问题。

    在依赖管理时,引入spring-framework-bom,如:

    复制代码
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>4.3.1.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    复制代码

    即可统一版本,而且,在引入BOM之后,在引入其他Spring依赖时,都无需指定版本,如:

    复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>
    <dependencies>
    复制代码
    5:配置文件
    WEB-INF
          web.xml
           spring
                 applicationContext.xml
                 mvc-dispatcher-servlet.xml
     
    内容如下:
    web.xml
    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Spring MVC Study</display-name>
    <!-- Spring应用上下文, 理解层次化的ApplicationContext -->
    <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/configs/spring/applicationContext*.xml</param-value>
    </context-param>

    <listener>
    <listener-class>
    org.springframework.web.context.ContextLoaderListener
    </listener-class>
    </listener>

    <!-- DispatcherServlet, Spring MVC的核心 --> 可有有多个DispatcherServlet

    <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class> org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- DispatcherServlet对应的上下文配置, 默认为/WEB-INF/$servlet-name$-servlet.xml
    -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/configs/spring/mvc-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <!-- mvc-dispatcher拦截所有的请求-->
    <url-pattern>/</url-pattern>
    </servlet-mapping>
    </web-app>
    复制代码

    applicationContext.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"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />

    <context:component-scan base-package="com.imooc.mvcdemo">
    <context:exclude-filter type="annotation"
    expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    </beans>
    复制代码

    mvc-dispatcher-servlet.xml如下:

    复制代码
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 本配置文件是工名为mvc-dispatcher的DispatcherServlet使用, 提供其相关的Spring MVC配置 -->

    <!-- 启用Spring基于annotation的DI, 使用户可以在Spring MVC中使用Spring的强大功能。 激活 @Required
    @Autowired,JSR 250's @PostConstruct, @PreDestroy and @Resource 等标注 -->
    <context:annotation-config />

    <!-- DispatcherServlet上下文, 只管理@Controller类型的bean, 忽略其他型的bean, 如@Service -->
    <context:component-scan base-package="com.imooc.mvcdemo">
    <context:include-filter type="annotation"
    expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- HandlerMapping, 无需配置, Spring MVC可以默认启动。 DefaultAnnotationHandlerMapping
    annotation-driven HandlerMapping -->

    <!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 -->
    <mvc:annotation-driven />

    <!-- 静态资源处理, css, js, imgs -->
    <mvc:resources mapping="/resources/**" location="/resources/" />


    <!-- 配置ViewResolver。 可以用多个ViewResolver。 使用order属性排序。 InternalResourceViewResolver放在最后。 -->
    <bean
    class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="order" value="1" />
    <property name="mediaTypes">
    <map>
    <entry key="json" value="application/json" />
    <entry key="xml" value="application/xml" />
    <entry key="htm" value="text/html" />
    </map>
    </property>

    <property name="defaultViews">
    <list>
    <!-- JSON View -->
    <bean
    class="org.springframework.web.servlet.view.json.MappingJackson2JsonView">
    </bean>
    </list>
    </property>
    <property name="ignoreAcceptHeader" value="true" />
    </bean>

    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass"
    value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsps/" />
    <property name="suffix" value=".jsp" />
    </bean>


    <!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="209715200" />
    <property name="defaultEncoding" value="UTF-8" />
    <property name="resolveLazily" value="true" />
    </bean>

    </beans>
    复制代码
    6:参数接收

    //本方法将处理 /courses/view?courseId=123 形式的URL
    @RequestMapping(value="/view", method=RequestMethod.GET)
    public String viewCourse(@RequestParam("courseId") Integer courseId,
    Model model) {


    log.debug("In viewCourse, courseId = {}", courseId);
    Course course = courseService.getCoursebyId(courseId);
    model.addAttribute(course);
    return "course_overview";
    }

    //本方法将处理 /courses/view2/123 形式的URL
    @RequestMapping("/view2/{courseId}")
    public String viewCourse2(@PathVariable("courseId") Integer courseId,
    Map<String, Object> model) {

    log.debug("In viewCourse2, courseId = {}", courseId);
    Course course = courseService.getCoursebyId(courseId);
    model.put("course",course);
    return "course_overview";
    }

    //本方法将处理 /courses/view3?courseId=123 形式的URL
    @RequestMapping("/view3")
    public String viewCourse3(HttpServletRequest request) {

    Integer courseId = Integer.valueOf(request.getParameter("courseId"));
    Course course = courseService.getCoursebyId(courseId);
    request.setAttribute("course",course);

    return "course_overview";
    }

    @RequestMapping(value="/admin", method = RequestMethod.GET, params = "add")
    public String createCourse(){
    return "course_admin/edit";
    }

    @RequestMapping(value="/save", method = RequestMethod.POST)
    public String doSave(@ModelAttribute Course course){

    log.debug("Info of Course:");
    log.debug(ReflectionToStringBuilder.toString(course));

    //在此进行业务操作,比如数据库持久化
    course.setCourseId(123);
    return "redirect:view2/"+course.getCourseId();
    }

    此处多了一个注解@ModelAttribute("user"),它的作用是将该绑定的命令对象以“user”为名称添加到模型对象中供视图页面展示使用。我们此时可以在视图页面使用${user.username}来获取绑定的命令对象的属性。

    7:用到HttpServletRequest  需要引入

    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    </dependency>

    8: 对json的支持


    @RequestMapping(value="/{courseId}",method=RequestMethod.GET)
    public @ResponseBody Course getCourseInJson(@PathVariable Integer courseId){
    return courseService.getCoursebyId(courseId);
    }


    @RequestMapping(value="/jsontype/{courseId}",method=RequestMethod.GET)
    public ResponseEntity<Course> getCourseInJson2(@PathVariable Integer courseId){
    Course course = courseService.getCoursebyId(courseId);
    return new ResponseEntity<Course>(course, HttpStatus.OK);
    }

    需要引入

    <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
    </dependency>

    以及配置ViewResolver
     
  • 相关阅读:
    Git哲学与使用
    save
    http://www.onvif.org/onvif/ver20/util/operationIndex.html
    图标
    C#高性能大容量SOCKET并发(一):IOCP完成端口例子介绍(转)
    一种基于PTP 协议的局域网高精度时钟同步方法(转)
    WPF中的数据模板(DataTemplate)(转)
    WPF中的ControlTemplate(控件模板)(转)
    也来说说C#异步委托(转)
    C#委托的介绍(delegate、Action、Func、predicate)(转)
  • 原文地址:https://www.cnblogs.com/zyy1688/p/10273157.html
Copyright © 2020-2023  润新知