javascript
SpringMVC注解开发(基础)---SpringMVC学习笔记(七)
需求
商品修改功能開發。
操作流程:
1、進入商品查詢列表頁面
2、點擊修改,進入商品修改頁面,頁面中顯示了要修改的商品(從數據庫查詢)
要修改的商品從數據庫查詢,根據商品id(主鍵)查詢商品信息
3、在商品修改頁面,修改商品信息,修改后,點擊提交
第一步:開發Mapper(也就是Dao層)
mapper:
根據id查詢商品信息
根據id更新Items表的數據
不用開發了,使用逆向工程生成的代碼。
第二步:開發Service
接口功能:
根據id查詢商品信息
修改商品信息
service接口:
service接口的實現類:
public class ItemsServiceImpl implements ItemsService {@Autowiredprivate ItemsMapperCustom itemsMapperCustom;@Autowiredprivate ItemsMapper itemsMapper;@Overridepublic List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo)throws Exception {//通過ItemsMapperCustom查詢數據庫return itemsMapperCustom.findItemsList(itemsQueryVo);}@Overridepublic ItemsCustom findItemsById(Integer id)throws Exception {Items items = itemsMapper.selectByPrimaryKey(id);//中間對商品信息進行一系列的處理,最終返回商品信息的擴展類的對象ItemsCustom itemsCustom = new ItemsCustom();//將items的屬性值拷貝到itemsCustomBeanUtils.copyProperties(items, itemsCustom);return itemsCustom ;}@Overridepublic void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {//添加業務的校驗,通常在service接口對關鍵參數進行校驗//因為int這里無法判斷是否為空,所以這里使用Integer//校驗id是否為空,如果為空拋出異常(這里先不寫,后面講異常處理的時候再添加)//更新商品信息,使用updateByPrimaryKeyWithBLOBs()方法可以根據id更新items表中的所有字段(包括大文本類型的字段)itemsCustom.setId(id);itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);}}第三步:開發controller(也就是SpringMVC層)
方法:
商品信息修改頁面顯示
商品信息修改提交
在ItemsController中添加如下代碼:
// 商品信息頁面的展示@RequestMapping("/editItems")public ModelAndView editItems() throws Exception {// 調用service根據商品id查詢商品信息ItemsCustom itemsCustom = itemsService.findItemsById(1);// 返回ModelAndViewModelAndView modelAndView = new ModelAndView();// 將商品信息放入到model中modelAndView.addObject("itemsCustom", itemsCustom);// 商品修改頁面modelAndView.setViewName("items/editItems");return modelAndView;}// 商品信息修改提交@RequestMapping("/editItemsSubmit")public ModelAndView editItemsSubmit() throws Exception {// 調用service更新商品信息ItemsCustom itemsCustom = itemsService.findItemsById(1);// 返回ModelAndViewModelAndView modelAndView = new ModelAndView();// 將商品信息放入到model中modelAndView.addObject("itemsCustom", itemsCustom);// 商品修改頁面modelAndView.setViewName("success");return modelAndView;}頁面代碼:
itemsList.jsp
editItems.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!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>修改商品信息</title></head> <body> <%-- <!-- 顯示錯誤信息 --><c:if test="${allErrors!=null }"><c:forEach items="${allErrors }" var="error">${ error.defaultMessage}<br /></c:forEach></c:if> --%><form id="itemForm"action="${pageContext.request.contextPath }/editItemsSubmit.action"method="post" enctype="multipart/form-data"><input type="hidden" name="id" value="${itemsCustom.id }" /> 修改商品信息:<table width="100%" border=1><tr><td>商品名稱</td><td><input type="text" name="name" value="${itemsCustom.name }" /></td></tr><tr><td>商品價格</td><td><input type="text" name="price"value="${itemsCustom.price }" /></td></tr><%-- <tr><td>商品生產日期</td><td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td> </tr> <tr><td>商品圖片</td><td><c:if test="${items.pic !=null}"><img src="/pic/${items.pic}" width=100 height=100/><br/></c:if><input type="file" name="items_pic"/> </td> </tr> --%><tr><td>商品簡介</td><td><textarea rows="3" cols="30" name="detail">${itemsCustom.detail }</textarea></td></tr><tr><td colspan="2" align="center"><input type="submit" value="提交" /></td></tr></table></form> </body></html>深入分析Controller層的內容
1.@RequestMappring注解的作用:
1.URL路徑映射
@RequestMapping(value=”/item”)或@RequestMapping(“/item)
value的值是數組,可以將多個url映射到同一個方法
2.窄化請求映射
在class上添加@RequestMapping(url)指定通用請求前綴, 限制此類下的所有方法請求url必須以請求前綴開頭,通過此方法對url進行分類管理。
如下:
@RequestMapping放在類名上邊,設置請求前綴
@Controller
@RequestMapping(“/item”)
方法名上邊設置請求映射url:
@RequestMapping放在方法名上邊,如下:
@RequestMapping(“/queryItem “)
訪問地址為:/item/queryItem
3.限定http請求的方式
- 限定GET方法
如果通過Post訪問則報錯:
HTTP Status 405 - Request method ‘POST’ not supported
例如:
- 限定POST方法
如果通過Get訪問則報錯:
HTTP Status 405 - Request method ‘GET’ not supported
- GET和POST都可以
2.controller類中方法的返回值:
1.返回ModelAndView
需要方法結束時,定義ModelAndView,將model和view分別進行設置。
2.返回String
如果controller方法返回string,
表示返回邏輯視圖名。
真正視圖(jsp路徑)=前綴+邏輯視圖名+后綴
redirect重定向
需求:商品修改提交后,重定向到商品查詢列表。
redirect重定向特點:瀏覽器地址欄中的url會變化。修改提交的request數據無法傳到重定向的地址。因為重定向后重新進行request(request無法共享)
forward頁面轉發
通過forward進行頁面轉發,瀏覽器地址欄url不變,request可以共享。
3.返回void
在controller方法形參上可以定義request和response,使用request或response指定響應結果:
使用request轉向頁面,如下:
request.getRequestDispatcher(“頁面路徑”).forward(request, response);
也可以通過response頁面重定向:
response.sendRedirect(“url”)
也可以通過response指定響應結果,例如響應json數據如下:
response.setCharacterEncoding(“utf-8”);
response.setContentType(“application/json;charset=utf-8”);
response.getWriter().write(“json串”);
3.參數綁定
參數綁定的過程:
從客戶端請求key/value數據,經過參數綁定,將key/value數據綁定到controller方法的形參上。
springmvc中,接收頁面提交的數據是通過方法形參來接收。而不是在controller類定義成員變量接收(這是struts2的接收方式)!
1.默認支持的參數類型
直接在controller方法形參上定義下邊類型的對象,就可以使用這些對象。在參數綁定過程中,如果遇到下邊類型直接進行綁定。
1.HttpServletRequest
通過request對象獲取請求信息
2.HttpServletResponse
通過response處理響應信息
3.HttpSession
通過session對象得到session中存放的對象
4.Model/ModelMap
ModelMap是Model接口的實現類,通過Model或ModelMap向頁面傳遞數據。
作用:將model數據填充到request域。
如下:
頁面通過${itemsCustom.XXXX}獲取itemsCustom對象的屬性值。
使用Model和ModelMap的效果一樣,如果直接使用Model,springmvc會實例化ModelMap。
2.簡單類型
包括整型、字符串、單精度和雙精度、布爾型。
eg:
請求該controller方法的url為:http://localhost:8080/Spring_mybatis/items/editItems.action?id=1
注意:url中的參數的名字必須與controller方法中的形參的參數名相同。如果不同就不會映射成功。
需求:解決url中的參數名如果和controller方法中的形參的參數名不同時,也可以映射成功的問題
通過@RequestParam對簡單類型的參數進行綁定。
如果不使用@RequestParam,要求request傳入參數名稱和controller方法的形參名稱一致,方可綁定成功。
如果使用@RequestParam,不用限制request傳入參數名稱和controller方法的形參名稱一致。
通過required屬性指定參數是否必須要傳入,如果設置為true,沒有傳入參數,報下邊錯誤:
錯誤信息:
@RequestParam小結:
value:參數名字,即入參的請求參數名字,如value=“item_id”表示請求的參數區中的名字為item_id的參數的值將傳入;
required:是否必須,默認是true,表示請求中一定要有相應的參數,否則將報;
defaultValue:默認值,表示如果請求中沒有同名參數時的默認值
定義如下:
形參名稱為id,但是這里使用value=” item_id”限定請求的參數名為item_id,所以頁面傳遞參數的名必須為item_id。
注意:如果請求參數中沒有item_id將跑出異常:
這里通過required=true限定item_id參數為必需傳遞,如果不傳遞則報400錯誤,可以使用defaultvalue設置默認值,即使required=true也可以不傳item_id參數值
3.pojo類型
1.簡單pojo類型
如果頁面中input的name和controller的pojo形參中的屬性名稱一致,springMVC會自動將頁面中數據綁定到controller中的pojo對應的屬性中。
如下:
editItems.jsp頁面的屬性name定義:
controller的pojo形參的定義:
Contrller方法定義如下:
需要說明的是:簡單類型的參數綁定和pojo參數綁定互不影響。
2.包裝pojo類型
如果頁面中參數的名稱和包裝pojo類中的屬性名一致,那么springMVC會自動將頁面中數據綁定到controller中的pojo對應的屬性中。
包裝對象定義如下:
頁面定義:
注意:頁面中name的值(也就是itemsCustom)和包裝pojo(也就是ItemsQueryVo)中的屬性(也就是itemsCustom屬性)一致,那么SpringMVC就自動將頁面中傳遞過來的參數值映射到下面的Controller方法的形參中。
Controller方法定義如下:
4.集合類型綁定
1.數組的綁定
需求:商品批量刪除,用戶在頁面選擇多個商品,批量刪除。
這里主要為了說明SpringMVC的集合類型綁定所以就只寫表現層的實現了。
頁面的定義:
controller類中方法的定義:
2.list的綁定
需求:通常在需要批量提交數據時,將提交的數據綁定到list中,比如:成績錄入(錄入多門課成績,批量提交),
本例子需求:批量商品修改,在頁面輸入多個商品信息,將多個商品信息提交到controller方法中。
表現層實現:
頁面的定義:
editItemsQuery.jsp
特別說明:
controller方法的定義:
1、進入批量商品修改頁面(頁面樣式參考商品列表實現)
2、批量修改商品提交
使用List接收頁面提交的批量數據,通過包裝pojo接收,在包裝pojo中定義list<pojo>屬性
上面形參對象中需要添加的屬性:
3.map的綁定
也通過在包裝pojo中定義map類型屬性。
在包裝類中定義Map對象,并添加get/set方法,action使用包裝對象接收。
包裝類中定義Map對象如下:
頁面定義如下:
<tr> <td>學生信息:</td> <td> 姓名:<inputtype="text"name="itemInfo['name']"/> 年齡:<inputtype="text"name="itemInfo['price']"/> .. .. .. </td> </tr>Contrller方法定義如下:
public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{ System.out.println(queryVo.getStudentinfo()); }5.自定義類型綁定
舉例:自定義日期類型綁定
對于controller形參中pojo對象,如果屬性中有日期類型,需要自定義參數綁定。
將請求日期數據串傳成 日期類型,要轉換的日期類型和pojo中日期屬性的類型保持一致。
所以自定義參數綁定將日期串轉成java.util.Date類型。
然后需要向處理器適配器中注入自定義的參數綁定組件。
自定義日期類型綁定組件:
配置方式1:
配置方式2:
<!--注解適配器 --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="webBindingInitializer" ref="customBinder"></property> </bean><!-- 自定義webBinder --><bean id="customBinder"class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"><property name="conversionService" ref="conversionService" /></bean><!-- conversionService --><bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean"><!-- 轉換器 --><property name="converters"><list><bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/></list></property></bean>SpringMVC與Struts2的不同
Post中文亂碼問題
在@RequestMapping中設置http請求方式為post時的出現的中文亂碼問題解決方式:
在web.xml中加入:
以上可以解決post請求亂碼問題。
對于get請求中文參數出現亂碼解決方法有兩個:
修改tomcat配置文件添加編碼與工程編碼一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>另外一種方法對參數進行重新編碼:
String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")ISO8859-1是tomcat默認編碼,需要將tomcat編碼后的內容按utf-8編碼
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的SpringMVC注解开发(基础)---SpringMVC学习笔记(七)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringMVC与Mybatis整合-
- 下一篇: SpringMVC校验---Spring