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>
          <!-- 設(shè)置攔截路徑 -->
          <mvc:mapping path="/**" />
          <!-- 攔截器完全限定名 -->
          <bean class="com.zzsong.interceptor.MyInterceptor">
              <!-- 攔截器內(nèi)存儲不攔截的路徑 -->
              <property name="allowpath">
                  <list>
                      <value>hello.do</value>
                      <value>login.do</value>
                  </list>
              </property>
          </bean>
      </mvc:interceptor>
    </mvc:interceptors>
    
  • 攔截器的使用

    實現(xiàn)接口的方式

    public class MyInterceptor implements HandlerInterceptor {
      public List<String> allowpath;
    
      public List<String> getAllowpath() {
          return allowpath;
      }
    
      public void setAllowpath(List<String> allowpath) {
          this.allowpath = allowpath;
      }
      //整個請求處理完畢回調(diào)方法项郊,即在視圖渲染完畢時回調(diào)沪停,如性能監(jiān)控中我們可以在此記錄結(jié)束時間并輸出消耗時間页慷,還可以進行一些資源清理午绳,類似于try-catch-finally中的finally棚瘟,但僅調(diào)用處理器執(zhí)行鏈中preHandle返回true的攔截器的afterCompletion氯葬。
      @Override
      public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
              throws Exception {
      }
    
      // 后處理回調(diào)方法虚茶,實現(xiàn)處理器的后處理(但在渲染視圖之前),此時我們可以通過modelAndView(模型和視圖對象)對模型數(shù)據(jù)進行處理或?qū)σ晥D進行處理丧鸯,modelAndView也可能為null蛤铜。
      @Override
      public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
              throws Exception {
      }
    
      // 預(yù)處理回調(diào)方法,實現(xiàn)處理器的預(yù)處理(如登錄檢查)骡送,第三個參數(shù)為響應(yīng)的處理器
      //返回值:true表示繼續(xù)流程(如調(diào)用下一個攔截器或處理器);false表示流程中斷(如登錄檢查失斝跫恰)摔踱,不會繼續(xù)調(diào)用其他的攔截器或處理器,此時我們需要通過response來產(chǎn)生響應(yīng)怨愤;
      @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;
      }
      
          // 預(yù)處理回調(diào)方法派敷,實現(xiàn)處理器的預(yù)處理(如登錄檢查),第三個參數(shù)為響應(yīng)的處理器
      //返回值:true表示繼續(xù)流程(如調(diào)用下一個攔截器或處理器)撰洗;false表示流程中斷(如登錄檢查失斃河洹),不會繼續(xù)調(diào)用其他的攔截器或處理器差导,此時我們需要通過response來產(chǎn)生響應(yīng)试躏;
      @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";
    }
}

轉(zhuǎn)發(fā)到其他servlet

/**
 * 轉(zhuǎn)發(fā)到其他servlet
 */
@RequestMapping("/login.do")
public String login() {
    return "forward:/hello.do";
}

重定向到其他servlet

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

帶參轉(zhuǎn)發(fā)

  • 方式一

    @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);
      //將需要跳轉(zhuǎn)到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();
    }
    
  • 返回集合或?qū)ο?/strong>

    @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

    需要使用相關(guān)的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);
    }
    
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市设褐,隨后出現(xiàn)的幾起案子颠蕴,更是在濱河造成了極大的恐慌,老刑警劉巖助析,帶你破解...
    沈念sama閱讀 218,122評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件犀被,死亡現(xiàn)場離奇詭異,居然都是意外死亡外冀,警方通過查閱死者的電腦和手機寡键,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來雪隧,“玉大人西轩,你說我怎么就攤上這事∧匝兀” “怎么了遭商?”我有些...
    開封第一講書人閱讀 164,491評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長捅伤。 經(jīng)常有香客問我劫流,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,636評論 1 293
  • 正文 為了忘掉前任祠汇,我火速辦了婚禮仍秤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘可很。我一直安慰自己诗力,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,676評論 6 392
  • 文/花漫 我一把揭開白布我抠。 她就那樣靜靜地躺著苇本,像睡著了一般。 火紅的嫁衣襯著肌膚如雪菜拓。 梳的紋絲不亂的頭發(fā)上瓣窄,一...
    開封第一講書人閱讀 51,541評論 1 305
  • 那天,我揣著相機與錄音纳鼎,去河邊找鬼俺夕。 笑死,一個胖子當(dāng)著我的面吹牛贱鄙,可吹牛的內(nèi)容都是我干的劝贸。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼逗宁,長吁一口氣:“原來是場噩夢啊……” “哼映九!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起瞎颗,我...
    開封第一講書人閱讀 39,211評論 0 276
  • 序言:老撾萬榮一對情侶失蹤氯迂,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后言缤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嚼蚀,經(jīng)...
    沈念sama閱讀 45,655評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,846評論 3 336
  • 正文 我和宋清朗相戀三年管挟,在試婚紗的時候發(fā)現(xiàn)自己被綠了轿曙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,965評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡僻孝,死狀恐怖导帝,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情穿铆,我是刑警寧澤您单,帶...
    沈念sama閱讀 35,684評論 5 347
  • 正文 年R本政府宣布,位于F島的核電站荞雏,受9級特大地震影響虐秦,放射性物質(zhì)發(fā)生泄漏平酿。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,295評論 3 329
  • 文/蒙蒙 一悦陋、第九天 我趴在偏房一處隱蔽的房頂上張望蜈彼。 院中可真熱鬧,春花似錦俺驶、人聲如沸幸逆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,894評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽还绘。三九已至,卻和暖如春栖袋,著一層夾襖步出監(jiān)牢的瞬間拍顷,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,012評論 1 269
  • 我被黑心中介騙來泰國打工栋荸, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留菇怀,地道東北人凭舶。 一個月前我還...
    沈念sama閱讀 48,126評論 3 370
  • 正文 我出身青樓晌块,卻偏偏與公主長得像,于是被迫代替她去往敵國和親帅霜。 傳聞我的和親對象是個殘疾皇子匆背,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,914評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)身冀,斷路器钝尸,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • 1、Spring MVC請求流程 (1)初始化:(對DispatcherServlet和ContextLoderL...
    拾壹北閱讀 1,948評論 0 12
  • Spring mvc 框架 DispatcherServlet前端控制器 ---- 整個流程控制的中心搂根,由它調(diào)用其...
    蕊er閱讀 705評論 0 0
  • Spring的模型-視圖-控制器(MVC)框架是圍繞一個DispatcherServlet來設(shè)計的珍促,這個Servl...
    4ea0af17fd67閱讀 1,052評論 0 5
  • 茶茶小姐喜歡睫毛先生很久了猪叙,倆個人關(guān)系不錯。用茶茶小姐的話講仁卷,睫毛先生每天都會陪她聊天穴翩,與她分享日常見到的趣事,看...
    一個檸檬茶姑娘閱讀 359評論 0 2