springmvc之註解介紹、方法返回值、異常處理以及數據交互

一、@RequestMapping

通過@RequestMapping註解可以定義不同的處理器映射規則。

1.1 URL路徑映射

@RequestMapping(value=“item”)或@RequestMapping("/item")。
value的值是數組,可以將多個url映射到同一個方法。

//查詢商品列表
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
	// 查詢商品數據
	List<Item> list = this.itemService.queryItemList();

	// 創建ModelAndView,設置邏輯視圖名
	ModelAndView mv = new ModelAndView("itemList");

	// 把商品數據放到模型中
	mv.addObject("itemList", list);
	return mv;
}

1.2 添加在類上面

在class上添加@RequestMapping(url)指定通用請求前綴, 限制此類下的所有方法請求url必須以請求前綴開頭。
可以使用此方法對url進行分類管理,如下圖:
在這裏插入圖片描述此時需要進入queryItemList()方法的請求url爲:
http://localhost:8080/springmvc-mybatis/item/itemList.action
或者:
http://localhost:8080/springmvc-mybatis/item/itemListAll.action

1.3 請求方法限定

    除了可以對url進行設置,還可以限定請求進來的方法:
        限定GET方法
          @RequestMapping(method = RequestMethod.GET)
          如果通過POST訪問則報錯:
             HTTP Status 405 - Request method ‘POST’ not supported
        限定POST方法
          @RequestMapping(method = RequestMethod.POST)
           如果通過GET訪問則報錯:
               HTTP Status 405 - Request method ‘GET’ not supported
        GET和POST都可以
             @RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})

二、controller方法返回值

2.1 返回ModelAndView

controller方法中定義ModelAndView對象並返回,對象中可添加model數據、指定view。

2.2 返回void

      在Controller方法形參上可以定義request和response,使用request或response指定響應結果:

  1. 使用request轉發頁面,如下:
            request.getRequestDispatcher(“頁面路徑”).forward(request, response);
request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
  1. 可以通過response頁面重定向:
            response.sendRedirect(“url”)
response.sendRedirect("/springmvc-mybatis/itemEdit.action");
  1. 可以通過response指定響應結果,例如響應json數據如下:
response.getWriter().print("{\"abc\":123}");

代碼展示:

	@RequestMapping("/queryItem")
	public void queryItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1 使用request進行轉發
		//request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
		// 2 使用response進行重定向到編輯頁面
		//response.sendRedirect("/springmvc-mybatis/itemEdit.action");
		// 3 使用response直接顯示
		response.getWriter().print("{\"abc\":123}");
	}

2.3 返回字符串

2.3.1 邏輯視圖名

controller方法返回字符串可以指定邏輯視圖名,通過視圖解析器解析爲物理視圖地址。

//指定邏輯視圖名,經過視圖解析器解析爲jsp物理路徑:/WEB-INF/jsp/itemList.jsp
return "itemList";

2.3.2 Redirect重定向

Contrller方法返回字符串可以重定向到一個url地址
如下商品修改提交後重定向到商品編輯頁面。

@RequestMapping("updateItem")
public String updateItemById(Item item) {
	// 更新商品
	this.itemService.updateItemById(item);
	// 修改商品成功後,重定向到商品編輯頁面
	// 重定向後瀏覽器地址欄變更爲重定向的地址,
	// 重定向相當於執行了新的request和response,所以之前的請求參數都會丟失
	// 如果要指定請求參數,需要在重定向的url後面添加 ?itemId=1 這樣的請求參數
	return "redirect:/itemEdit.action?itemId=" + item.getId();
}

2.3.3 forwards轉發

Controller方法執行後繼續執行另一個Controller方法
如下商品修改提交後轉向到商品修改頁面,修改商品的id參數可以帶到商品修改方法中。

@RequestMapping("updateItem")
public String updateItemById(Item item) {
	// 更新商品
	this.itemService.updateItemById(item);

	// 修改商品成功後,重定向到商品編輯頁面
	// 重定向後瀏覽器地址欄變更爲重定向的地址,
	// 重定向相當於執行了新的request和response,所以之前的請求參數都會丟失
	// 如果要指定請求參數,需要在重定向的url後面添加 ?itemId=1 這樣的請求參數
	// return "redirect:/itemEdit.action?itemId=" + item.getId();

	// 修改商品成功後,繼續執行另一個方法
	// 使用轉發的方式實現。轉發後瀏覽器地址欄還是原來的請求地址,
	// 轉發並沒有執行新的request和response,所以之前的請求參數都存在
	return "forward:/itemEdit.action";
}

//結果轉發到editItem.action,request可以帶過去
return "forward: /itemEdit.action";

三、異常處理器

springmvc在處理請求過程中出現異常信息交由異常處理器進行處理,自定義異常處理器可以實現一個系統的異常處理邏輯。

3.1 異常處理思路

      系統中異常包括兩類:預期異常和運行時異常RuntimeException,前者通過捕獲異常從而獲取異常信息,後者主要通過規範代碼開發、測試通過手段減少運行時異常的發生。
      系統的dao、service、controller出現都通過throws Exception向上拋出,最後由springmvc前端控制器交由異常處理器進行異常處理,如下圖:
在這裏插入圖片描述

3.2 自定義異常類

      爲了區別不同的異常,通常根據異常類型進行區分,這裏我們創建一個自定義系統異常。
      如果controller、service、dao拋出此類異常說明是系統預期處理的異常信息。

public class MyException extends Exception {
	// 異常信息
	private String message;
	public MyException() {
		super();
	}
	public MyException(String message) {
		super();
		this.message = message;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

3.3 自定義異常處理器

public class CustomHandleException implements HandlerExceptionResolver {
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) {
		// 定義異常信息
		String msg;
		// 判斷異常類型
		if (exception instanceof MyException) {
			// 如果是自定義異常,讀取異常信息
			msg = exception.getMessage();
		} else {
			// 如果是運行時異常,則取錯誤堆棧,從堆棧中獲取異常信息
			Writer out = new StringWriter();
			PrintWriter s = new PrintWriter(out);
			exception.printStackTrace(s);
			msg = out.toString();

		}
		// 把錯誤信息發給相關人員,郵件,短信等方式
		// TODO
		// 返回錯誤頁面,給用戶友好頁面顯示錯誤信息
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("msg", msg);
		modelAndView.setViewName("error");
		return modelAndView;
	}
}

3.4 異常處理器配置

在springmvc.xml中添加:

<!-- 配置全局異常處理器 -->
	<bean id="customHandleException" class="com.springmvc_mybatis.exception.CustomHandleException"/>

此時出現異常時,就會被轉到錯誤頁面去

四、上傳圖片

4.1 配置虛擬目錄

在tomcat上配置圖片虛擬目錄,在tomcat下conf/server.xml中添加:<Context docBase=“F:\test\temp” path="/pic" reloadable=“false”/>
訪問http://localhost:8080/pic即可訪問F:\test\temp下的圖片。
也可以通過eclipse配置,如下圖:
在這裏插入圖片描述

4.2 加入jar包

在這裏插入圖片描述

4.3 配置上傳解析器

在springmvc.xml中配置文件上傳解析器

	<!-- 文件上傳,id必須設置爲multipartResolver -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 設置文件上傳大小 -->
		<property name="maxUploadSize" value="5000000" />
	</bean>

4.4 jsp頁面修改

在這裏插入圖片描述

4.5 圖片上傳

	@RequestMapping("/updateItem")
	public String updateItem(Items item,MultipartFile pictureFile) throws Exception{
		// 圖片上傳
		// 設置圖片名稱,不能重複,可以使用uuid
		String picName = UUID.randomUUID().toString();
		// 獲取文件名
		String oriName = pictureFile.getOriginalFilename();
		// 獲取圖片後綴
		String extName = oriName.substring(oriName.lastIndexOf("."));
		// 開始上傳
		pictureFile.transferTo(new File("F:/test/temp/" + picName + extName));
		// 設置圖片名到商品中
		item.setPic(picName + extName);
		// ---------------------------------------------
		// 更新商品
		this.itemService.updateItemById(item);
		return "forward:/itemEdit.action";
	}

五、json數據交互

5.1 8.1. @RequestBody

作用:
@RequestBody註解用於讀取http請求的內容(字符串),通過springmvc提供的HttpMessageConverter接口將讀到的內容(json數據)轉換爲java對象並綁定到Controller方法的參數上。
傳統的請求參數:
itemEdit.action?id=1&name=zhangsan&age=12
現在的請求參數:
使用POST請求,在請求體裏面加入json數據
{
“id”: 1,
“name”: “測試商品”,
“price”: 99.9,
“detail”: “測試商品描述”,
“pic”: “123456.jpg”
}
本例子應用:
@RequestBody註解實現接收http請求的json數據,將json數據轉換爲java對象進行綁定。

5.2 @ResponseBody

作用:
@ResponseBody註解用於將Controller的方法返回的對象,通過springmvc提供的HttpMessageConverter接口轉換爲指定格式的數據如:json,xml等,通過Response響應給客戶端
本例子應用:
@ResponseBody註解實現將Controller方法返回java對象轉換爲json響應給客戶端。

5.3 請求json,響應json

5.3.1 加入jar包

如果需要springMVC支持json,必須加入json的處理jar。
在這裏插入圖片描述

5.3.2 ItemController編寫

/**
 * 測試json的交互
 * @param item
 * @return
 */
@RequestMapping("testJson")
// @ResponseBody
public @ResponseBody Item testJson(@RequestBody Item item) {
	return item;
}

5.3.3 配置json轉換器

如果不使用註解驅動<mvc:annotation-driven />,就需要給處理器適配器配置json轉換器,參考之前學習的自定義參數綁定。
在springmvc.xml配置文件中,給處理器適配器加入json轉換器:

<!--處理器適配器 -->
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
		<list>
		<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
		</list>
		</property>
	</bean>

六、RESTFul支持

6.1 什麼是restful

Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。
資源:互聯網所有的事物都可以被抽象爲資源
資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進行操作。
分別對應 添加、 刪除、修改、查詢。
傳統方式操作資源
http://127.0.0.1/item/queryItem.action?id=1 查詢,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 刪除,GET或POST
使用RESTful操作資源
http://127.0.0.1/item/1 查詢,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 刪除,DELETE

6.2 需求

RESTful方式實現商品信息查詢,返回json數據。

6.3 從url上獲取參數

使用RESTful風格開發的接口,根據id查詢商品,接口地址是:
http://127.0.0.1/item/1
我們需要從url上獲取商品id,步驟如下:

  1. 使用註解@RequestMapping(“item/{id}”)聲明請求的url
    {xxx}叫做佔位符,請求的URL可以是“item /1”或“item/2”
  2. 使用(@PathVariable() Integer id)獲取url上的數據
/**
 * 使用RESTful風格開發接口,實現根據id查詢商品
 * 
 * @param id
 * @return
 */
@RequestMapping("item/{id}")
@ResponseBody
public Item queryItemById(@PathVariable() Integer id) {
	Item item = this.itemService.queryItemById(id);
	return item;
}

如果@RequestMapping中表示爲"item/{id}",id和形參名稱一致,@PathVariable不用指定名稱。如果不一致,例如"item/{ItemId}"則需要指定名稱@PathVariable(“itemId”)。
http://127.0.0.1/item/123?id=1
注意兩個區別

  1. @PathVariable是獲取url上數據的。@RequestParam獲取請求參數的(包括post表單提交)
  2. 如果加上@ResponseBody註解,就不會走視圖解析器,不會返回頁面,目前返回的json數據。如果不加,就走視圖解析器,返回頁面。

七、攔截器

7.1 攔截器定義

Spring Web MVC 的處理器攔截器類似於Servlet 開發中的過濾器Filter,用於對處理器進行預處理和後處理。

public class Interceptor implements HandlerInterceptor{

	// controller執行後且視圖返回後調用此方法
		// 這裏可得到執行controller時的異常信息
		// 這裏可記錄操作日誌
		@Override
		public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
				throws Exception {
			System.out.println("HandlerInterceptor1....afterCompletion");
		}

		// controller執行後但未返回視圖前調用此方法
		// 這裏可在返回用戶前對模型數據進行加工處理,比如這裏加入公用信息以便頁面顯示
		@Override
		public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
				throws Exception {
			System.out.println("HandlerInterceptor1....postHandle");
		}

		// Controller執行前調用此方法
		// 返回true表示繼續執行,返回false中止執行
		// 這裏可以加入登錄校驗、權限攔截等
		@Override
		public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
			System.out.println("HandlerInterceptor1....preHandle");
			// 設置爲true,測試使用
			return true;
		}
}

7.2 攔截器配置

在springmvc.xml中配置攔截器

	<!-- 配置攔截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 所有的請求都進入攔截器 -->
			<mvc:mapping path="/**" />
			<!-- 配置具體的攔截器 -->
			<bean class="com.springmvc_mybatis.interceptor.Interceptor" />
		</mvc:interceptor>
	</mvc:interceptors>

7.3 攔截過程總結

preHandle按攔截器定義順序調用
postHandler按攔截器定義逆序調用
afterCompletion按攔截器定義逆序調用

postHandler在攔截器鏈內所有攔截器返成功調用
afterCompletion只有preHandle返回true才調用

7.4 攔截器應用

7.4.1 處理流程

1、有一個登錄頁面,需要寫一個Controller訪問登錄頁面
2、登錄頁面有一提交表單的動作。需要在Controller中處理。
    a) 判斷用戶名密碼是否正確(在控制檯打印)
    b) 如果正確,向session中寫入用戶信息(寫入用戶名username)
    c) 跳轉到商品列表
3、攔截器。
    a) 攔截用戶請求,判斷用戶是否登錄(登錄請求不能攔截)
    b) 如果用戶已經登錄。放行
    c) 如果用戶未登錄,跳轉到登錄頁面。

7.4.2 登錄頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/user/login.action">
<label>用戶名:</label>
<br>
<input type="text" name="username">
<br>
<label>密碼:</label>
<br>
<input type="password" name="password">
<br>
<input type="submit">
</form>
</body>
</html>

7.4.3 登錄controller

@Controller
@RequestMapping("user")
public class UserController {
	//跳轉到登錄頁面
	@RequestMapping("toLogin")
	public String toLogin() {
		return "login";
	}
	//用戶登錄
	@RequestMapping("login")
	public String login(String username, String password, HttpSession session) {
		// 校驗用戶登錄
		System.out.println(username);
		System.out.println(password);
		// 把用戶名放到session中
		session.setAttribute("username", username);
		return "redirect:/item/itemList.action";
	}
}

7.4.4 編寫攔截器

		@Override
		public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
			// 從request中獲取session
			HttpSession session = request.getSession();
			// 從session中獲取username
			Object username = session.getAttribute("username");
			// 判斷username是否爲null
			if (username != null) {
				// 如果不爲空則放行
				return true;
			} else {
				// 如果爲空則跳轉到登錄頁面
			response.sendRedirect(request.getContextPath() + "/user/toLogin.action");
			}
			return false;
		}

7.4.5 配置攔截器

只能攔截商品的url,所以需要修改ItemController,讓所有的請求都必須以item開頭,如下圖:
在這裏插入圖片描述在springmvc.xml配置攔截器

	<!-- 配置攔截器 -->
	<mvc:interceptors>
		<mvc:interceptor>
			<!-- 所有的請求都進入攔截器 -->
			<mvc:mapping path="/item/**" />
			<!-- 配置具體的攔截器 -->
			<bean class="com.springmvc_mybatis.interceptor.Interceptor" />
		</mvc:interceptor>
	</mvc:interceptors>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章