?
對于java中的思考的方向,1必須要看前端的頁面,對于前端的頁面基本的邏輯,如果能理解最好,不理解也要知道幾點。
1他傳遞什么樣的參數,url是什么。
2返回什么樣的值,或者說是json,是自己定義好的某個工具類中,
3 返回的值是在那幾個表中存在的,對于某些表而言是否需要補齊。
4對于頁面的轉發而言:
轉發和沖頂向的時候,參數的設置
5
Controller對于正常的來說:
因為注解的存在,前期你只要設置好以后是不需要寫什么的,
?如果你引入了dubbo的話,有可能需要接受下服務。
?? Service
因為這個也是使用注解的存在,如果使用dubbo的話,提供下服務即可。
??Dao一般采取單表進行查詢,用逆向工程區實現,
注意下: 對于搜索而言的,搜索中的三圈問題,
在xml中設置參數,編碼問題,就好像之前的國稅系統一樣。
課程計劃
第一天
[if !supportLists]1、[endif]SpringMVC介紹
[if !supportLists]2、[endif]入門程序
[if !supportLists]3、[endif]SpringMVC架構講解
[if !supportLists]a)???????[endif]框架結構
[if !supportLists]b)???????[endif]組件說明
[if !supportLists]4、[endif]SpringMVC整合MyBatis
[if !supportLists]5、[endif]參數綁定
[if !supportLists]a)???????[endif]SpringMVC默認支持的類型
[if !supportLists]b)???????[endif]簡單數據類型
[if !supportLists]c)???????[endif]Pojo類型
[if !supportLists]d)???????[endif]Pojo包裝類型
[if !supportLists]e)???????[endif]自定義參數綁定
[if !supportLists]6、[endif]SpringMVC和Struts2的區別
第二天
[if !supportLists]1、[endif]高級參數綁定
[if !supportLists]a)???????[endif]數組類型的參數綁定
[if !supportLists]b)???????[endif]List類型的綁定
[if !supportLists]2、[endif]@RequestMapping注解的使用
[if !supportLists]3、[endif]Controller方法返回值
[if !supportLists]4、[endif]SpringMVC中異常處理
[if !supportLists]5、[endif]圖片上傳處理
[if !supportLists]6、[endif]Json數據交互
[if !supportLists]7、[endif]SpringMVC實現RESTful
8、攔截器
Web-inf
1:? DispatcherServlet和亂碼問題
2:? Conf? springmvc.xml
??約束:通常會配的
2.1 視圖解析器
2.2 注解的方式,進行掃描
2.3?? 相當于加載了上面的東西。
自動加載RequestMappingHandlerMapping和RequestMappingHandlerAdapter
Springmvc和mybatis的整合
常見的接受參數合返回域對象,
他里面是有request和response的api的一般為了解耦,不用罷了。
接受參數:
1:在上面接受參數的時候,用包裝類型Integer,因為基礎的數據不能為空。
value:參數名字,即入參的請求參數名字,如value=“itemId”表示請求的參數 ?? 區中的名字為itemId的參數的值將傳入
required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報錯
TTP Status 400 - Required Integer parameter 'XXXX' is notpresent
defaultValue:默認值,表示如果請求中沒有同名參數時的默認值
@RequestParam,?? 在這里名字可以不一樣,第一次訪問給默認值
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
?????? ModelMapmodelMap) {
2:用pojo進行接受。?
用你逆向工程生成的pojo的方式來進行傳遞數據。這個比較方便,只要名字一樣就可以了。
用這種方式的時候,如果存在的日期的話,會爆粗,他只能轉化為基本的數據類型,?你要加上一個轉換器就可以了。
用這個對象的時候,jsp里面的寫法問題,所以才會出現,如果兩個類的成員出現了同名的話,那么就要封裝到一個大的javaBean里面。
public class QueryVo {
??? private Item item;
set/get。。。
}
[if !vml]
[endif]
頁面定義如下圖:
1:接受數組的形式 String 【】 id, 你可以在pojo中進行定義,
也可以單獨搞一個這種參數。
[if !supportLists]1.1. [endif]將表單的數據綁定到List
[if !supportLists]1.1.1. [endif]需求
實現商品數據的批量修改。
[if !supportLists]1.1.2. [endif]開發分析
開發分析
[if !supportLists]1. [endif]在商品列表頁面中可以對商品信息進行修改。
[if !supportLists]2. [endif]可以批量提交修改后的商品數據。
[if !supportLists]1.1.3. [endif]定義pojo
List中存放對象,并將定義的List放在包裝類QueryVo中
使用包裝pojo對象接收,如下圖:
[if !vml]
[endif]
[if !supportLists]1.1.4. [endif]Jsp改造
前端頁面應該顯示的html代碼,如下圖:
[if !vml]
[endif]
分析發現:name屬性必須是list屬性名+下標+元素屬性。
Jsp做如下改造:
"${itemList }"var="item"varStatus="s">
??? "checkbox"name="ids"value="${item.id}"/>
?????? "hidden"name="itemList[${s.index}].id"value="${item.id }"/>
?????? "text"name="itemList[${s.index}].name"value="${item.name }"/>
??? "text"name="itemList[${s.index}].price"value="${item.price }"/>
??? "text"name="itemList[${s.index}].createtime"value=""yyyy-MM-dd HH:mm:ss"/>"/>
??? "text"name="itemList[${s.index}].detail"value="${item.detail }"/>
??? "${pageContext.request.contextPath
}/itemEdit.action?id=${item.id}">修改
${current} 當前這次迭代的(集合中的)項
${status.first}?? 判斷當前項是否為集合中的第一項,返回值為true或false
${status.last}??? 判斷當前項是否為集合中的最
varStatus屬性常用參數總結下:
${status.index}?? 輸出行號,從0開始。
${status.count}?? 輸出行號,從1開始。
${status.后一項,返回值為true或false
begin、end、step分別表示:起始序號,結束序號,跳躍步伐。
不再使用
[if !supportLists]1.2. [endif]自定義參數綁定
[if !supportLists]1.2.1. [endif]需求
在商品修改頁面可以修改商品的生產日期,并且根據業務需求自定義日期格式。
[if !supportLists]1.2.2. [endif]需求分析
由于日期數據有很多種格式,springmvc沒辦法把字符串轉換成日期類型。所以需要自定義參數綁定。
前端控制器接收到請求后,找到注解形式的處理器適配器,對RequestMapping標記的方法進行適配,并對方法中的形參進行參數綁定。可以在springmvc處理器適配器上自定義轉換器Converter進行參數綁定。
一般使用注解驅動加載處理器適配器,可以在此標簽上進行配置。
[if !supportLists]1.2.3. [endif]修改jsp頁面
如下圖修改itemEdit.jsp頁面,顯示時間
[if !vml]
[endif]
[if !supportLists]1.2.4. [endif]自定義Converter
//Converter
//S:source,需要轉換的源的類型
//T:target,需要轉換的目標類型
public class DateConverter implementsConverter {
?? @Override
?? public Date convert(String source) {
????? try {
???????? // 把字符串轉換為日期類型
???????? SimpleDateFormatsimpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
???????? Datedate = simpleDateFormat.parse(source);
???????? return date;
????? }catch (ParseException e) {
???????? // TODOAuto-generated catch block
???????? e.printStackTrace();
????? }
????? // 如果轉換異常則返回空
????? return null;
?? }
}
在進行傳遞參數的時候:
域對象傳遞值:Model
ModelMap是Model接口的實現類
model.addAttribute("item", item);
轉發或者是重定向的時候傳遞參數:添加以后,跳轉到list。
// 返回的值的時候傳遞值。
??? return "redirect:/itemEdit.action?itemId=" + item.getId();
// 這個就相當于add跳轉到list
return "forward: /itemEdit.action";
應該是這樣的定義的。
你在*.action一樣,
你在瀏覽器中是要添加?xxx.action的。
你在RequestMapping的時候是不用的。
springmvc與struts2不同
[if !supportLists]1、? [endif]springmvc的入口是一個servlet即前端控制器,而struts2入口是一個filter過濾器。
[if !supportLists]2、?[endif]springmvc是基于方法開發(一個url對應一個方法),請求參數傳遞到方法的形參,可以設計為單例或多例(建議單例),struts2是基于類開發,傳遞參數是通過類的屬性,只能設計為多例。
[if !supportLists]3、? [endif]Struts采用值棧存儲請求和響應的數據,通過OGNL存取數據, springmvc通過參數解析器是將request請求內容解析,并給方法形參賦值,將數據和視圖封裝成ModelAndView對象,最后又將ModelAndView中的模型數據通過request域傳輸到頁面。Jsp視圖解析器默認使用jstl。
[if !supportLists]4、? [endif]Springmvc的效率更加的高一點,struts的效率低一點。
[if !supportLists]1.2.5. [endif]常用的注解:
@RequestMapping(value = { "itemList", "itemListAll"},
Method=RequestMethod.POST)
@ResponseBody? 使用json的形式進行解析,如果是String的話,直接顯示到瀏覽器中。??可以使用javaBean或者是集合容器,list,map,
你只有定義了這個注解,他才不會轉發到視圖中,要不然即使是void,他依然是會進行跳轉的。??路徑加上前后綴。
(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,?ModelMap modelMap)
這個是接受參數的,uri的形式的
圖片上傳:
[if !supportLists]2.??[endif]上傳圖片
[if !supportLists]2.1. [endif]配置虛擬目錄
在tomcat上配置圖片虛擬目錄,在tomcat下conf/server.xml中添加:
D:\develop\upload\temp"path="/pic" reloadable="false"/>
訪問http://localhost:8080/pic即可訪問D:\develop\upload\temp下的圖片。
也可以通過eclipse配置,如下圖:
[if !vml]
[endif]
[if !vml]
[endif]
復制一張圖片到存放圖片的文件夾,使用瀏覽器訪問
測試效果,如下圖:
[if !vml]
[endif]
[if !supportLists]2.2. [endif]加入jar包
實現圖片上傳需要加入的jar包,如下圖:
[if !vml]
[endif]
把兩個jar包放到工程的lib文件夾中
[if !supportLists]2.3. [endif]配置上傳解析器
在springmvc.xml中配置文件上傳解析器
-->
"multipartResolver"
??? class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
??? "maxUploadSize"value="5000000"/>
[if !supportLists]2.4. [endif]jsp頁面修改
在商品修改頁面,打開圖片上傳功能,如下圖:
[if !vml]
[endif]
設置表單可以進行文件上傳,如下圖:
[if !vml]
[endif]
[if !supportLists]2.5. [endif]圖片上傳
在更新商品方法中添加圖片上傳邏輯
/**
?*更新商品
?*
?*@param item
?*@return
?*@throws Exception
?*/
@RequestMapping("updateItem")
public String updateItemById(Item item, MultipartFile pictureFile) throws Exception {
??? // 圖片上傳
??? // 設置圖片名稱,不能重復,可以使用uuid
??? StringpicName = UUID.randomUUID().toString();
??? // 獲取文件名
??? StringoriName = pictureFile.getOriginalFilename();
??? // 獲取圖片后綴
??? StringextName = oriName.substring(oriName.lastIndexOf("."));
??? // 開始上傳
??? pictureFile.transferTo(new File("C:/upload/image/" + picName + extName));
??? // 設置圖片名到商品中
??? item.setPic(picName + extName);
??? // ---------------------------------------------
??? // 更新商品
??? this.itemService.updateItemById(item);
??? return "forward:/itemEdit.action";
}
效果,如下圖:[if !vml]
[endif]
[if !supportLists]3.??[endif]json數據交互
[if !supportLists]3.1. [endif]@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對象進行綁定
[if !supportLists]3.2. [endif]@ResponseBody
作用:
@ResponseBody注解用于將Controller的方法返回的對象,通過springmvc提供的HttpMessageConverter接口轉換為指定格式的數據如:json,xml等,通過Response響應給客戶端。你也可以直接返回string對象,那么是向瀏覽器返回string的值。
本例子應用:
@ResponseBody注解實現將Controller方法返回java對象轉換為json響應給客戶端。
[if !supportLists]3.3. [endif]請求json,響應json實現:
[if !supportLists]3.3.1. [endif]加入jar包
如果需要springMVC支持json,必須加入json的處理jar
我們使用Jackson這個jar,如下圖:
[if !vml]
[endif]
[if !supportLists]3.3.2. [endif]ItemController編寫
/**
?*測試json的交互
?*@param item
?*@return
?*/
@RequestMapping("testJson")
// @ResponseBody
public @ResponseBody Item testJson(@RequestBody Item item) {
??? return item;
}
[if !supportLists]3.3.3. [endif]安裝谷歌瀏覽器測試工具
安裝程序在課后資料
參考安裝文檔,如下圖:
[if !vml]
[endif]
[if !supportLists]3.3.4. [endif]測試方法
測試方法,如下圖:
[if !vml]
[endif]
[if !supportLists]3.3.5. [endif]測試結果
如下圖:
[if !vml]
[endif]
[if !supportLists]3.3.6. [endif]配置json轉換器
如果不使用注解驅動
/>,就需要給處理器適配器配置json轉換器,參考之前學習的自定義參數綁定。
在springmvc.xml配置文件中,給處理器適配器加入json轉換器:
?? "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
????? <property name="messageConverters">
?????
????? "org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
[if !supportLists]4.??[endif]RESTful支持
[if !supportLists]4.1. [endif]什么是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
[if !supportLists]4.2. [endif]需求
RESTful方式實現商品信息查詢,返回json數據
[if !supportLists]4.3. [endif]從URL上獲取參數
使用RESTful風格開發的接口,根據id查詢商品,接口地址是:
http://127.0.0.1/item/1
我們需要從url上獲取商品id,步驟如下:
[if !supportLists]1. [endif]使用注解@RequestMapping("item/{id}")聲明請求的url
{xxx}叫做占位符,請求的URL可以是“item /1”或“item/2”
[if !supportLists]2. [endif]使用(@PathVariable() Integer id)獲取url上的數據?
/**
?*使用RESTful風格開發接口,實現根據id查詢商品
?*
?*@param id
?*@return
?*/
@RequestMapping("item/{id}")
@ResponseBody
public Item queryItemById(@PathVariable() Integer id) {
??? Itemitem = this.itemService.queryItemById(id);
??? return item;
}
如果@RequestMapping中表示為"item/{id}",id和形參名稱一致,@PathVariable不用指定名稱。如果不一致,例如"item/{ItemId}"則需要指定名稱@PathVariable("itemId")。
http://127.0.0.1/item/123?id=1
注意兩個區別
[if !supportLists]1. [endif]@PathVariable是獲取url上數據的。@RequestParam獲取請求參數的(包括post表單提交)
[if !supportLists]2. [endif]如果加上@ResponseBody注解,就不會走視圖解析器,不會返回頁面,目前返回的json數據。如果不加,就走視圖解析器,返回頁面
[if !supportLists]5.??[endif]攔截器
[if !supportLists]5.1. [endif]定義
?????? Spring Web MVC的處理器攔截器類似于Servlet 開發中的過濾器Filter,用于對處理器進行預處理和后處理。
[if !supportLists]5.2. [endif]攔截器定義
實現HandlerInterceptor接口,如下:
public class HandlerInterceptor1 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;
??? }
}
[if !supportLists]5.3. [endif]攔截器配置
上面定義的攔截器再復制一份HandlerInterceptor2,注意新的攔截器修改代碼:
System.out.println("HandlerInterceptor2....preHandle");
在springmvc.xml中配置攔截器
???
?????? "/**"/>
?????? "cn.itcast.ssm.interceptor.HandlerInterceptor1"/>
???
?????? "/**"/>
?????? "cn.itcast.ssm.interceptor.HandlerInterceptor2"/>
?
[if !supportLists]5.4. [endif]正常流程測試
瀏覽器訪問地址
http://127.0.0.1:8080/springmvc-web2/itemList.action
[if !supportLists]5.4.1. [endif]運行流程
控制臺打印:
HandlerInterceptor1..preHandle..
HandlerInterceptor2..preHandle..
HandlerInterceptor2..postHandle..
HandlerInterceptor1..postHandle..
HandlerInterceptor2..afterCompletion..
HandlerInterceptor1..afterCompletion..
[if !supportLists]5.5. [endif]中斷流程測試
瀏覽器訪問地址
http://127.0.0.1:8080/springmvc-web2/itemList.action
[if !supportLists]5.5.1. [endif]運行流程
HandlerInterceptor1的preHandler方法返回false,HandlerInterceptor2返回true,運行流程如下:
HandlerInterceptor1..preHandle..
從日志看出第一個攔截器的preHandler方法返回false后第一個攔截器只執行了preHandler方法,其它兩個方法沒有執行,第二個攔截器的所有方法不執行,且Controller也不執行了。
HandlerInterceptor1的preHandler方法返回true,HandlerInterceptor2返回false,運行流程如下:
HandlerInterceptor1..preHandle..
HandlerInterceptor2..preHandle..
HandlerInterceptor1..afterCompletion..
從日志看出第二個攔截器的preHandler方法返回false后第一個攔截器的postHandler沒有執行,第二個攔截器的postHandler和afterCompletion沒有執行,且controller也不執行了。
總結:
preHandle按攔截器定義順序調用
postHandler按攔截器定義逆序調用
afterCompletion按攔截器定義逆序調用
postHandler在攔截器鏈內所有攔截器返成功調用
afterCompletion只有preHandle返回true才調用
[if !supportLists]5.6. [endif]攔截器應用
[if !supportLists]5.6.1. [endif]處理流程
[if !supportLists]1、[endif]有一個登錄頁面,需要寫一個Controller訪問登錄頁面
[if !supportLists]2、[endif]登錄頁面有一提交表單的動作。需要在Controller中處理。
[if !supportLists]a)???????[endif]判斷用戶名密碼是否正確(在控制臺打印)
[if !supportLists]b)???????[endif]如果正確,向session中寫入用戶信息(寫入用戶名username)
[if !supportLists]c)???????[endif]跳轉到商品列表
[if !supportLists]3、[endif]攔截器。
[if !supportLists]a)???????[endif]攔截用戶請求,判斷用戶是否登錄(登錄請求不能攔截)
[if !supportLists]b)???????[endif]如果用戶已經登錄。放行
[if !supportLists]c)???????[endif]如果用戶未登錄,跳轉到登錄頁面。
[if !supportLists]5.6.2. [endif]編寫登錄jsp
<%@pagelanguage="java"contentType="text/html; charset=UTF-8"
??? pageEncoding="UTF-8"%>
"Content-Type"content="text/html;
charset=UTF-8">
Insert
title here
"${pageContext.request.contextPath }/user/login.action">
用戶名:
"text"name="username">
密碼:
"password"name="password">
"submit">
[if !supportLists]5.6.3. [endif]用戶登陸Controller
@Controller
@RequestMapping("user")
public class UserController {
??? /**
??? ?*跳轉到登錄頁面
??? ?*
??? ?*@return
??? ?*/
??? @RequestMapping("toLogin")
??? public String toLogin() {
?????? return "login";
??? }
??? /**
??? ?*用戶登錄
??? ?*
??? ?*@param username
??? ?*@param password
??? ?*@param session
??? ?*@return
??? ?*/
??? @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";
??? }
}
[if !supportLists]5.6.4. [endif]編寫攔截器
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
??? // 從request中獲取session
??? HttpSessionsession = request.getSession();
??? // 從session中獲取username
??? Objectusername = session.getAttribute("username");
??? // 判斷username是否為null
??? if (username != null) {
?????? // 如果不為空則放行
?????? return true;
??? }else {
?????? // 如果為空則跳轉到登錄頁面
?????? response.sendRedirect(request.getContextPath() + "/user/toLogin.action");
??? }
??? return false;
}
[if !supportLists]5.6.5. [endif]配置攔截器
只能攔截商品的url,所以需要修改ItemController,讓所有的請求都必須以item開頭,如下圖:
[if !vml]
[endif]
在springmvc.xml配置攔截器
??? "/item/**"/>
??? "cn.itcast.ssm.interceptor.LoginHandlerInterceptor"/>
[if !supportLists]6.??[endif]Spring入門
[if !supportLists]6.1. [endif]Springmvc是什么
Spring web mvc和Struts2都屬于表現層的框架,它是Spring框架的一部分,我們可以從Spring的整體結構中看得出來,如下圖:
[if !vml]
[endif]
[if !supportLists]6.2. [endif]Springmvc處理流程
如下圖所示:
[if !vml]
[endif]
[if !supportLists]6.2.1. [endif]導入jar包
從課前資料中導入springMVC的jar包,位置如下圖:
[if !vml]
[endif]
[if !supportLists]6.2.2. [endif]加入配置文件
創建config資源文件夾,存放配置文件,如下圖:
[if !vml]
[endif]
[if !supportLists]6.2.2.1. [endif]創建springmvc.xml
創建SpringMVC的核心配置文件
SpringMVC本身就是Spring的子項目,對Spring兼容性很好,不需要做很多配置。
這里只配置一個Controller掃描就可以了,讓Spring對頁面控制層Controller進行管理。
創建springmvc.xml
"1.0"encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
??? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
??? xmlns:context="http://www.springframework.org/schema/context"
??? xmlns:mvc="http://www.springframework.org/schema/mvc"
??? xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
???????http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
???????http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd">
??? "cn.itcast.springmvc.controller"/>
配置文件需要的約束文件,位置如下圖:
[if !vml]
[endif]
[if !supportLists]6.2.2.2. [endif]配置前端控制器
配置SpringMVC的前端控制器DispatcherServlet
需要注意的是:
在web.xml中
"1.0"encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance"
??? xmlns="http://java.sun.com/xml/ns/javaee"
??? xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
??? id="WebApp_ID"version="2.5">
??? springmvc-first
???
?????? index.html
?????? index.htm
?????? index.jsp
?????? default.html
?????? default.htm
?????? default.jsp
???
?????? springmvc-first
?????? org.springframework.web.servlet.DispatcherServlet
-->
??????
?????????? contextConfigLocation
?????????? classpath:springmvc.xml
???
??? ??? springmvc-first
?????? *.action
[if !supportLists]6.2.2.3. [endif]創建pojo
分析頁面,查看頁面需要的數據,如下圖:
[if !vml]
[endif]
創建商品pojo
public class Item {
??? // 商品id
??? private int id;
??? // 商品名稱
??? private String name;
??? // 商品價格
??? private double price;
??? // 商品創建時間
??? private Date createtime;
??? // 商品描述
??? private String detail;
創建帶參數的構造器
set/get。。。
}
[if !supportLists]6.2.2.4. [endif]創建ItemController
ItemController是一個普通的java類,不需要實現任何接口。
需要在類上添加@Controller注解,把Controller交由Spring管理
在方法上面添加@RequestMapping注解,里面指定請求的url。其中“.action”可以加也可以不加。
@Controller
public class ItemController {
??? // @RequestMapping:里面放的是請求的url,和用戶請求的url進行匹配
??? // action可以寫也可以不寫
??? @RequestMapping("/itemList.action")
??? public ModelAndView queryItemList() {
?????? // 創建頁面需要顯示的商品數據
?????? Listlist = new ArrayList<>();
?????? list.add(new Item(1, "1華為 榮耀8", 2399, new Date(), "質量好!1"));
?????? list.add(new Item(2, "2華為 榮耀8", 2399, new Date(), "質量好!2"));
?????? list.add(new Item(3, "3華為 榮耀8", 2399, new Date(), "質量好!3"));
?????? list.add(new Item(4, "4華為 榮耀8", 2399, new Date(), "質量好!4"));
?????? list.add(new Item(5, "5華為 榮耀8", 2399, new Date(), "質量好!5"));
?????? list.add(new Item(6, "6華為 榮耀8", 2399, new Date(), "質量好!6"));
?????? // 創建ModelAndView,用來存放數據和視圖
?????? ModelAndViewmodelAndView = new ModelAndView();
?????? // 設置數據到模型中
?????? modelAndView.addObject("list", list);
?????? // 設置視圖jsp,需要設置視圖的物理地址
?????? modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
?????? return modelAndView;
??? }
}
[if !supportLists]6.2.3. [endif]啟動項目測試
啟動項目,瀏覽器訪問地址
http://127.0.0.1:8080/springmvc-first/itemList.action
效果如下圖:
[if !vml]
[endif]
為什么可以用呢?我們需要分析一下springMVC的架構圖。
[if !supportLists]7.??[endif]Springmvc架構
[if !supportLists]7.1. [endif]框架結構
框架結構如下圖:
[if !vml]
[endif]
[if !supportLists]7.2. [endif]架構流程
[if !supportLists]1、[endif]用戶發送請求至前端控制器DispatcherServlet
[if !supportLists]2、[endif]DispatcherServlet收到請求調用HandlerMapping處理器映射器。
[if !supportLists]3、[endif]處理器映射器根據請求url找到具體的處理器,生成處理器對象及處理器攔截器(如果有則生成)一并返回給DispatcherServlet。
[if !supportLists]4、[endif]DispatcherServlet通過HandlerAdapter處理器適配器調用處理器
[if !supportLists]5、[endif]執行處理器(Controller,也叫后端控制器)。
[if !supportLists]6、[endif]Controller執行完成返回ModelAndView
[if !supportLists]7、[endif]HandlerAdapter將controller執行結果ModelAndView返回給DispatcherServlet
[if !supportLists]8、[endif]DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
[if !supportLists]9、[endif]ViewReslover解析后返回具體View
[if !supportLists]10、???????????[endif]DispatcherServlet對View進行渲染視圖(即將模型數據填充至視圖中)。
[if !supportLists]11、???????????[endif]DispatcherServlet響應用戶
[if !supportLists]7.3. [endif]組件說明
以下組件通常使用框架提供實現:
[if !supportLists]u?[endif]DispatcherServlet:前端控制器
用戶請求到達前端控制器,它就相當于mvc模式中的c,dispatcherServlet是整個流程控制的中心,由它調用其它組件處理用戶的請求,dispatcherServlet的存在降低了組件之間的耦合性。
[if !supportLists]u? [endif]HandlerMapping:處理器映射器
HandlerMapping負責根據用戶請求url找到Handler即處理器,springmvc提供了不同的映射器實現不同的映射方式,例如:配置文件方式,實現接口方式,注解方式等。
[if !supportLists]u?[endif]Handler:處理器
Handler 是繼DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler對具體的用戶請求進行處理。
由于Handler涉及到具體的用戶業務請求,所以一般情況需要程序員根據業務需求開發Handler。
[if !supportLists]u? [endif]HandlAdapter:處理器適配器
通過HandlerAdapter對處理器進行執行,這是適配器模式的應用,通過擴展適配器可以對更多類型的處理器進行執行。
[if !supportLists]u? [endif]ViewResolver:視圖解析器
View Resolver負責將處理結果生成View視圖,View Resolver首先根據邏輯視圖名解析成物理視圖名即具體的頁面地址,再生成View視圖對象,最后對View進行渲染將處理結果通過頁面展示給用戶。
[if !supportLists]u?[endif]View:視圖
springmvc框架提供了很多的View視圖類型的支持,包括:jstlView、freemarkerView、pdfView等。我們最常用的視圖就是jsp。
一般情況下需要通過頁面標簽或頁面模版技術將模型數據通過頁面展示給用戶,需要由程序員根據業務需求開發具體的頁面。
說明:在springmvc的各個組件中,處理器映射器、處理器適配器、視圖解析器稱為springmvc的三大組件。
需要用戶開發的組件有handler、view
[if !supportLists]7.4. [endif]默認加載的組件
我們沒有做任何配置,就可以使用這些組件
因為框架已經默認加載這些組件了,配置文件位置如下圖:
[if !vml]
[endif]
# Default implementation
classes for DispatcherServlet's strategy interfaces.
# Used as fallback when no
matching beans are found in the DispatcherServlet context.
# Not meant to be customized by
application developers.
org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver
org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
??? org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
??? org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
??? org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
??? org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
??? org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager
[if !supportLists]7.5. [endif]組件掃描器
使用組件掃描器省去在spring容器配置每個Controller類的繁瑣。
使用自動掃描標記@Controller的控制器類,
在springmvc.xml配置文件中配置如下:
"cn.itcast.springmvc.controller"/>
[if !supportLists]7.6. [endif]注解映射器和適配器
[if !supportLists]7.6.1. [endif]配置處理器映射器
注解式處理器映射器,對類中標記了@ResquestMapping的方法進行映射。根據@ResquestMapping定義的url匹配@ResquestMapping標記的方法,匹配成功返回HandlerMethod對象給前端控制器。
HandlerMethod對象中封裝url對應的方法Method。
在springmvc.xml配置文件中配置如下:
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
注解描述:
@RequestMapping:定義請求url到處理器功能方法的映射
[if !supportLists]7.6.2. [endif]配置處理器適配器
注解式處理器適配器,對標記@ResquestMapping的方法進行適配。
從spring3.1版本開始,廢除了AnnotationMethodHandlerAdapter的使用,推薦使用RequestMappingHandlerAdapter完成注解式處理器適配。
在springmvc.xml配置文件中配置如下:
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
[if !supportLists]7.6.3. [endif]注解驅動
直接配置處理器映射器和處理器適配器比較麻煩,可以使用注解驅動來加載。
SpringMVC使用自動加載RequestMappingHandlerMapping和RequestMappingHandlerAdapter
可以在springmvc.xml配置文件中使用替代注解處理器和適配器的配置。
[if !supportLists]7.7. [endif]視圖解析器
視圖解析器使用SpringMVC框架默認的InternalResourceViewResolver,這個視圖解析器支持JSP視圖解析
在springmvc.xml配置文件中配置如下:
prefix="/WEB-INF/jsp/", suffix=".jsp",
viewname="test" ->
?????? "/WEB-INF/jsp/test.jsp" -->
?????? class="org.springframework.web.servlet.view.InternalResourceViewResolver">
?????? "prefix"value="/WEB-INF/jsp/"/>
?????? "suffix"value=".jsp"/>
邏輯視圖名需要在controller中返回ModelAndView指定,比如邏輯視圖名為ItemList,則最終返回的jsp視圖地址:
“WEB-INF/jsp/itemList.jsp”
最終jsp物理地址:前綴+邏輯視圖名+后綴
[if !supportLists]8.??[endif]異常處理器
?????? springmvc在處理請求過程中出現異常信息交由異常處理器進行處理,自定義異常處理器可以實現一個系統的異常處理邏輯。
[if !supportLists]8.1. [endif]異常處理思路
?????? 系統中異常包括兩類:預期異常和運行時異常RuntimeException,前者通過捕獲異常從而獲取異常信息,后者主要通過規范代碼開發、測試通過手段減少運行時異常的發生。
?????? 系統的dao、service、controller出現都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理,如下圖:
[if !vml]
[endif]
[if !supportLists]8.2. [endif]自定義異常類
?????? 為了區別不同的異常,通常根據異常類型進行區分,這里我們創建一個自定義系統異常。
如果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;
??? }
}
[if !supportLists]8.3. [endif]自定義異常處理器
public class CustomHandleException implements HandlerExceptionResolver {
??? @Override
??? public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
?????????? Exceptionexception) {
?????? // 定義異常信息
?????? Stringmsg;
?????? // 判斷異常類型
?????? if (exception instanceof MyException) {
?????????? // 如果是自定義異常,讀取異常信息
?????????? msg = exception.getMessage();
?????? }else {
?????????? // 如果是運行時異常,則取錯誤堆棧,從堆棧中獲取異常信息
?????????? Writerout = new StringWriter();
?????????? PrintWriters = new PrintWriter(out);
?????????? exception.printStackTrace(s);
?????????? msg = out.toString();
?????? }
?????? // 把錯誤信息發給相關人員,郵件,短信等方式
?????? // TODO
?????? // 返回錯誤頁面,給用戶友好頁面顯示錯誤信息
?????? ModelAndViewmodelAndView = new ModelAndView();
?????? modelAndView.addObject("msg", msg);
?????? modelAndView.setViewName("error");
?????? return modelAndView;
??? }
}
[if !supportLists]8.4. [endif]異常處理器配置
在springmvc.xml中添加:
id="customHandleException"? class="cn.itcast.ssm.exception.CustomHandleException"/>
[if !supportLists]8.5.[endif]錯誤頁面
<%@pagelanguage="java"contentType="text/html; charset=UTF-8"
??? pageEncoding="UTF-8"%>
"Content-Type"content="text/html;
charset=UTF-8">
Insert
title here
???
系統發生異常了!
???
???
異常信息
???
???
${msg }
[if !supportLists]8.6. [endif]異常測試
修改ItemController方法“queryItemList”,拋出異常:
/**
?*查詢商品列表
?*
?*@return
?*@throws Exception
?*/
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() throws Exception {
??? // 自定義異常
??? if (true) {
?????? throw new MyException("自定義異常出現了~");
??? }
??? // 運行時異常
??? int a = 1 / 0;
??? // 查詢商品數據
??? Listlist = this.itemService.queryItemList();
??? // 創建ModelAndView,設置邏輯視圖名
??? ModelAndViewmv = new ModelAndView("itemList");
??? // 把商品數據放到模型中
??? mv.addObject("itemList", list);
??? return mv;
}
[if !supportLists]9.??[endif]整合mybatis
?????? 為了更好的學習 springmvc和mybatis整合開發的方法,需要將springmvc和mybatis進行整合。
整合目標:控制層采用springmvc、持久層使用mybatis實現。
[if !supportLists]9.1. [endif]創建數據庫表
sql腳本,位置如下圖:
[if !vml]
[endif]
創建數據庫表springmvc,導入到數據庫中,如下圖:
[if !vml]
[endif]
[if !supportLists]9.2. [endif]需要的jar包
[if !supportLists]1.?????[endif]spring(包括springmvc)
[if !supportLists]2.?????[endif]mybatis
[if !supportLists]3.?????[endif]mybatis-spring整合包
[if !supportLists]4.?????[endif]數據庫驅動
[if !supportLists]5.?????[endif]第三方連接池。
jar包位置如下圖:
[if !vml]
[endif]
[if !supportLists]9.3. [endif]整合思路
Dao層:
[if !supportLists]1、[endif]SqlMapConfig.xml,空文件即可,但是需要文件頭。
[if !supportLists]2、[endif]applicationContext-dao.xml
[if !supportLists]a)???????[endif]數據庫連接池
[if !supportLists]b)???????[endif]SqlSessionFactory對象,需要spring和mybatis整合包下的。
[if !supportLists]c)???????[endif]配置mapper文件掃描器。
Service層:
[if !supportLists]1、[endif]applicationContext-service.xml包掃描器,掃描@service注解的類。
[if !supportLists]2、[endif]applicationContext-trans.xml配置事務。
Controller層:
[if !supportLists]1、[endif]Springmvc.xml
[if !supportLists]a)???????[endif]包掃描器,掃描@Controller注解的類。
[if !supportLists]b)???????[endif]配置注解驅動
[if !supportLists]c)???????[endif]配置視圖解析器
Web.xml文件:
[if !supportLists]1、[endif]配置spring
[if !supportLists]2、[endif]配置前端控制器。
[if !supportLists]9.4. [endif]創建工程
[if !supportLists]9.5. [endif]加入配置文件
創建資源文件夾config
在其下創建mybatis和spring文件夾,用來存放配置文件,如下圖:
[if !vml]
[endif]
[if !supportLists]9.5.1. [endif]sqlMapConfig.xml
使用逆向工程來生成Mapper相關代碼,不需要配置別名。
在config/mybatis下創建SqlMapConfig.xml
"1.0"encoding="UTF-8"?>
PUBLIC"-//mybatis.org//DTD Config
3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
[if !supportLists]9.5.2. [endif]applicationContext-dao.xml
配置數據源、配置SqlSessionFactory、mapper掃描器。
"1.0"encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
??? xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
??? xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
??? 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-4.0.xsd
??? http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd
??? http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd
??? http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.0.xsd">
??? "classpath:db.properties"/>
??? "dataSource"class="org.apache.commons.dbcp.BasicDataSource"
?????? destroy-method="close">
?????? "driverClassName"value="${jdbc.driver}"/>
?????? "url"value="${jdbc.url}"/>
?????? "username"value="${jdbc.username}"/>
?????? "password"value="${jdbc.password}"/>
?????? "maxActive"value="10"/>
?????? "maxIdle"value="5"/>
??? "sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
?????? "dataSource"ref="dataSource"/>
?????? "configLocation"value="classpath:mybatis/SqlMapConfig.xml"/>
??? "org.mybatis.spring.mapper.MapperScannerConfigurer">
?????? "basePackage"value="cn.itcast.ssm.mapper"/>
[if !supportLists]9.5.3. [endif]db.properties
配置數據庫相關信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
[if !supportLists]9.5.4. [endif]applicationContext-service.xml
"1.0"encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
??? xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
??? xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
??? 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-4.0.xsd
??? http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd
??? http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd
??? http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.0.xsd">
??? "cn.itcast.ssm.service"/>
[if !supportLists]9.5.5. [endif]applicationContext-trans.xml
"1.0"encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
??? xmlns:context="http://www.springframework.org/schema/context"xmlns:p="http://www.springframework.org/schema/p"
??? xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"
??? 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-4.0.xsd
??? http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd
??? http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsd
??? http://www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-4.0.xsd">
??? "transactionManager"
?????? class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
?????? "dataSource"ref="dataSource"/>
??? "txAdvice"transaction-manager="transactionManager">
??????
?????????? "save*"propagation="REQUIRED"/>
?????????? "insert*"propagation="REQUIRED"/>
?????????? "delete*"propagation="REQUIRED"/>
?????????? "update*"propagation="REQUIRED"/>
?????????? "find*"propagation="SUPPORTS"read-only="true"/>
?????????? "get*"propagation="SUPPORTS"read-only="true"/>
?????????? "query*"propagation="SUPPORTS"read-only="true"/>
???
?????? "txAdvice"
?????????? pointcut="execution(*
cn.itcast.ssm.service.*.*(..))" />
[if !supportLists]9.5.6. [endif]springmvc.xml
"1.0"encoding="UTF-8"?>
"http://www.springframework.org/schema/beans"
??? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
??? xmlns:context="http://www.springframework.org/schema/context"
??? xmlns:mvc="http://www.springframework.org/schema/mvc"
??? xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
???????http://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
???????http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
??? "cn.itcast.ssm.controller"/>
???
prefix="/WEB-INF/jsp/", suffix=".jsp",
viewname="test" ->
?????? "/WEB-INF/jsp/test.jsp" -->
??? class="org.springframework.web.servlet.view.InternalResourceViewResolver">
?????? "prefix"value="/WEB-INF/jsp/"/>
?????? "suffix"value=".jsp"/>
[if !supportLists]9.5.7. [endif]web.xml
"1.0"encoding="UTF-8"?>
"http://www.w3.org/2001/XMLSchema-instance"
??? xmlns="http://java.sun.com/xml/ns/javaee"
??? xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
??? id="WebApp_ID"version="2.5">
??? springmvc-web
???
?????? index.html
?????? index.htm
?????? index.jsp
?????? default.html
?????? default.htm
?????? default.jsp
???
?????? contextConfigLocation
?????? classpath:spring/applicationContext*.xml
???
?????? org.springframework.web.context.ContextLoaderListener
???
?????? springmvc-web
?????? org.springframework.web.servlet.DispatcherServlet
??????
?????????? contextConfigLocation
?????????? classpath:spring/springmvc.xml
???
?????? springmvc-web
?????? *.action
[if !supportLists]9.6. [endif]效果
配置完效果如下圖:
[if !vml]
[endif]
[if !supportLists]10.????????????[endif]實現商品列表顯示
[if !supportLists]10.1. [endif]需求
實現商品查詢列表,從mysql數據庫查詢商品信息。
[if !supportLists]10.2. [endif]DAO開發
使用逆向工程,生成代碼
注意修改逆向工程的配置文件,參考MyBatis第二天
逆向工程生成代碼如下圖:
[if !vml]
[endif]
[if !supportLists]10.3. [endif]ItemService接口
public interface ItemService {
??? /**
??? ?*查詢商品列表
??? ?*
??? ?*@return
??? ?*/
??? ListqueryItemList();
}
[if !supportLists]10.4. [endif]ItemServiceImpl實現類
@Service
public class ItemServiceImpl implements ItemService {
??? @Autowired
??? private ItemMapper itemMapper;
??? @Override
??? public List queryItemList() {
?????? // 從數據庫查詢商品數據
?????? Listlist = this.itemMapper.selectByExample(null);
?????? return list;
??? }
}
[if !supportLists]10.5. [endif]ItemController
@Controller
public class ItemController {
??? @Autowired
??? private ItemService itemService;
??? /**
??? ?*顯示商品列表
??? ?*
??? ?*@return
??? ?*/
??? @RequestMapping("/itemList")
??? public ModelAndView queryItemList() {
?????? // 獲取商品數據
?????? Listlist = this.itemService.queryItemList();
?????? ModelAndViewmodelAndView = new ModelAndView();
?????? // 把商品數據放到模型中
?????? modelAndView.addObject("itemList", list);
?????? // 設置邏輯視圖
?????? modelAndView.setViewName("itemList");
?????? return modelAndView;
??? }
}
[if !supportLists]10.6. [endif]測試
訪問url:
http://127.0.0.1:8080/springmvc-web/itemList.action
效果如下圖:
[if !vml]
[endif]
[if !supportLists]11.????????????[endif]參數綁定
[if !supportLists]11.1. [endif]默認支持的參數類型
[if !supportLists]11.1.1. [endif]需求
打開商品編輯頁面,展示商品信息。
[if !supportLists]11.1.2. [endif]需求分析
編輯商品信息,首先要顯示商品詳情
需要根據商品id查詢商品信息,然后展示到頁面。
請求的url:/itemEdit.action
參數:id(商品id)
響應結果:商品編輯頁面,展示商品詳細信息。
[if !supportLists]11.1.3. [endif]ItemService接口
編寫ItemService接口如下圖:
[if !vml]
[endif]
[if !supportLists]11.1.4. [endif]ItemServiceImpl實現類
@Override
public Item queryItemById(int id) {
??? Itemitem = this.itemMapper.selectByPrimaryKey(id);
??? return item;
}
[if !supportLists]11.1.5. [endif]ItemController
頁面點擊修改按鈕,發起請求
http://127.0.0.1:8080/springmvc-web/itemEdit.action?id=1
需要從請求的參數中把請求的id取出來。
Id包含在Request對象中。可以從Request對象中取id。
想獲得Request對象只需要在Controller方法的形參中添加一個參數即可。Springmvc框架會自動把Request對象傳遞給方法。
代碼實現
/**
?*根據id查詢商品
?*
?*@param request
?*@return
?*/
@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
??? // 從request中獲取請求參數
??? StringstrId = request.getParameter("id");
??? Integerid = Integer.valueOf(strId);
??? // 根據id查詢商品數據
??? Itemitem = this.itemService.queryItemById(id);
??? // 把結果傳遞給頁面
??? ModelAndViewmodelAndView = new ModelAndView();
??? // 把商品數據放在模型中
??? modelAndView.addObject("item", item);
??? // 設置邏輯視圖
??? modelAndView.setViewName("itemEdit");
??? return modelAndView;
}
[if !supportLists]11.1.6. [endif]解決post亂碼問題
提交發現,保存成功,但是保存的是亂碼
在web.xml中加入:
???
?????? encoding
?????? org.springframework.web.filter.CharacterEncodingFilter
??????
?????????? encoding
?????????? UTF-8
???
?????? encoding
?????? /*
以上可以解決post請求亂碼問題。
對于get請求中文參數出現亂碼解決方法有兩個:
修改tomcat配置文件添加編碼與工程編碼一致,如下:
另外一種方法對參數進行重新編碼:
String userNamenew
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
ISO8859-1是tomcat默認編碼,需要將tomcat編碼后的內容按utf-8編碼