4 資料處理及跳轉
結果跳轉方式
ModelAndView
設定 ModelAndView 物件,根據 View 的名稱和視圖決議器跳轉到指定的頁面
頁面 : {視圖決議器前綴} + viewName +{視圖決議器后綴}
<!--視圖決議器-->
<bean id="InternalResourceViewResolver">
<!--前綴-->
<property name="prefix" value="https://www.cnblogs.com/WEB-INF/jsp/"/>
<!--后綴-->
<property name="suffix" value="https://www.cnblogs.com/zzbstudy/p/.jsp"/>
</bean>
對應的Controller類
package com.zzb.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// 創建模型視圖
ModelAndView modelAndView = new ModelAndView();
// 呼叫業務層
String msg = "ControllerTest1";
modelAndView.addObject("msg", msg);
// 設定跳轉視圖
modelAndView.setViewName("test");
return modelAndView;
}
}
ServletAPI
通過設定ServletAPI,不需要視圖決議器
1、通過HttpServletResponse進行輸出
2、通過HttpServletResponse實作重定向
3、通過HttpServletRequest實作轉發
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/t3")
public class ControllerTest3 {
@RequestMapping("/t1")
public void test1(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/t2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 重定向
resp.sendRedirect(req.getContextPath() + "/index.jsp");
}
@RequestMapping("/t3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 轉發
req.setAttribute("msg", "/t3/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req, resp);
}
}
Spring MVC
通過 Spring MVC 來實作轉發和重定向——不需要視圖決議器,
注意:測驗前先將視圖決議器注釋掉,
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/t4")
public class ControllerTest4 {
@RequestMapping("/t1")
public String test1(){
// 轉發
return "/index.jsp";
}
@RequestMapping("/t2")
public String test2(){
// 顯示轉發
return "forward:/index.jsp";
}
@RequestMapping("/t3")
public String test3(){
// 重定向
return "redirect:/index.jsp";
}
}
通過 Spring MVC 來實作轉發和重定向——使用視圖決議器,
注意:開啟視圖決議器,
package com.zzb.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/t5")
public class ControllerTest5 {
@RequestMapping("/t1")
public String test1(){
// 轉發
return "test";
}
@RequestMapping("/t2")
public String test2(){
// 重定向
return "redirect:/index.jsp";
}
}
資料處理
處理提交資料
1、提交的域名資料名稱和處理方法的引數名一致
package com.zzb.controller;
import com.zzb.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/data")
public class DataController {
// 域名引數與控制器引數名一致的情況
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端引數
System.out.println(name);
// 2 將資料回傳給前端
model.addAttribute("msg", name);
return "test";
}
}
測驗結果:

2、提交的域名資料名稱和處理方法的引數名不一致
// 域名引數與控制器引數名不一致的情況
@RequestMapping("/t2")
public String test2(@RequestParam("username") String name, Model model){
// 1 接受前端引數
System.out.println(name);
// 2 將引數傳遞給前端展示
model.addAttribute("msg", name);
return "test";
}
測驗結果:

3、引數是一個物件
package com.zzb.pojo;
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
// 前端提交的引數是一個物件
@RequestMapping("/t3")
public String test3(User user, Model model){
// 1 接收前端傳遞的引數
System.out.println(user.toString());
// 2 將引數傳遞給前端頁面展示
model.addAttribute("msg", user.toString());
return "test";
}
測驗結果:

注意:如果傳遞引數是物件的話,前端傳遞的引數名和物件的屬性名必須一致,否則為null,
前端展示資料
1、ModelAndView
package com.zzb.controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// 創建模型視圖
ModelAndView modelAndView = new ModelAndView();
// 呼叫業務層
String msg = "ControllerTest1";
modelAndView.addObject("msg", msg);
// 設定跳轉視圖
modelAndView.setViewName("test");
return modelAndView;
}
}
2、ModelMap
@RequestMapping("/t1")
public String test1(String name, ModelMap modelMap){
// 1 接收前端引數
System.out.println(name);
// 2 將資料回傳給前端
modelMap.addAttribute("msg", name);
return "test";
}
3、Model
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端引數
System.out.println(name);
// 2 將資料回傳給前端
model.addAttribute("msg", name);
return "test";
}
3種方法對比:
-
Model 只有寥寥幾個方法只適合用于儲存資料,簡化了新手對于Model物件的操作和理解;
-
ModelMap 繼承了 LinkedMap ,除了實作了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性;
-
ModelAndView 可以在儲存資料的同時,可以進行設定回傳的邏輯視圖,進行控制展示層的跳轉,
亂碼問題
1、在index.jsp頁面寫一個表單
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action=${pageContext.request.contextPath}/data/t1 method="post">
<input type="text" name="name">
<input type="submit">
</form>
</body>
</html>
2、后端處理程式
@Controller
@RequestMapping("/data")
public class DataController {
// 域名引數與控制器引數名一致的情況
@RequestMapping("/t1")
public String test1(String name, Model model){
// 1 接收前端引數
System.out.println(name);
// 2 將資料回傳給前端
model.addAttribute("msg", name);
return "test";
}
}
3、輸入中文 哈哈哈 測驗

亂碼問題通過過濾器解決,Spring MVC 提供了一個過濾器,需要在web.xml中配置!
<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>

自定義過濾器:
package com.zzb.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, FilterChain chain) throws IOException, ServletException {
//處理response的字符編碼
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 轉型為與協議相關物件
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物件的建構式,以便對其進行裝飾
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]; // 取回引數的第一個值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
然后在web.xml中配置這個過濾器即可!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/235202.html
標籤:Java
上一篇:精盡Spring MVC原始碼分析 - HandlerMapping 組件(一)之 AbstractHandlerMapping
