springmvc01

springmvc

@RequestMapping

處理器映射器之因此可以從瀏覽器地址中將對應的地址映射出來,取決於 @RequestMapping 註解的value屬性
由於前端控制器的匹配模式是 *.action 因此對於處理器映射器而言,請求能到達處理器映射器,確定後綴名都是 .action 因此路徑中不寫的 .action 能夠省略規範起見仍是加上php

多個路徑匹配

其value屬性是數組,能夠同時匹配多個映射路徑html

 

enter description here

enter description here

 

簡化路徑

若是當前類中的全部的路徑的前綴都是相同的,那麼能夠使用@RequestMapping配置在類的上方,如下全部的方法均可以省去前面的那個路徑。前端

 

enter description here

enter description here

 

限定請求方法

能夠經過@RequestMapping限定是GET請求仍是POST請求,使用其method屬性(是數組,也就是能夠同時設置多個方式),屬性類型是RequestMethod(枚舉類型)java

 

enter description here

enter description here

 

注意:頁面出現405錯誤表示沒有對應請求的set或get方法,若是出現錯誤,首先排查此項web

controller方法的返回值

對於controller方法的返回值咱們能夠使用3中類型的返回值ajax

ModelAndView

返回數據和頁面,其內部的原理是:數據放在Request域中,頁面經過內部轉發獲得,咱們以前一直使用的是這種類型,使用對象的addObject添加數據,使用serViewName 設置視圖spring

 

enter description here

enter description here

 

void返回值

> 若是返回值是void,則意味着請求處理完成後不會進行頁面跳轉,若是想要進行頁面跳轉,能夠使用參數中的request和response(與其原生態的servlet跳轉)還不如不將返回值設置爲void
// 1 使用request進行轉發request.getRequestD
ispatcher("/WEB-INF/jsp/success.jsp").forward(request,response);
//2 使用response進行重定向response.sendRedi
rect(req.getContextPath()+"/role/roleList.action");

void 的主要用途在於咱們之後要學習的ajax請求,由於ajax只須要返回數據,不須要返回視圖數據庫

String返回值

返回值是String,表明返回視圖的名稱,會配和前面在配置文件中配置的視圖解析器,會加前綴和後綴,若是使用這種方式,能夠使用參數中的model或者modelMap進行數據的填充(企業開發中推薦使用這種方式,由於數據模型和視圖被分離,程序被解耦)數組

 

enter description here

enter description here

 

內部轉發

相對於執行了request的內部轉發的操做,model中的數據存在,至關於一次請求
return "forward:/role/roleList.action;"瀏覽器

重定向

至關於執行了重定向的操做,model中的數據沒有return "redirect:/role/roleList.action?id=" + id;

注意:此種方式的重定向是不須要添加web應用的名稱,系統會自動爲咱們添加

返回值是String注意問題

  • 若是返回值是單純的字符串,springmvc會添加先後綴,若是是重定向或者轉發不會添加先後綴
  • 若是是重定向的話此處的路徑不寫wen應用的名稱,springmvc會默認添加

 

enter description here

enter description here

 

  • 若是咱們使用response對象進行重定向,那麼必需要寫web應用名稱,由於上一種是springmvc幫咱們進行的重定向,使用response的話springmvc就不會給咱們添加
  • 若是是重定向的話model中的數據是不能使用的,由於model中的數據是保存在request域中

設置全局異常處理

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

 

enter description here

enter description here

 

因此咱們要想處理這些從dao、service、controller拋出的這些異常,就須要咱們本身寫一個類實現異常處理器接口HandlerExceptionResolver,而後將此實現類配置到springmvc的配置文件中

@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		
		if(request.getServletPath().equals("/user/login.action")){
			return true;
		}
		
		if(request.getSession().getAttribute("user") != null){
			return true;
		}
		request.getRequestDispatcher("/index.jsp").forward(request, response);
		return false;
	}
<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/>
		<mvc:exclude-mapping path=""/>
		<bean class="top.xiesen.ssm.intercept.LoginIntercept"></bean>
	</mvc:interceptor>
</mvc:interceptors>

1.自定義一個異常類實現 HandlerExceptionResolver ,重寫 resolveException 方法
2.將異常類放到spring容器中,能夠在springmvc文件中配置bean,<bean class="top.xiesen.ssm.util.CustomException"></bean> 或者直接在異常類上添加註解

@Controller
public class CustomException implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exception) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("obj", obj);
		mav.addObject("exception", exception);
		mav.setViewName("role/error");
		return mav;
	}

}

Spring圖像上傳

1.導包 commons-iocommonsfileuplod
2.在jsp頁面上添加上傳空間 <input type="file" name="pic"> name屬性名特別注意不能喝model中的名字相同,由於此處上傳的路徑名不是惟一的,須要咱們本身修改一下路徑名。注意修改form表單的屬性值 <form action="<c:url value="/role/updateRole.action"/>" method="post" enctype="multipart/form-data">
3.編寫Controller實現類

@RequestMapping(value="/role/updateRole.action",method=RequestMethod.POST)
	public String EditRole(RoleVo rv,MultipartFile pic) throws Exception{
		// 產生隨機的名字
		String str = UUID.randomUUID().toString().replaceAll("-", "");
		// 獲取圖像的後綴名
		String extension = FilenameUtils.getExtension(pic.getOriginalFilename());
		// 拼接新起的圖片名
		String fileName = str + "." + extension;
		// 設置圖像上傳後的路徑,
		String path = "D:\\Develop\\upload";
		// 拼接成圖片訪問路徑
		pic.transferTo(new File(path + "\\" + fileName));
		// 把文件名給對象
		rv.getRole().setrPic(fileName);
		// 數據庫更新
		rs.updateRole(rv.getRole());
		// 跳轉頁面
		return "redirect:/role/roleList.action";
	}

4.在springmvc中配置上傳實現類

<!-- 這個bean比較特殊,只能使用id進行標識,而且id必須是id="multipartResolver" -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	<!-- 配置圖片最大上傳大小 -->
	<property name="maxUploadSize" value="6291456"></property>
</bean>

咱們也能夠建立一個虛擬目錄,進行文件的存放文件,這樣就不會在服務器從新部署的時候將文件夾的內容給清空了

 

enter description here

enter description here

 

RESTful支持

Restful就是一個資源定位及資源操做的風格。不是標準也不是協議,只是一種風格

 

enter description here

enter description here

 

  • 使用RESTful進行資源訪問,requestMapping上要使用{變量名} ,參數使用註解 @PathVariable 進行獲取

 

enter description here

enter description here

 

@RequestMapping("/{id}.action")
public ModelAndView restful(@PathVariable Integer id){
	System.out.println(id);
	ModelAndView mv = new ModelAndView();
	mv.setViewName("success");
	return mv;
}

自定義分頁標籤

目錄結構

 

enter description here

enter description here

 

操做步驟

  • 將tld文件夾拷貝到WEB-INF下
  • 將NavigationTag和Page文件拷貝到src自定義目錄
  • 修改tld文件夾下的 commons.tld 文件,注意將 <tagclass> 標籤改成 NavigationTag 的完整類名
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
	<tlib-version>2.0</tlib-version>
	<jsp-version>1.2</jsp-version>
	<short-name>common</short-name>
	<!-- 名字能夠隨便寫,至關於引入標籤庫中的uri -->
	<uri>http://top.xiesen.com/common/</uri>
	<!-- 至關於給標籤庫起的名字 -->
	<display-name>Common Tag</display-name>
	<!-- 給標籤庫進行的描述 -->
	<description>Common Tag library</description>
	<!-- 在該標籤庫中定義一個標籤 -->
	<tag>
	<!-- 標籤的名稱 -->
		<name>page</name>
		<!-- 和相關的類進行關聯 -->
		<tag-class>top.xiesen.ssm.util.NavigationTag</tag-class>
		<body-content>JSP</body-content>
		<description>create navigation for paging</description>
		<!-- 定義標籤中的一個屬性名稱是bean-->
		<attribute>
			<name>bean</name>
			<!-- 是否能夠經過jsp表達式動態的進行賦值 -->
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<!-- 定義標籤中的一個屬性名稱是number-->
		<attribute>
			<name>number</name>
			<!-- 是否能夠經過jsp表達式動態的進行賦值 -->
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<!-- 定義標籤中的屬性 -->
		<attribute>
			<name>url</name>
			<!-- 是不是必須的 -->
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>
	</tag>
</taglib>
  • 在須要引入分頁標籤的文件中添加標籤庫的引入,注意 uri 爲以前定義的路徑
<%@ taglib prefix="xs" uri="http://top.xiesen.com/common/" %>
  • 在頁面中添加分頁,注意url屬性不能使用c標籤,而且只有域中有名稱爲page且值爲page對象的數據的時候,分頁才能正常顯示,不然分頁是不會渲染的
<xs:page url="${pageContext.request.contextPath }/user/userList.action"></xs:page>
  • 在對應的controller中,須要向model中放入名稱爲page,值爲page對象的數據
  • page中有4個屬性
    • total表示總條數
    • page表示當前頁
    • size表示每頁顯示多少條
    • rows表示存放的數據
  • NavigationTag中有3個屬性
    • bean表示在jsp頁面中放在request域中的key的值,默認是page
    • number表示分頁標籤中顯示多少個頁碼(有默認值)
    • url表示點擊分頁後請求的地址(會自動讀取請求中的數據進行拼接)
  • 在處理分頁的時候,必定要注意表單中的數據回填,由於 NavigationTag 會將回填的數據獲取到,進行url上的拼接,因此當咱們查看分頁標籤的連接地址的時候會發現其後面會默認拼接進行回填的數據,這樣 controller 就能獲得請求頁和請求查詢的數據進行查詢

 

enter description here

enter description here

 

  • 建立分頁對象的過程應該在service層進行建立
@Override
	public Page loadPage(String userKeyWord, String userserarchfield, int currentPage) {
		Page<User> page = new Page<>();
		page.setPage(currentPage);
		page.setTotal(um.findAllUserCount(userKeyWord,userserarchfield));
		page.setSize(10);
		page.setRows(um.findAllUser(userKeyWord, userserarchfield,(currentPage-1)*10));
		return page;
	}
相關文章
相關標籤/搜索