Spring MVC教程_第1頁(yè)
Spring MVC教程_第2頁(yè)
Spring MVC教程_第3頁(yè)
Spring MVC教程_第4頁(yè)
Spring MVC教程_第5頁(yè)
已閱讀5頁(yè),還剩18頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶(hù)提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、一、 開(kāi)發(fā)一個(gè)springMVC步驟1. 需要的jar包(在原來(lái)基礎(chǔ)上要加的)2. 添加配置文件springMVC.xml<?xml version="1.0" encoding="UTF-8"?><beans xmlns:xsi="/2001/XMLSchema-instance" xmlns="/schema/beans"xmlns:context="http:/www.springframew

2、/schema/context"xmlns:util="/schema/util"xmlns:mvct="/schema/mvc"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsdhttp:/www.springfra

3、/schema/context/schema/context/spring-context.xsd/schema/util/schema/util/spring-util.xsd/schema/mvc/schema/mvc/spring-mvc.xsd"></bean

4、s>3. 在web.xml配置DispacherServlet啟動(dòng)springMVC<servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!- spring的配置文

5、件 -> <param-value>classpath:springMVC.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>4.

6、寫(xiě)一個(gè)自己定制的controllerimport org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;public class FirstController implements Controller public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception System.out.println(&quo

7、t;-FirstController");ModelAndView mv=new ModelAndView("/WEB-INF/views/first.jsp");/轉(zhuǎn)到這個(gè)頁(yè)面return mv;5. 在springMVC.xml文件配置controller<bean name="/first" class="controller.FirstController"></bean></beans>6. 輸入網(wǎng)址為http:/localhost:8080/SpringMVCspringMVC

8、為工程名,會(huì)交給中央處理器DispacherServlet,在web.xml找到classpath下的文件,如springMVC.xml。輸入http:/localhost:8080/SpringMVC/first,會(huì)在springMVC下找到name為/first的bean,這個(gè)bean的class屬性,那個(gè)類(lèi)就是處理請(qǐng)求的。二、 一個(gè)controller寫(xiě)多個(gè)方法1. 繼承MultiActionController繼承之后,可以寫(xiě)多個(gè)返回值是ModelAndView的方法,第一個(gè)參數(shù)是HttpServletRequest,第二個(gè)參數(shù)是HttpServletResponse。public c

9、lass StudentController extends MultiActionController public ModelAndView add(HttpServletRequest request,HttpServletResponse response)System.out.println("->add");ModelAndView mv=new ModelAndView("/WEB-INF/views/ControllerTest.jsp");return mv;public ModelAndView edit(HttpServlet

10、Request request,HttpServletResponse response)System.out.println("->edit");ModelAndView mv=new ModelAndView("/WEB-INF/views/ControllerTest.jsp");return mv;2. 配置springMVC.xml配置文件添加bean配置方法參數(shù)的處理器<!- id可以隨意改變,class不能改 -> <bean id="methodNameResolver" class="

11、;org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"><!name不能修改,value可以修改 -> <property name="paramName" value="action"></property> <!- name不能改,value可以改,value為,打開(kāi)controller時(shí)候默認(rèn)調(diào)用的方法名 -> <property name="defaultMethodN

12、ame" value="view"></property> </bean> 在自己寫(xiě)的MultiActionController中引用方法參數(shù)處理器 <bean name="/student" class="controller.StudentController"> <!- name不能改,ref要和上面的id一樣 -> <property name="methodNameResolver" ref="methodNameResolv

13、er"></property> </bean>輸入http:/localhost:8080/SpringMVC/student,會(huì)打開(kāi)defaultMethodName對(duì)應(yīng)value的方法,如果要打開(kāi)StudentController控制器里面的add方法,可以輸入http:/localhost:8080/SpringMVC/student?action=add 這個(gè)action對(duì)應(yīng)methodNameResolver的paramName的值。三、 配置視圖處理器視圖處理器,可以在編程的時(shí)候,跳轉(zhuǎn)頁(yè)面時(shí),不用寫(xiě)前綴,如/WEB-INF/views,和后綴

14、,如.jsp。<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/views/"></property><!- 前綴 -> <property name="suffix" value=".jsp">

15、;</property><!- 后綴 -> </bean>這樣的話(huà)ModelAndView mv=new ModelAndView("ControllerTest");四、 給頁(yè)面?zhèn)鬟f信息用addObject(String,Object)方法,也可以用request.setAttribute()方法public ModelAndView test(HttpServletRequest request,HttpServletResponse response)System.out.println("->test")

16、;ModelAndView mv=new ModelAndView("TestModelView");/和request.setAttribute()傳的參數(shù)一樣mv.addObject("username", "tomcat");mv.addObject("interest", new String"籃球","足球");return mv;五、 使用注解1. 在springMVC.xml添加注解配置信息,聲明啟用MVC注解<bean class="org.s

17、pringframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean><bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>2. 用Controller和RequestMapping注解controller類(lèi),該類(lèi)不用繼承任何類(lèi)方法返回類(lèi)型是ModelAndView,可以不用傳參數(shù)Cont

18、rollerpublic class TestAnnotationController /聲明這是一個(gè)控制器方法,后面?zhèn)魅氲?,是一個(gè)urlRequestMapping("/annotation/test1")public ModelAndView test1()ModelAndView mv=new ModelAndView("testannotation");return mv;RequestMapping("/annotation/test2")public ModelAndView test2()ModelAndView mv=

19、new ModelAndView("testannotation");return mv;RequestMapping("/annotation/test3")public ModelAndView test3()ModelAndView mv=new ModelAndView("testannotation");return mv;3. 在springMVC.xml添加配置信息<!- 掃描base-package包下的所有類(lèi) -><context:component-scan base-package="

20、controller"></context:component-scan>六、 controller接收頁(yè)面信息1. 使用HttpServletRequest來(lái)接收和Servlet處理差不多public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception String username=request.getParameter("username");String password=request.getParam

21、eter("password");System.out.println("username->"+username);System.out.println("password->"+password);ModelAndView mv=new ModelAndView("testparameter");return mv;2. 使用分散的方法RequestMapping(value="/testparameter2/test2")public ModelAndView test2(St

22、ring username,String password)System.out.println("采用分散的方式");System.out.println("username->"+username);System.out.println("password->"+password);ModelAndView mv=new ModelAndView("testparameter");return mv;傳入來(lái)的參數(shù)變量名,必須要與html表單的name一模一樣。3. 使用合成的一個(gè)對(duì)象參數(shù)接收Requ

23、estMapping(value="/testparameter2/test3")public ModelAndView test3(User user)System.out.println("采用對(duì)象的方式");System.out.println("username->"+user.getUsername();System.out.println("password->"+user.getPassword();ModelAndView mv=new ModelAndView("testpa

24、rameter");return mv;User類(lèi)的屬性名必須與html表單的name一樣。4. 中文亂碼post解決方法可以寫(xiě)一個(gè)過(guò)濾器,進(jìn)行過(guò)濾,也可以也可以用spring提供的過(guò)濾器在web.xml添加以下配置<filter> <filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param

25、> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>5. 中文亂碼get解決方法如果你

26、是更改的tomcat安裝目錄的server.xml配置文件,那么在用eclipse運(yùn)行項(xiàng)目時(shí)會(huì)發(fā)現(xiàn)配置沒(méi)起作用,其實(shí)是因?yàn)閑clipse在運(yùn)行項(xiàng)目時(shí)是用的eclipse中配置的tomcat,打開(kāi)eclipse中的tomcat配置文件,server.xml在<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>更改為<Connector connectionTimeout=&

27、quot;20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>七、 靜態(tài)資源訪(fǎng)問(wèn)1. 靜態(tài)資源:js,css,image開(kāi)啟spring mvc之后,按照平常的方法,導(dǎo)入js,css,image資源,并不能正常運(yùn)行。因?yàn)樵谂渲脀eb.xml時(shí)候,配置了DispacherServlet,所以,所有請(qǐng)求都經(jīng)過(guò)DispacherServlet。DispacherServlet把那些請(qǐng)求過(guò)濾掉。2.

28、在spring.xml下配置靜態(tài)資源<!- 靜態(tài)資源處理 -><mvc:resources mapping="/images/*" location="/images/" ></mvc:resources><mvc:resources location="/js/" mapping="/js/*"></mvc:resources><mvc:resources location="/css/" mapping="/css/

29、*"></mvc:resources>mapping的意思是,請(qǐng)求地址,images下的所有子文件夾(第一個(gè)*號(hào))的所有文件(第二個(gè)*號(hào)),全部映射到物理地址image文件夾下。還有一種方法,就是<mvc:default-servlet-handler/>,可以代替上面三句。八、 PathVariable的使用1. 單參數(shù)<a href="<%=request.getContextPath()%>/testpathvariable/detail?id=3">通過(guò)參數(shù)傳遞id</a>參數(shù)傳遞,就是?后

30、面加個(gè)key=value。還有一種方法,就是用PathVariable注解,可以通過(guò)下面方式傳遞<a href="<%=request.getContextPath()%>/testpathvariable/detail/3">直接在路徑上傳遞id</a>是直接/后面加value。Controllerpublic class TestPathVariableController RequestMapping(value="/testpathvariable")public ModelAndView view()Mode

31、lAndView mv=new ModelAndView("TestPathVariable");return mv;RequestMapping(value="/testpathvariable/detail")public ModelAndView detail(Integer id)System.out.println("->"+id);ModelAndView mv=new ModelAndView("TestPathVariable");return mv;/PathVariable注解的參數(shù),名字

32、一定要和里面的一樣RequestMapping注解的value,后面 RequestMapping(value="/testpathvariable/detail/id")public ModelAndView detail2(PathVariable("id") Integer id)System.out.println("-fd->"+id);ModelAndView mv=new ModelAndView("TestPathVariable");return mv;還有一種,請(qǐng)求是偽html的方法Req

33、uestMapping(value="/testpathvariable/detail/id.html")public ModelAndView detail2(PathVariable("id") Integer id)System.out.println("-fd->"+id);ModelAndView mv=new ModelAndView("TestPathVariable");return mv;在后面加自己想加的內(nèi)容,在請(qǐng)求的時(shí)候就可以加自己的內(nèi)容,<a href="<%=r

34、equest.getContextPath()%>/testpathvariable/detail/3.html">2. 多個(gè)參數(shù)RequestMapping(value="/testpathvariable/detail/id/name")public ModelAndView detail3(PathVariable("id") Integer id,PathVariable("name") String name)System.out.println("-fd->"+id);Sys

35、tem.out.println("-"+name);ModelAndView mv=new ModelAndView("TestPathVariable");return mv;請(qǐng)求連接為<a href="<%=request.getContextPath()%>/testpathvariable/detail/3/tom">直接在路徑上傳遞id和name</a>九、 注解和Controller代碼的優(yōu)化1. springMVC.XML對(duì)注解配置的優(yōu)化要添加注解,則要在springMVC.XML下添

36、加兩句配置<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean><bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>通過(guò)優(yōu)化,可以把以上兩句簡(jiǎn)化為以下一句<mvc:annotation-driven><

37、/mvc:annotation-driven>2. controller代碼優(yōu)化,統(tǒng)一的RequestMapping在注解的時(shí)候,后面的url很多都相同,例如/annotation,很多重復(fù),如果要改,全部改,很麻煩RequestMapping(value="/annotation/test1")public ModelAndView test1()System.out.println("test1");ModelAndView mv=new ModelAndView("testannotation");return mv;Re

38、questMapping(value="/annotation/test2")public ModelAndView test2()System.out.println("test2");ModelAndView mv=new ModelAndView("testannotation");return mv;解決方法如下:ControllerRequestMapping("/annotation2")public class TestAnnotationController2 RequestMapping(&quo

39、t;/test1")public ModelAndView test1()System.out.println("test1");ModelAndView mv=new ModelAndView("testannotation");return mv;RequestMapping("/test2")public ModelAndView test2()System.out.println("test2");ModelAndView mv=new ModelAndView("testannotat

40、ion");return mv;3. Model和View的優(yōu)化RequestMapping("/test3")public String test3(Model model)System.out.println("test3");model.addAttribute("mm", "赫本");/return jsp的名字return "testannotation"十、 使用ResponseBody返回json數(shù)據(jù)1. 使用原始API HttpServletResponse返回Requ

41、estMapping("/test1")public void test1(HttpServletResponse response) throws IOExceptionresponse.setContentType("application/x-javascript;charset=utf-8");String json=""username":tomcat,"password":123456,"realname":小明"response.getWriter().prin

42、t(json);response.getWriter().flush();2. 使用ResponseBody注解返回字符串jsonRequestMapping("/test2")ResponseBodypublic String test2()String json=""username":tomcat,"password":123456,"realname":小明"return json;3. 使用ResponseBody注解返回對(duì)象RequestMapping("/test3&qu

43、ot;)ResponseBodypublic User test3()User u=new User();u.setUsername("tomcat");u.setPassword("123456");u.setRealname("哈哈");return u;4. 使用ResponseBody注解返回ListRequestMapping("/test4")ResponseBodypublic List<User> test4()List<User> users=new ArrayList&l

44、t;User>();for (int i = 0; i < 10; i+) User u=new User();u.setUsername("tomcat"+i);u.setPassword("123456"+i);u.setRealname("哈哈"+i);users.add(u);return users;5. 使用ResponseBody注解返回MapRequestMapping("/test5")ResponseBodypublic Map test5()Map m=new HashMap();

45、m.put("mm", "赫本");m.put("date", new Date();m.put("d", 22.3);List<User> users=new ArrayList<User>();for (int i = 0; i < 10; i+) User u=new User();u.setUsername("tomcat"+i);u.setPassword("123456"+i);u.setRealname("哈哈"

46、+i);users.add(u);m.put("users", users);return m;十一、 springMVC文件上傳1. 配置文件上傳處理器<!- 配置文件上傳處理器 -> <bean id="multipartResolver" class="mons.CommonsMultipartResolver"> <!- 默認(rèn)編碼 -> <property name="defaultEncoding" value="utf-8"></

47、property> <!- 上傳文件大小的最大值,單位為B -> <property name="maxUploadSize" value="100242880"></property> <!- 在內(nèi)存中的最大值,超過(guò)最大值,放在臨時(shí)文件夾 -> <property name="maxInMemorySize" value="40960"></property> </bean>2. 原始IO上傳方式Html的代碼<h1&

48、gt;演示采用spring提供的api保存</h1><!- 必須要用post的方式,enctype屬性一定要填 -><form action="<%=request.getContextPath()%>/testupload/upload2" method="post" enctype="multipart/form-data">選擇文件:<input type="file" name="upload"><br/><i

49、nput type="submit" value="上傳"></form>Controller代碼RequestMapping("/upload1")/傳入?yún)?shù)名"upload"已經(jīng)和html傳進(jìn)來(lái)的名字一樣,所以注解里面的"upload"可以刪除,如果傳入?yún)?shù)名不一樣,則注解參數(shù)名一定要和html傳入的一樣public String upload1(RequestParam("upload")CommonsMultipartFile upload,Http

50、Session session) throws IOException/獲得文件的原始文件名String originalFilename= upload.getOriginalFilename();String extendName=""/獲得文件前綴if(originalFilename.lastIndexOf(".")!=-1)extendName=originalFilename. substring(originalFilename.indexOf(".");String newFileName=System.current

51、TimeMillis()+extendName;/新生成的文件名,要唯一,不能有中文System.out.println(originalFilename+"->"+newFileName);String realPath=session.getServletContext().getRealPath("/upload");File saveDir=new File(realPath);if(!saveDir.exists()/如果文件不存在,就要?jiǎng)?chuàng)建出來(lái)saveDir.mkdirs();File saveFile=new File(saveDir

52、,newFileName);OutputStream out=new FileOutputStream(saveFile);/構(gòu)建目標(biāo)流InputStream in=upload.getInputStream();/得到上傳的文件流byte b=new byte1024;int len=-1;while(len=in.read(b)!=-1)out.write(b, 0, len);out.flush();out.close();in.close();return "TestUpload"上傳后的文件,放在D:workspace.metadata.pluginsorg.ec

53、lipse.wst.server.coretmp0wtpwebappsprojectnameuploadWorkspace為工作空間文件夾,projectname為工程名上傳文件之后,會(huì)請(qǐng)求轉(zhuǎn)發(fā),回到TestUpload.jsp,這樣刷新頁(yè)面,就會(huì)重復(fù)上文文件。所以要請(qǐng)求轉(zhuǎn)發(fā)才可以。一個(gè)錯(cuò)誤的方法就是return "redirect:TestUpload"這樣其實(shí)是訪(fǎng)問(wèn)/SpringMVC/WEB-INF/views/TestUpload.jsp。這個(gè)WEB-INF下的文件是不能直接訪(fǎng)問(wèn)的。所以,要訪(fǎng)問(wèn)view這個(gè)controller。return "redire

54、ct:/testupload"3. 采用spring提供的api保存RequestMapping("/upload2")public String upload2(RequestParam("upload")CommonsMultipartFile upload,HttpSession session) throws IllegalStateException, IOExceptionString originalFilename= upload.getOriginalFilename();/獲得文件的原始文件名String extendNam

55、e=""if(originalFilename.lastIndexOf(".")!=-1)/獲得文件前綴extendName=originalFilename. substring(originalFilename.indexOf(".");String newFileName=System.currentTimeMillis()+extendName;/新生成的文件名,要唯一,不能有中文System.out.println(originalFilename+"->"+newFileName);String

56、realPath=session.getServletContext().getRealPath("/upload");File saveDir=new File(realPath);if(!saveDir.exists()/如果文件不存在,就要?jiǎng)?chuàng)建出來(lái)saveDir.mkdirs();File saveFile=new File(saveDir,newFileName);upload.transferTo(saveFile);/將文件轉(zhuǎn)移到目標(biāo)位置上return "redirect:/testupload"4. 多文件上傳<h1>演示多文件

57、上傳</h1><form action="<%=request.getContextPath()%>/testupload/upload3" method="post" enctype="multipart/form-data">選擇文件:<input type="file" name="upload"><br/>選擇文件:<input type="file" name="upload"&g

58、t;<br/>選擇文件:<input type="file" name="file"><br/><input type="submit" value="上傳"></form>RequestMapping("/upload3")public String upload3(HttpServletRequest request) throws IllegalStateException, IOExceptionString realPath=

59、request.getSession().getServletContext().getRealPath("/upload");File saveDir=new File(realPath);if(!saveDir.exists()/如果文件不存在,就要?jiǎng)?chuàng)建出來(lái)saveDir.mkdirs();if(request instanceof MultipartHttpServletRequest)MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;List<Multip

60、artFile> uploads=multiRequest.getFiles("upload");for(MultipartFile mv:uploads)String originalFileName=mv.getOriginalFilename();String extendName=""if(originalFileName.indexOf(".")!=-1)extendName=originalFileName.substring( originalFileName.indexOf(".");Stri

61、ng newFileName=System.currentTimeMillis()+extendName;System.out.println(originalFileName+"->"+newFileName);File saveFile=new File(saveDir,newFileName);mv.transferTo(saveFile);MultipartFile file=multiRequest.getFile("file");String originalFileName=file.getOriginalFilename();Str

62、ing extendName=""if(originalFileName.indexOf(".")!=-1)extendName=originalFileName.substring( originalFileName.indexOf(".");String newFileName=System.currentTimeMillis()+extendName;System.out.println(originalFileName+"->"+newFileName);File saveFile=new File(saveDir,newFileName);file.transferTo(saveFile);return "redirect:/testupload"十二、 服務(wù)端數(shù)據(jù)校驗(yàn)1. 為什么要有服務(wù)端數(shù)據(jù)校驗(yàn)(1) 防止用戶(hù)禁用JavaScript(2) 防止用戶(hù)繞過(guò)瀏覽器,比如利用第三方組件HttpClient.jar2. 校驗(yàn)日期表單提交的日期,是字符串形式返回給服務(wù)器。而實(shí)體類(lèi)的日期屬性;類(lèi)型是util包下的Date類(lèi),所以可能會(huì)產(chǎn)生錯(cuò)誤,解決方法如

溫馨提示

  • 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶(hù)所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶(hù)上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶(hù)上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶(hù)因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

最新文檔

評(píng)論

0/150

提交評(píng)論