SpringMVC04:跳轉(zhuǎn)及數(shù)據(jù)處理

6、springMVC:結(jié)果跳轉(zhuǎn)方式

6.1生均、ModelAndView

設(shè)置ModelAndView對象 , 根據(jù)view的名稱 , 和視圖解析器跳到指定的頁面 .

頁面 : {視圖解析器前綴} + viewName +{視圖解析器后綴}

<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
     id="internalResourceViewResolver">
   <!-- 前綴 -->
   <property name="prefix" value="/WEB-INF/jsp/" />
   <!-- 后綴 -->
   <property name="suffix" value=".jsp" />
</bean>

對應(yīng)的controller類

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
       //返回一個模型視圖對象
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

ServletAPI

通過設(shè)置ServletAPI , 不需要視圖解析器 .

1、通過HttpServletResponse進行輸出

2、通過HttpServletResponse實現(xiàn)重定向

3、通過HttpServletResponse實現(xiàn)轉(zhuǎn)發(fā)

@Controller
public class ResultGo {

   @RequestMapping("/result/t1")
   public void test1(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
       rsp.getWriter().println("Hello,Spring BY servlet API");
  }

   @RequestMapping("/result/t2")
   public void test2(HttpServletRequest req, HttpServletResponse rsp) throwsIOException {
       rsp.sendRedirect("/index.jsp");
  }

   @RequestMapping("/result/t3")
   public void test3(HttpServletRequest req, HttpServletResponse rsp) throwsException {
       //轉(zhuǎn)發(fā)
       req.setAttribute("msg","/result/t3");
       req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
  }

}

SpringMVC(重點)

通過SpringMVC來實現(xiàn)轉(zhuǎn)發(fā)和重定向 - 無需視圖解析器秧荆;

測試前,需要將視圖解析器注釋掉

@Controller
public class ResultSpringMVC {
   @RequestMapping("/rsm/t1")
   public String test1(){
       //轉(zhuǎn)發(fā)
       return "/index.jsp";
  }

   @RequestMapping("/rsm/t2")
   public String test2(){
       //轉(zhuǎn)發(fā)二
       return "forward:/index.jsp";
  }

   @RequestMapping("/rsm/t3")
   public String test3(){
       //重定向
       return "redirect:/index.jsp";
  }
}

通過SpringMVC來實現(xiàn)轉(zhuǎn)發(fā)和重定向 - 有視圖解析器埃仪;

重定向 , 不需要視圖解析器 , 本質(zhì)就是重新請求一個新地方嘛 , 所以注意路徑問題.

可以重定向到另外一個請求實現(xiàn) .

@Controller
public class ResultSpringMVC2 {
   @RequestMapping("/rsm2/t1")
   public String test1(){
       //轉(zhuǎn)發(fā)
       return "test";
  }

   @RequestMapping("/rsm2/t2")
   public String test2(){
       //重定向
       return "redirect:/index.jsp";
       //return "redirect:hello.do"; //hello.do為另一個請求/
  }

}

7乙濒、數(shù)據(jù)處理

處理提交數(shù)據(jù)

1、提交的域名稱和處理方法的參數(shù)名一致

提交數(shù)據(jù) : http://localhost:8080/springmvc_04_controller_war_exploded/hello?name=liusen

處理方法 :

@RequestMapping("/hello")
public String hello(String name){
   System.out.println(name);
   return "hello";
}

后臺輸出 : liusen

2卵蛉、提交的域名稱和處理方法的參數(shù)名不一致

提交數(shù)據(jù) : http://localhost:8080/springmvc_04_controller_war_exploded/hello?name=liusen

處理方法 :

//@RequestParam("username") : username提交的域的名稱 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
   System.out.println(name);
   return "hello";
}

后臺輸出 : liusen

3颁股、提交的是一個對象

要求提交的表單域和對象的屬性名一致 , 參數(shù)使用對象即可

1、實體類

public class User {
   private int id;
   private String name;
   private int age;
   //構(gòu)造
   //get/set
   //tostring()
}

2傻丝、提交數(shù)據(jù) : http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15

3甘有、處理方法 :

@RequestMapping("/user")
public String user(User user){
   System.out.println(user);
   return "hello";
}

后臺輸出 : User { id=1, name='kuangshen', age=15 }

說明:如果使用對象的話,前端傳遞的參數(shù)名和對象名必須一致葡缰,否則就是null亏掀。

數(shù)據(jù)顯示到前端

第一種 : 通過ModelAndView

我們前面一直都是如此 . 就不過多解釋

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception {
       //返回一個模型視圖對象
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

第二種 : 通過ModelMap

ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
   //封裝要顯示到視圖中的數(shù)據(jù)
   //相當于req.setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}

第三種 : 通過Model

Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
   //封裝要顯示到視圖中的數(shù)據(jù)
   //相當于req.setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}

對比

就對于新手而言簡單來說使用區(qū)別就是:

Model 只有寥寥幾個方法只適合用于儲存數(shù)據(jù),簡化了新手對于Model對象的操作和理解泛释;

ModelMap 繼承了 LinkedMap 滤愕,除了實現(xiàn)了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性怜校;

ModelAndView 可以在儲存數(shù)據(jù)的同時间影,可以進行設(shè)置返回的邏輯視圖,進行控制展示層的跳轉(zhuǎn)茄茁。

當然更多的以后開發(fā)考慮的更多的是性能和優(yōu)化魂贬,就不能單單僅限于此的了解。

請使用80%的時間打好扎實的基礎(chǔ)裙顽,剩下18%的時間研究框架付燥,2%的時間去學點英文,框架的官方文檔永遠是最好的教程锦庸。

8机蔗、亂碼問題

測試步驟:

1蒲祈、我們可以在首頁編寫一個提交的表單

<form action="/e/t" method="post">
 <input type="text" name="name">
 <input type="submit">
</form>

2甘萧、后臺編寫對應(yīng)的處理類

@Controller
public class Encoding {
   @RequestMapping("/e/t")
   public String test(Model model,String name){
       model.addAttribute("msg",name); //獲取表單提交的值
       return "test"; //跳轉(zhuǎn)到test頁面顯示輸入的值
  }
}

3萝嘁、輸入中文測試,發(fā)現(xiàn)亂碼

不得不說扬卷,亂碼問題是在我們開發(fā)中十分常見的問題牙言,也是讓我們程序猿比較頭大的問題!

以前亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.xml中配置 .

修改了xml文件需要重啟服務(wù)器怪得!

<filter>
   <filter-name>encoding</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>encoding</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

但是我們發(fā)現(xiàn) , 有些極端情況下.這個過濾器對get的支持不好 .

處理方法 :

1咱枉、修改tomcat配置文件 :設(shè)置編碼!

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

2徒恋、自定義過濾器

package com.kuang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
* 解決get和post請求 全部亂碼的過濾器
*/
public class GenericEncodingFilter implements Filter {

   @Override
   public void destroy() {
  }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChainchain) throws IOException, ServletException {
       //處理response的字符編碼
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");

       // 轉(zhuǎn)型為與協(xié)議相關(guān)對象
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // 對request包裝增強
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
  }

}

//自定義request對象蚕断,HttpServletRequest的包裝類
class MyRequest extends HttpServletRequestWrapper {

   private HttpServletRequest request;
   //是否編碼的標記
   private boolean hasEncode;
   //定義一個可以傳入HttpServletRequest對象的構(gòu)造函數(shù),以便對其進行裝飾
   public MyRequest(HttpServletRequest request) {
       super(request);// super必須寫
       this.request = request;
  }

   // 對需要增強方法 進行覆蓋
   @Override
   public Map getParameterMap() {
       // 先獲得請求方式
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
           // post請求
           try {
               // 處理post亂碼
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
           // get請求
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) { // 確保get手動編碼邏輯只運行一次
               for (String parameterName : parameterMap.keySet()) {
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
                       for (int i = 0; i < values.length; i++) {
                           try {
                               // 處理get亂碼
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }

   //取一個值
   @Override
   public String getParameter(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // 取回參數(shù)的第一個值
  }

   //取所有值
   @Override
   public String[] getParameterValues(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

這個也是我在網(wǎng)上找的一些大神寫的入挣,一般情況下亿乳,SpringMVC默認的亂碼處理就已經(jīng)能夠很好的解決了!

然后在web.xml中配置這個過濾器即可径筏!

亂碼問題葛假,需要平時多注意,在盡可能能設(shè)置編碼的地方滋恬,都設(shè)置為統(tǒng)一編碼 UTF-8聊训!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市恢氯,隨后出現(xiàn)的幾起案子带斑,更是在濱河造成了極大的恐慌,老刑警劉巖酿雪,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件遏暴,死亡現(xiàn)場離奇詭異,居然都是意外死亡指黎,警方通過查閱死者的電腦和手機朋凉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來醋安,“玉大人杂彭,你說我怎么就攤上這事∠啪荆” “怎么了亲怠?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長柠辞。 經(jīng)常有香客問我团秽,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任习勤,我火速辦了婚禮踪栋,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘图毕。我一直安慰自己夷都,他們只是感情好,可當我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布予颤。 她就那樣靜靜地躺著囤官,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蛤虐。 梳的紋絲不亂的頭發(fā)上党饮,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天,我揣著相機與錄音驳庭,去河邊找鬼劫谅。 笑死,一個胖子當著我的面吹牛嚷掠,可吹牛的內(nèi)容都是我干的捏检。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼不皆,長吁一口氣:“原來是場噩夢啊……” “哼贯城!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起霹娄,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤能犯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后犬耻,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體踩晶,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年枕磁,在試婚紗的時候發(fā)現(xiàn)自己被綠了渡蜻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡计济,死狀恐怖茸苇,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情沦寂,我是刑警寧澤学密,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站传藏,受9級特大地震影響腻暮,放射性物質(zhì)發(fā)生泄漏彤守。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一哭靖、第九天 我趴在偏房一處隱蔽的房頂上張望遗增。 院中可真熱鬧,春花似錦款青、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至蔗坯,卻和暖如春康震,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背宾濒。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工腿短, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人绘梦。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓橘忱,卻偏偏與公主長得像,于是被迫代替她去往敵國和親卸奉。 傳聞我的和親對象是個殘疾皇子钝诚,可洞房花燭夜當晚...
    茶點故事閱讀 45,044評論 2 355

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