SpringMVC

作者: Stern_ | 来源:发表于2019-06-01 11:45 被阅读0次

知识储备

1、j2ee基础

2、spring框架基础

3、JDBC

4、Eclipse+Maven+Tomcat

SpringMVC基本工作流程

前端控制器:DispatcherServlet

DispatcherServlet详解

1、作用分析

        分发,拦截请求,委托请求给处理器;

        将处理器返回的model给view

2、集成web环境的web.xml中的配置

        <context-param>

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

            <param-value>classpath:spring-common.xml</param-value>

        </context-param>

        <listener>

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

        </listener>

注意点:

此时common管理的bean与springmvc管理的bean会在同一个容器中,<context:component-scan>中的地址有重叠则会重复加载bean,需要分离管理地址。

spring-common.xml:

spring-mvc.xml:

Controller处理器详解

        @Controller注解声明了这个类是个controller处理器

        @Scope注解:

        在原有的spring中有的singleton(单例)和prototype(原型)的基础上增加了request级别和session级别

        singleton:单例,永远只有一个对象服务;

        prototype:每一个请求都会创建一个实例对象服务;

        session:一个session创建一个对象服务;

        @requestMapping(value="..."params="...",method=...)

        params:参数限定  (不常用,了解即可)

        在method中可有RequestMethod.GET和RequestMethod.POST也可有{RequestMethod.GET,RequestMethod.POST}复合型

:prototype 原型模式的生命周期由JVM的GC来销毁,不会在容器关闭时调用destroy-method。

视图解析器

        spring-mvc.xml配置

        <!-- 视图解析器 -->               

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

             <!-- 配置从项目根目录到指定目录一端路径 ,建议指定浅一点的目录-->

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

             <!-- 文件的后缀名 -->

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

    </bean>

        通过ModeAndView对象获得和返回参数

        ModelAndView mav = new ModelAndView();

        mav.setViewName("welcome");

        mav.addObject("message","参数传递到页面");

        return mav;

    freemarket视图配置

        <!-- 配置freeMarker的模板路径 -->

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

           <property name="templateLoaderPath" value="/WEB-INF/ftl/"/>

           <property name="defaultEncoding" value="UTF-8"/>

        </bean>

        <!-- freeMarker视图解析器 -->

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

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

           <property name="contentType" value="text/html;charset=UTF-8"/>

        </bean>

ajax返回对象json数据

    需导包jackson-core和jackson-databind

    @RequestMapping(value="empJson")

    public @ResponseBody Emp ajax() {

        Emp emp = new Emp();

        emp.setName("jack");

        emp.setAge(12);

        return emp;

    }

相关文章

网友评论

      本文标题:SpringMVC

      本文链接:https://www.haomeiwen.com/subject/zmbotctx.html