Spring MVC

Spring MVC

[TOC]

配置文件

配置核心控制器

<servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <!-- SpringMVC的配置文件,在src目录下 -->
        <param-value>classpath:springMVC-servlet.xml</param-value>
    </init-param>
    <!-- 启动顺序:表示启动容器时初始化该Servlet -->
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!-- 拦截所有.do请求 -->
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

解决post中文乱码

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Spring MVC基本配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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/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">

</beans>

servlet 扫描器

<!-- servlet扫描器 , 扫描指定包下的所有类 -->
<context:component-scan base-package="com.zzsong.controller"></context:component-scan>

视图解析器

<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/index/" />
    <property name="suffix" value=".jsp" />
</bean>

文件上传解析器

<!-- 文件上传的 解析器的配置 -->
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 最大缓存大小 -->
    <property name="maxInMemorySize">
        <value>40960</value>
    </property>
    <!-- 上传最大限制 -->
    <property name="maxUploadSize">
        <value>10485760000</value>
    </property>
    <!-- 上传文件编码 -->
    <property name="defaultEncoding">
        <value>UTF-8</value>
    </property>
</bean>

JSON解析器

<!-- JSON解析器 -->
<bean id="stringConverter"
      class="org.springframework.http.converter.StringHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>text/plain;charset=UTF-8</value>
        </list>
    </property>
</bean>
<bean id="jsonConverter"
      class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="stringConverter" />
            <ref bean="jsonConverter" />
        </list>
    </property>
</bean>

拦截器

  • 拦截器的配置

    <!-- 配置拦截器 -->
    <mvc:interceptors>
      <mvc:interceptor>
          <!-- 设置拦截路径 -->
          <mvc:mapping path="/**" />
          <!-- 拦截器完全限定名 -->
          <bean class="com.zzsong.interceptor.MyInterceptor">
              <!-- 拦截器内存储不拦截的路径 -->
              <property name="allowpath">
                  <list>
                      <value>hello.do</value>
                      <value>login.do</value>
                  </list>
              </property>
          </bean>
      </mvc:interceptor>
    </mvc:interceptors>
    
  • 拦截器的使用

    实现接口的方式

    public class MyInterceptor implements HandlerInterceptor {
      public List<String> allowpath;
    
      public List<String> getAllowpath() {
          return allowpath;
      }
    
      public void setAllowpath(List<String> allowpath) {
          this.allowpath = allowpath;
      }
      //整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion。
      @Override
      public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
              throws Exception {
      }
    
      // 后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。
      @Override
      public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
              throws Exception {
      }
    
      // 预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器
      //返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
      @Override
      public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
          String servletPath = arg0.getServletPath();
          for (String string : allowpath) {
              if (servletPath.contains(string)) {
                  return true;
              }
          }
              arg1.sendRedirect("login.do");
          return true;
      }
    
    }
    

    继承类的方式

    public class MyInterceptor extends HandlerInterceptorAdapter {
      public List<String> allowpath;
    
      public List<String> getAllowpath() {
          return allowpath;
      }
    
      public void setAllowpath(List<String> allowpath) {
          this.allowpath = allowpath;
      }
      
          // 预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器
      //返回值:true表示继续流程(如调用下一个拦截器或处理器);false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;
      @Override
      public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
          String servletPath = request.getServletPath();
          for (String string : allowpath) {
              if (servletPath.contains(string)) {
                  return true;
              } 
          }
              response.sendRedirect("login.do");
          return true;
      }
    
    }
    

使用方法

基本使用方式

@Controller
public class MyController {
    @RequestMapping("/login.do")
    public String login() {
        return "forward:/hello.do";
    }
}

窄化请求映射

package cn.javass.chapter6.web.controller;
@Controller
@RequestMapping(value="/user")    //①处理器的通用映射前缀
public class HelloWorldController2 {
    @RequestMapping("/login.do")  //②相对于①处的映射进行窄化
    public String login() {
        return "forward:/hello.do";
    }
}

转发到其他servlet

/**
 * 转发到其他servlet
 */
@RequestMapping("/login.do")
public String login() {
    return "forward:/hello.do";
}

重定向到其他servlet

/**
 * 重定向到其他servlet
 */
@RequestMapping("/login.do")
public String login() {
    return "redirect:/hello.do";
}

带参转发

  • 方式一

    @RequestMapping("/hello.do")
    public ModelAndView index() {
    ModelAndView mv = new ModelAndView();
    StuInfo s = new StuInfo();
    s.setName("sdafas");
    s.setPsw("21412");
      //等同于request.setAttribute
    mv.addObject("msg", s);
      //将需要跳转到JSP名放入
    mv.setViewName("hello");
    return mv;
    }
    
  • 方式二

    @RequestMapping("/hello.do")
    public String index(ModelMap mm) {
    StuInfo s = new StuInfo();
    s.setName("sdafas");
    s.setPsw("21412");
    mm.addAttribute("msg", s);
    return "hello";
    }
    

文件上传

@RequestMapping("/upload.do")
public String upload(@RequestParam("file") CommonsMultipartFile cf[], HttpServletRequest         
                     request, String name) {
    String path = request.getServletContext().getRealPath("/");
    for (int i = 0; i < cf.length; i++) {
        String fileName = cf[i].getOriginalFilename();
        try {
            cf[i].transferTo(new File(path, fileName));
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
    }
    return "forward:/hello.do";
}

AJAX

  • 直接返回字符串

    @RequestMapping("/account.do")
    @ResponseBody
    public void account(String account, HttpServletResponse response) throws IOException {
    PrintWriter writer = response.getWriter();
    if ("123".equals(account)) {
    writer.print("ok");
    } else {
    writer.print("err");
    }
    writer.close();
    }
    
  • 返回集合或对象

    @RequestMapping("/getstu.do")
    @ResponseBody
    public List<StuInfo> getstu() throws IOException {
    List<StuInfo> stus = new ArrayList<>();
    StuInfo s1 = new StuInfo("小红", "123");
    StuInfo s3 = new StuInfo("小明", "456");
    stus.add(s1);
    stus.add(s3);
    return stus;
    }
    
  • 返回JSON

    需要使用相关的JSON处理jar包

    @RequestMapping("/getstu.do")
    @ResponseBody
    public String getstu() throws IOException {
      List<StuInfo> stus = new ArrayList<>();
      StuInfo s1 = new StuInfo("小红", "123");
      StuInfo s3 = new StuInfo("小明", "456");
      stus.add(s1);
      stus.add(s3);
      return JSON.toJSONString(stus);
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,264评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,549评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,389评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,616评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,461评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,351评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,776评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,414评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,722评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,760评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,537评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,381评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,787评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,030评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,304评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,734评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,943评论 2 336

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,517评论 18 139
  • 1、Spring MVC请求流程 (1)初始化:(对DispatcherServlet和ContextLoderL...
    拾壹北阅读 1,943评论 0 12
  • Spring mvc 框架 DispatcherServlet前端控制器 ---- 整个流程控制的中心,由它调用其...
    蕊er阅读 685评论 0 0
  • Spring的模型-视图-控制器(MVC)框架是围绕一个DispatcherServlet来设计的,这个Servl...
    4ea0af17fd67阅读 1,034评论 0 5
  • 茶茶小姐喜欢睫毛先生很久了,俩个人关系不错。用茶茶小姐的话讲,睫毛先生每天都会陪她聊天,与她分享日常见到的趣事,看...
    一个柠檬茶姑娘阅读 358评论 0 2