springMVC3.0(文件上传,@RequestMapping加参数,@SessionAttributes,@ModelAttribute,转发,重定向,数值获取,传参,ajax,拦截器)
1.項目包結構如下:
2.?????? spring配置文件springMVC.xml修改如下:
| <?xml version="1.0" encoding="UTF-8"?> |
?
3.?????? spring配置文件beans.xml內容修改如下:
| <?xml version="1.0" encoding="UTF-8"?> |
?
4.?????? web.xml文件不變
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
?xmlns="http://java.sun.com/xml/ns/j2ee"
?xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
?xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
?http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
?
?<!-- 通過上下文參數指定spring配置文件的位置 -->
?<context-param>
??<param-name>contextConfigLocation</param-name>
??<param-value>classpath:beans.xml</param-value>
?</context-param>
?<listener>
??<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
?</listener>
?
?<servlet>
??<servlet-name>action</servlet-name>
??<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
??<init-param>
???<param-name>contextConfigLocation</param-name>
???<param-value>classpath:springMVC.xml</param-value>
??</init-param>
?</servlet>
?<servlet-mapping>
??<servlet-name>action</servlet-name>
??<url-pattern>/</url-pattern>
?</servlet-mapping>
? <welcome-file-list>
??? <welcome-file>index.jsp</welcome-file>
? </welcome-file-list>
</web-app>
5.?????? 類的代碼不變。
6.?????? 運行,測試。跟上一個項目保持一致。
Spring MVC 3.0 深入
核心原理
1.?????? 用戶發送請求給服務器。url:user.do
2.?????? 服務器收到請求。發現DispatchServlet可以處理。于是調用DispatchServlet。
3.?????? DispatchServlet內部,通過HandleMapping檢查這個url有沒有對應的Controller。如果有,則調用Controller。
4.??????Controller開始執行。
5.?????? Controller執行完畢后,如果返回字符串,則ViewResolver將字符串轉化成相應的視圖對象;如果返回ModelAndView對象,該對象本身就包含了視圖對象信息。
6.?????? DispatchServlet將執視圖對象中的數據,輸出給服務器。
7.?????? 服務器將數據輸出給客戶端。
spring3.0中相關jar包的含義
| org.springframework.aop-3.0.3.RELEASE.jar | spring的aop面向切面編程 |
| org.springframework.asm-3.0.3.RELEASE.jar | spring獨立的asm字節碼生成程序 |
| org.springframework.beans-3.0.3.RELEASE.jar | IOC的基礎實現 |
| org.springframework.context-3.0.3.RELEASE.jar | IOC基礎上的擴展服務 |
| org.springframework.core-3.0.3.RELEASE.jar | spring的核心包 |
| org.springframework.expression-3.0.3.RELEASE.jar | spring的表達式語言 |
| org.springframework.web-3.0.3.RELEASE.jar | web工具包 |
| org.springframework.web.servlet-3.0.3.RELEASE.jar | mvc工具包 |
?
?
@Controller控制器定義
和Struts1一樣,Spring的Controller是Singleton的。這就意味著會被多個請求線程共享。因此,我們將控制器設計成無狀態類。
?
在spring 3.0中,通過@controller標注即可將class定義為一個controller類。為使spring能找到定義為controller的bean,需要在spring-context配置文件中增加如下定義:
?
| <context:component-scan base-package="com.sxt.web"/> |
?
????????注:實際上,使用@component,也可以起到@Controller同樣的作用。
?
@RequestMapping
?
??? 在類前面定義,則將url和類綁定。
??????在方法前面定義,則將url和類的方法綁定,如下所示:
| package com.sxt.web; ? import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.sxt.service.UserService; ? @Controller @RequestMapping("/user.do") publicclass UserController?{ ? ??? @Resource ??? private UserServiceuserService; ??? ??? //http://localhost:8080/springmvc02/user.do?method=reg&uname=zzzz ??? @RequestMapping(params="method=reg") ??? public String reg(String uname) { ?????? System.out.println("HelloController.handleRequest()"); ?????? userService.add(uname); ?????? return"index"; ??? } ??? ??? public UserService getUserService() { ?????? returnuserService; ??? } ??? publicvoid setUserService(UserService userService) { ?????? this.userService = userService; ??? } ? ??? } |
?
@RequestParam
???????? 一般用于將指定的請求參數賦給方法中形參。示例代碼如下:
????????
| @RequestMapping(params="method=reg5") ??? public String reg5(@RequestParam("name")String uname,ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); ?????? System.out.println(uname); ??????? //通過ModelMap傳參 ??????? map.put("name", uname);????? ??????? return"index"; ??? } |
????????
???????? 這樣,就會將name參數的值付給uname。當然,如果請求參數名稱和形參名稱保持一致,則不需要這種寫法。
@SessionAttributes
??? 將ModelMap中指定的屬性放到session中。示例代碼如下:
???
| @Controller @RequestMapping("/user.do") @SessionAttributes({"u","a"})??//將ModelMap中屬性名字為u、a的再放入session中。這樣,request和session中都有了。 publicclass UserController?{ ??? @RequestMapping(params="method=reg4") ??? public String reg4(ModelMap map) {??? ??? System.out.println("HelloController.handleRequest()"); ?????? map.addAttribute("u","uuuu");?//將u放入request作用域中,這樣轉發頁面也可以取到這個數據。 ?????? return"index"; ??? } } |
| ? <body> ?? <h1>**********${requestScope.u.uname}</h1> ?? <h1>**********${sessionScope.u.uname}</h1> ? </body> |
???
??? 注:名字為”user”的屬性再結合使用注解@SessionAttributes可能會報錯。
?
@ModelAttribute
?????這個注解可以跟@SessionAttributes配合在一起用。可以將ModelMap中屬性的值通過該注解自動賦給指定變量。
??? 示例代碼如下:
| package com.sxt.web; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; @Controller @RequestMapping("/user.do") @SessionAttributes({"u","a"})? publicclass UserController?{ ??? ??? @RequestMapping(params="method=reg4") ??? public String reg4(ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); ?????? map.addAttribute("u","尚學堂高淇"); ?????? return"index"; ??? } ??? ??? @RequestMapping(params="method=reg5") public String reg5(@ModelAttribute("u")String uname?,ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); ?????? System.out.println(uname); ??? ??? return"index"; ??? } ??? } |
?
先調用reg4方法,再調用reg5方法。我們發現控制臺打印出來:尚學堂高淇
?
Controller類中方法參數的處理
?
Controller類中方法返回值的處理
1.?????? 返回string(建議)
a)???????? 根據返回值找對應的顯示頁面。路徑規則為:prefix前綴+返回值+suffix后綴組成
b)???????? 代碼如下:
| @RequestMapping(params="method=reg4") ??? public String reg4(ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); ?????? return"index"; ??? } |
| 前綴為:/WEB-INF/jsp/???后綴是:.jsp 在轉發到:/WEB-INF/jsp/index.jsp |
?
2.?????? 也可以返回ModelMap、ModelAndView、map、List、Set、Object、無返回值。一般建議返回字符串!
?
?
請求轉發和重定向
???????? 代碼示例:
????????
| package com.sxt.web; ? import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; ? @Controller @RequestMapping("/user.do") publicclass UserController?{ ??? ??? @RequestMapping(params="method=reg4") ??? public String reg4(ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); //???? return "forward:index.jsp"; //???? return "forward:user.do?method=reg5"; //轉發 //???? return "redirect:user.do?method=reg5";? //重定向 ?????? return"redirect:http://www.baidu.com";?//重定向 ??? } ??? ??? @RequestMapping(params="method=reg5") ??? public String reg5(String uname,ModelMap map) { ?????? System.out.println("HelloController.handleRequest()"); ?????? System.out.println(uname); ?????? return"index"; ??? } ??? } |
????????
???????? 訪問reg4方法,既可以看到效果。
?
?
?
獲得request對象、session對象
普通的Controller類,示例代碼如下:
| @Controller @RequestMapping("/user.do") publicclass UserController?{ ??? ??? @RequestMapping(params="method=reg2") ??? public String reg2(String uname,HttpServletRequest req,ModelMap map){ ?????? req.setAttribute("a","aa"); ?????? req.getSession().setAttribute("b","bb"); ?????? return"index"; ??? } } |
?
?
ModelMap
???????? 是map的實現,可以在其中存放屬性,作用域同request。下面這個示例,我們可以在modelMap中放入數據,然后在forward的頁面上顯示這些數據。通過el表達式、JSTL、java代碼均可。代碼如下:
????????
| package com.sxt.web; ? import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; ? @Controller @RequestMapping("/user.do") publicclass UserControllerextends MultiActionController?{ ??? ??? @RequestMapping(params="method=reg") ??? public String reg(String uname,ModelMap map){ ?????? map.put("a","aaa"); ?????? return"index"; ??? } } |
| <%@ page language="java"import="java.util.*"pageEncoding="utf-8"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ? <head></head> ? <body> ??? ?? <h1>${requestScope.a}</h1> ??? ?? <c:out value="${requestScope.a}"></c:out> ? </body> </html> |
?
ModelAndView模型視圖類
見名知意,從名字上我們可以知道ModelAndView中的Model代表模型,View代表視圖。即,這個類把要顯示的數據存儲到了Model屬性中,要跳轉的視圖信息存儲到了view屬性。我們看一下ModelAndView的部分源碼,即可知其中關系:
| publicclassModelAndView { ? ??? /** View instance or view name String */ ??? private Objectview; ? ??? /** Model Map */ ??? private ModelMapmodel; ? ??? /** ??? ?* Indicates whether or not this instance has been cleared with a call to{@link #clear()}. ??? ?*/ ??? privatebooleancleared =false; ? ? ??? /** ??? ?* Default constructor for bean-style usage: populating bean ??? ?* properties instead of passing in constructor arguments. ??? ?* @see #setView(View) ??? ?* @see #setViewName(String) ??? ?*/ ??? public ModelAndView() { ??? } ? ??? /** ??? ?* Convenient constructor when there is no model data to expose. ??? ?* Can also be used in conjunction with<code>addObject</code>. ??? ?* @param viewName name of the View to render, to be resolved ??? ?* by the DispatcherServlet's ViewResolver ??? ?* @see #addObject ??? ?*/ ??? public ModelAndView(String viewName) { ?????? this.view = viewName; ??? } ? ??? /** ??? ?* Convenient constructor when there is no model data to expose. ??? ?* Can also be used in conjunction with<code>addObject</code>. ??? ?* @param view View object to render ??? ?* @see #addObject ??? ?*/ ??? public ModelAndView(View view) { ?????? this.view = view; ??? } ? ??? /** ??? ?* Creates new ModelAndView given a view name and a model. ??? ?* @param viewName name of the View to render, to be resolved ??? ?* by the DispatcherServlet's ViewResolver ??? ?* @param model Map of model names (Strings) to model objects ??? ?* (Objects). Model entries may not be<code>null</code>, but the ??? ?* model Map may be <code>null</code> if there is no model data. ??? ?*/ ??? public ModelAndView(String viewName, Map<String, ?> model) { ?????? this.view = viewName; ?????? if (model !=null) { ?????????? getModelMap().addAllAttributes(model); ?????? } ??? } ? ??? /** ??? ?* Creates new ModelAndView given a View object and a model. ??? ?* <emphasis>Note: the supplied model data is copied into the internal ??? ?* storage of this class. You should not consider to modify the supplied ??? ?* Map after supplying it to this class</emphasis> ??? ?* @param view View object to render ??? ?* @param model Map of model names (Strings) to model objects ??? ?* (Objects). Model entries may not be<code>null</code>, but the ??? ?* model Map may be <code>null</code> if there is no model data. ??? ?*/ ??? public ModelAndView(View view, Map<String, ?> model) { ?????? this.view = view; ?????? if (model !=null) { ?????????? getModelMap().addAllAttributes(model); ?????? } ??? } ? ??? /** ??? ?* Convenient constructor to take a single model object. ??? ?* @param viewName name of the View to render, to be resolved ??? ?* by the DispatcherServlet's ViewResolver ??? ?* @param modelName name of the single entry in the model ??? ?* @param modelObject the single model object ??? ?*/ ??? public ModelAndView(String viewName, String modelName, Object modelObject) { ?????? this.view = viewName; ?????? addObject(modelName, modelObject); ??? } ? ??? /** ??? ?* Convenient constructor to take a single model object. ??? ?* @param view View object to render ??? ?* @param modelName name of the single entry in the model ??? ?* @param modelObject the single model object ??? ?*/ ??? public ModelAndView(View view, String modelName, Object modelObject) { ?????? this.view = view; ?????? addObject(modelName, modelObject); ??? } ? ? ??? /** ??? ?* Set a view name for this ModelAndView, to be resolved by the ??? ?* DispatcherServlet via a ViewResolver. Will override any ??? ?* pre-existing view name or View. ??? ?*/ ??? publicvoid setViewName(String viewName) { ?????? this.view = viewName; ??? } ? ??? /** ??? ?* Return the view name to be resolved by the DispatcherServlet ??? ?* via a ViewResolver, or <code>null</code> if we are using a View object. ??? ?*/ ??? public String getViewName() { ?????? return (this.viewinstanceof String ? (String) this.view :null); ??? } ? ??? /** ??? ?* Set a View object for this ModelAndView. Will override any ??? ?* pre-existing view name or View. ??? ?*/ ??? publicvoid setView(View view) { ?????? this.view = view; ??? } ? ??? /** ??? ?* Return the View object, or<code>null</code> if we are using a view name ??? ?* to be resolved by the DispatcherServlet via a ViewResolver. ??? ?*/ ??? public View getView() { ?????? return (this.viewinstanceof View ? (View) this.view :null); ??? } ? ??? /** ??? ?* Indicate whether or not this<code>ModelAndView</code> has a view, either ??? ?* as a view name or as a direct{@link View} instance. ??? ?*/ ??? publicboolean hasView() { ?????? return (this.view != null); ??? } ? ??? /** ??? ?* Return whether we use a view reference, i.e.<code>true</code> ??? ?* if the view has been specified via a name to be resolved by the ??? ?* DispatcherServlet via a ViewResolver. ??? ?*/ ??? publicboolean isReference() { ?????? return (this.viewinstanceof String); ??? } ? ??? /** ??? ?* Return the model map. May return<code>null</code>. ??? ?* Called by DispatcherServlet for evaluation of the model. ??? ?*/ ??? protected Map<String, Object> getModelInternal() { ?????? returnthis.model; ??? } ? ??? /** ??? ?* Return the underlying <code>ModelMap</code> instance (never<code>null</code>). ??? ?*/ ??? public ModelMap getModelMap() { ?????? if (this.model == null) { ?????????? this.model =new ModelMap(); ?????? } ?????? returnthis.model; ??? } ? ??? /** ??? ?* Return the model map. Never returns<code>null</code>. ??? ?* To be called by application code for modifying the model. ??? ?*/ ??? public Map<String, Object> getModel() { ?????? return getModelMap(); ??? } ? ? ??? /** ??? ?* Add an attribute to the model. ??? ?* @param attributeName name of the object to add to the model ??? ?* @param attributeValue object to add to the model (never<code>null</code>) ??? ?* @see ModelMap#addAttribute(String, Object) ??? ?* @see #getModelMap() ??? ?*/ ??? publicModelAndView addObject(String attributeName, Object attributeValue) { ?????? getModelMap().addAttribute(attributeName, attributeValue); ?????? returnthis; ??? } ? ??? /** ??? ?* Add an attribute to the model using parameter name generation. ??? ?* @param attributeValue the object to add to the model (never<code>null</code>) ??? ?* @see ModelMap#addAttribute(Object) ??? ?* @see #getModelMap() ??? ?*/ ??? publicModelAndView addObject(Object attributeValue) { ?????? getModelMap().addAttribute(attributeValue); ?????? returnthis; ??? } ? ??? /** ??? ?* Add all attributes contained in the provided Map to the model. ??? ?* @param modelMap a Map of attributeName-> attributeValue pairs ??? ?* @see ModelMap#addAllAttributes(Map) ??? ?* @see #getModelMap() ??? ?*/ ??? publicModelAndView addAllObjects(Map<String, ?> modelMap) { ?????? getModelMap().addAllAttributes(modelMap); ?????? returnthis; ??? } ? ? ??? /** ??? ?* Clear the state of this ModelAndView object. ??? ?* The object will be empty afterwards. ??? ?* <p>Can be used to suppress rendering of a given ModelAndView object ??? ?* in the <code>postHandle</code> method of a HandlerInterceptor. ??? ?* @see #isEmpty() ??? ?* @see HandlerInterceptor#postHandle ??? ?*/ ??? publicvoid clear() { ?????? this.view =null; ?????? this.model =null; ?????? this.cleared =true; ??? } ? ??? /** ??? ?* Return whether this ModelAndView object is empty, ??? ?* i.e. whether it does not hold any view and does not contain a model. ??? ?*/ ??? publicboolean isEmpty() { ?????? return (this.view == null && CollectionUtils.isEmpty(this.model)); ??? } ? ??? /** ??? ?* Return whether this ModelAndView object is empty as a result of a call to{@link #clear} ??? ?* i.e. whether it does not hold any view and does not contain a model. ??? ?* <p>Returns <code>false</code> if any additional state was added to the instance ??? ?* <strong>after</strong> the call to{@link #clear}. ??? ?* @see #clear() ??? ?*/ ??? publicboolean wasCleared() { ?????? return (this.cleared && isEmpty()); ??? } ? ? ??? /** ??? ?* Return diagnostic information about this model and view. ??? ?*/ ??? @Override ??? public String toString() { ??? ??? StringBuilder sb = new StringBuilder("ModelAndView: "); ?????? if (isReference()) { ?????????? sb.append("reference to view with name '").append(this.view).append("'"); ?????? } ?????? else { ?????????? sb.append("materialized View is [").append(this.view).append(']'); ?????? } ?????? sb.append("; model is ").append(this.model); ?????? return sb.toString(); ??? } } |
?
測試代碼如下:
| package com.sxt.web; ? import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; ? import com.sxt.po.User; ? @Controller @RequestMapping("/user.do") publicclass UserControllerextends MultiActionController?{ ??? ??? @RequestMapping(params="method=reg") ??? public ModelAndView reg(String uname){ ?????? ModelAndView mv = new ModelAndView(); ?????? mv.setViewName("index"); //???? mv.setView(new RedirectView("index")); ?????? ?????? User u = new User(); ?????? u.setUname("高淇"); ?????? mv.addObject(u);?? //查看源代碼,得知,直接放入對象。屬性名為”首字母小寫的類名”。一般建議手動增加屬性名稱。 ?????? mv.addObject("a","aaaa"); ?????? returnmv; ??? } ? } |
| <%@ page language="java"import="java.util.*"pageEncoding="gbk"%> <%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ? <head> ? </head> ? <body> ??? ?? <h1>${requestScope.a}</h1> ??? ?? <h1>${requestScope.user.uname}</h1> ? </body> </html> |
| 地址欄輸入:http://localhost:8080/springmvc03/user.do?method=reg 結果為: |
?
?
基于spring 3.0mvc 框架的文件上傳實現
1. spring使用了apache-commons下得上傳組件,因此,我們需要引入兩個jar包:
1.?????? apache-commons-fileupload.jar
2.?????? apache-commons-io.jar
?
2.? 在springmvc-servlet.xml配置文件中,增加CommonsMultipartResoler配置:
| <!--處理文件上傳 --> <beanid="multipartResolver"? ??? class="org.springframework.web.multipart.commons.CommonsMultipartResolver">? ??? <propertyname="defaultEncoding"value="gbk"/><!--默認編碼 (ISO-8859-1) -->? ??? <propertyname="maxInMemorySize"value="10240"/><!--最大內存大小 (10240)-->? ??? <propertyname="uploadTempDir"value="/upload/"/><!--上傳后的目錄名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE),這個程序中的WebRoot下要有upload和tmp包,否則會報錯 -->? ??? <propertyname="maxUploadSize"value="-1"/><!--最大文件大小,-1為無限止(-1) -->? </bean> |
?
3.? 建立upload.jsp頁面,內容如下:
????????
| <%@ page language="java"import="java.util.*"pageEncoding="gbk"%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ??? <head> ?????? <title>測試springmvc中上傳的實現</title> ??? </head> ??? <body> <formaction="upload.do"?method="post"enctype="multipart/form-data"> ?????????? <inputtype="text"name="name"/> ?????????? <inputtype="file"name="file"/> ?????????? <inputtype="submit"/> ?????? </form> ??? </body> </html> |
?
4. 建立控制器,代碼如下:
????????
| package com.sxt.web; ? import java.io.File; import java.util.Date; ? import javax.servlet.ServletContext; ? import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.context.ServletContextAware; import org.springframework.web.multipart.commons.CommonsMultipartFile; ? @Controller public class FileUploadController implements ServletContextAware { ? ???????? private ServletContext servletContext; ???????? ???????? @Override ???????? public void setServletContext(ServletContext context) { ?????????????????? this.servletContext? = context; ???????? } ???????? ???????? @RequestMapping(value="/upload.do", method = RequestMethod.POST) ???????? public String handleUploadData(String name,@RequestParam("file")[微軟用戶2]?CommonsMultipartFile file){ ?????????????????? if (!file.isEmpty()) { ??????????????????????????? ?? String path = this.servletContext.getRealPath("/tmp/");? //獲取本地存儲路徑 ??????????????????????????? ?? System.out.println(path); ??????????????????????????? ?? String fileName = file.getOriginalFilename(); ??????????????????????????? ?? String fileType = fileName.substring(fileName.lastIndexOf(".")); ??????????????????????????? ?? System.out.println(fileType); ??????????????????????????? ?? File file2 = new File(path,new Date().getTime() + fileType); //新建一個文件 ??????????????????????????? ?? try { ???????????????????????????????????? ??? file.getFileItem().write(file2); //將上傳的文件寫入新建的文件中 ??????????????????????????? ? ?} catch (Exception e) { ???????????????????????????????????? ??? e.printStackTrace(); ??????????????????????????? ?? } ??????????????????????????? ?? return "redirect:upload_ok.jsp"; ??????????????????????????? }else{ ???????????????????????????????????? return "redirect:upload_error.jsp"; ??????????????????????????? } ???????? } } |
?
5. 建立upload_ok.jsp頁面
| <%@ page language="java"import="java.util.*"pageEncoding="gbk"%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ? <head> ? </head> ? <body> ??? ?? <h1>上傳成功!</h1> ? </body> </html> |
?
6. 建立upload_error.jsp頁面
| ? <%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%> <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ? <head> ? </head> ? <body> ??? ?? <h1>上傳失敗!</h1> ? </body> </html> |
?
7.?????? 發布項目,運行測試:http://localhost:8080/springmvc03/upload.jsp
?? 進入項目發布后的目錄,發現文件上傳成功:
?
處理ajax請求
spring使用了jackson類庫,幫助我們在java對象和json、xml數據之間的互相轉換。他可以將控制器返回的對象直接轉換成json數據,供客戶端使用。客戶端也可以傳送json數據到服務器進行直接轉換。使用步驟如下:
?
1.? 項目中需要引入如下兩個jar包:
???????? ???????? jackson-core-asl-1.7.2jar
?????????????????? jackson-mapper-asl-1.7.2jar
2.? spring配置文件中修改:
| ???????????<mvc:annotation-driven/>?<!--支持spring3.0新的mvc注解 --> ??? <!--啟動Spring MVC的注解功能,完成請求和注解POJO的映射 --> ??? ? <beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">? ??????? <propertyname="cacheSeconds"value="0"/>? ??????? <propertyname="messageConverters">? ??????????? <list>? ??????????????? <beanclass="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>? ??????????? </list>? ??????? </property> ??? </bean>? |
?
3.?????? 客戶端代碼a.jsp如下:
| <%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> ? <!DOCTYPEHTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> ? <head> ??? <basehref="<%=basePath%>"> ??? ??? <title>My JSP 'index.jsp' starting page</title> ??? <metahttp-equiv="pragma"content="no-cache"> ??? <metahttp-equiv="cache-control"content="no-cache"> ??? <metahttp-equiv="expires"content="0">??? ??? <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> ??? <metahttp-equiv="description"content="This is my page"> ??? <script> ?????? function createAjaxObj(){ ?????????? var req; ?????????? if(window.XMLHttpRequest){ ????????????? req = new XMLHttpRequest(); ??? ?????? }else{ ????????????? req = new ActiveXObject("Msxml2.XMLHTTP");?//ie ?????????? } ?????????? return req; ?????? } ?????? ?????? function sendAjaxReq(){ ?????????? var req = createAjaxObj(); ?????????? req.open("get","myajax.do?method=test2&uname=張三"); ?????????? req.setRequestHeader("accept","application/json"); ?????? ??? req.onreadystatechange? =function(){ ????????????? eval("var result="+req.responseText); ????????????? document.getElementById("div1").innerHTML=result[0].uname; ?????????? } ?????????? req.send(null); ?????? } ??? </script> ? </head> ? ? <body> ??? <ahref="javascript:void(0);"onclick="sendAjaxReq();">測試</a> ??? <divid="div1"></div> ? </body> </html> ? |
?
4.?????? 服務器端代碼如下:
????????
| package com.sxt.web; ? import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; ? import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; ? import com.sxt.po.User; ? @Controller @RequestMapping("myajax.do") public class MyAjaxController { ???????? ???????? @RequestMapping(params="method=test1",method=RequestMethod.GET) ???????? public @ResponseBody List<User> test1(String uname) throws Exception{ ?????????????????? String uname2 = new String(uname.getBytes("iso8859-1"),"gbk"); ?????????????????? System.out.println(uname2); ?????????????????? System.out.println("MyAjaxController.test1()"); ?????????????????? List<User> list = new ArrayList<User>(); ?????????????????? list.add(new User("高淇","123")); ?????????????????? list.add(new User("馬士兵","456")); ?????????????????? ?????????????????? return list; ???????? } ???????? } |
?
?
5.?????? 測試。
a)???????? 啟動服務器。輸入:http://localhost:8080/springmvc03/a.jsp
?
Spring中的攔截器
定義spring攔截器兩種基本方式
1.?????? 實現接口:org.springframework.web.servlet.HandlerInterceptor。
接口中有如下方法需要重寫:
注意:參數中的Object handler是下一個攔截器。
a)???????? publicboolean preHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler) throws Exception
該方法在action執行前執行,可以實現對數據的預處理,比如:編碼、安全控制等。
如果方法返回true,則繼續執行action。
b)???????? publicvoid postHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler,?? ModelAndView modelAndView) throws Exception
該方法在action執行后,生成視圖前執行。在這里,我們有機會修改視圖層數據。
c)???????? publicvoid afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)?? throws Exception
最后執行,通常用于釋放資源,處理異常。我們可以根據ex是否為空,來進行相關的異常處理。因為我們在平時處理異常時,都是從底層向上拋出異常,最后到了spring框架從而到了這個方法中。
2.?????? 繼承適配器:
org.springframework.web.servlet.handler.HandlerInterceptorAdapter
這個適配器實現了HandlerInterceptor接口。提供了這個接口中所有方法的空實現。
?
如下我們寫出兩個攔截器的示例代碼,僅供大家參考:
| package com.sxt.interceptor; ? importjavax.interceptor.Interceptors; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; ? import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; ? ? publicclass MyInterceptorimplements HandlerInterceptor { ? ??? @Override ??? publicvoid afterCompletion(HttpServletRequest request,???HttpServletResponse response, Object handler, Exception ex)??? throws Exception { ?????? System.out.println("最后執行!!!一般用于釋放資源!!"); ?????? ??? } ? ??? @Override ??? publicvoid postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,???ModelAndView modelAndView) throws Exception { ?????? System.out.println("Action執行之后,生成視圖之前執行!!"); ??? } ? ??? @Override ??? publicboolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception { ?????? System.out.println("action之前執行!!!"); ?????? returntrue;?//繼續執行action ??? } ? } ? |
| package com.sxt.interceptor; ? import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; ? import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; ? ? publicclass MyInterceptor2extends HandlerInterceptorAdapter { ? ??? @Override ??? publicboolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)throws Exception { ?????? System.out.println("MyInterceptor2.preHandle()"); ?????? returntrue;?//繼續執行action ??? } } |
?
3.?????? XML中如何配置。如下為示例代碼:
| ???<mvc:interceptors> ?????? <beanclass="com.sxt.interceptor.MyInterceptor"></bean><!--攔截所有springmvc的url! --> ?????? <mvc:interceptor> ?????????? <mvc:mappingpath="/user.do"/> ?????????? <!--<mvc:mapping path="/test/*" />--> ?????????? <beanclass="com.sxt.interceptor.MyInterceptor2"></bean> ?????? </mvc:interceptor> ??? </mvc:interceptors> |
?
總結
以上是生活随笔為你收集整理的springMVC3.0(文件上传,@RequestMapping加参数,@SessionAttributes,@ModelAttribute,转发,重定向,数值获取,传参,ajax,拦截器)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于注解的Spring MVC整合Hib
- 下一篇: s3c2440移植MQTT