您好,登錄后才能下訂單哦!
這篇文章給大家介紹springMVC框架是什么樣的,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
SpringMVC
概念:SpringMVC是一種基于java的實(shí)現(xiàn)MVC設(shè)計(jì)模型的請(qǐng)求驅(qū)動(dòng)類型的輕量級(jí)web框架,屬于springFramework的后續(xù)產(chǎn)品,已經(jīng)融合在Spring Web Flow里面,Spring框架提供了構(gòu)建web應(yīng)用程序的全功能MVC模塊,使用Spring可插入的MVC框架,從而在使用Spring進(jìn)行WEB開(kāi)發(fā)時(shí),可以選擇使用Spring的SpringMVC框架或集成其他MVC框架。
它通過(guò)一套注解,讓一個(gè)簡(jiǎn)單的Java類成為處理請(qǐng)求的控制器,而無(wú)序?qū)崿F(xiàn)任何接口,同時(shí)它還支持RESTful編程風(fēng)格的請(qǐng)求。
入門(mén)代碼:
第一步:配置前端控制器,在web.xml中
<!--配置前端控制權(quán)--> <servlet> <servlet-name>dispatcherServlet</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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
2、創(chuàng)建控制類
@Controller public class HelloController { @RequestMapping(path = "/hello")//用于建立請(qǐng)求URL和處理請(qǐng)求方法之間的對(duì)應(yīng)關(guān)系 /* * 屬性;path/value ,映射路徑 * method,當(dāng)前方法可以接受怎么樣的請(qǐng)求方式 * params,用于請(qǐng)求參數(shù)的條件 * handers,發(fā)送的請(qǐng)求必須包含請(qǐng)求頭 * */ public String sayHello(){ System.out.println("hello StringMvc"); return "success"; } }
3、在資源文件夾下創(chuàng)建配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="lianbang.wu"></context:component-scan> <!--視圖解析器對(duì)象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--開(kāi)啟-springmvc框架注解支持 自動(dòng)配置處理器映射器和處理器適配器--> <mvc:annotation-driven /> <!--配置類型轉(zhuǎn)換器--> <bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters" > <set> <bean class="lianbang.wu.utils.StringToDateConverter"></bean> </set> </property> </bean> <!--前端控制權(quán)哪些靜態(tài)資源不攔截--> <mvc:resources mapping="/js/**" location="/js/**"/> </beans>
程序解析:
1、啟動(dòng)服務(wù)器,加載一些配置文件
2、發(fā)送請(qǐng)求,后臺(tái)處理請(qǐng)求
組件介紹:springmvc框架基于組件方式執(zhí)行流程
前端控制器:DispatcherServlet,它相當(dāng)于mvc中的c,由它調(diào)用其他組件處理用戶的請(qǐng)求,降低組件間的耦合性
處理器映射器:HandlerMapping,負(fù)責(zé)根據(jù)用戶請(qǐng)求找到handler(處理器)
處理器適配器:HandlerAdapter,對(duì)處理器進(jìn)行執(zhí)行
處理器:Handler,它就是我們開(kāi)發(fā)中要編寫(xiě)的具體業(yè)務(wù)控制器
視圖解析器:ViewResolver,負(fù)責(zé)處理結(jié)果生成view視圖
請(qǐng)求參數(shù)綁定
入門(mén)代碼:
1、發(fā)送請(qǐng)求參數(shù)
<form action="/param/testParam" method="post"> 用戶名:<input type="text" name="username"/><br> </form>
2、請(qǐng)求參數(shù)綁定,自動(dòng)進(jìn)行同名參數(shù)的綁定
@Controller @RequestMapping("/param") public class ParamController { @RequestMapping("/testParam") public String testParam(String username){ System.out.println("執(zhí)行了。。。"+username); return "success"; } }
請(qǐng)求參數(shù)綁定實(shí)體類:
1、創(chuàng)建實(shí)體類
public class DemoClass implements Serializable { private String username; private String password; private Double money; //------省略get,set方法,自行添加 }
2、發(fā)送請(qǐng)求
<form action="/param/save" method="post"> 用戶名:<input type="text" name="username"/><br> 密碼:<input type="text" name="password"/><br> 金額:<input type="text" name="money"/><br> </form>
3、自動(dòng)進(jìn)行實(shí)體類型綁定
@Controller @RequestMapping("/param") public class ParamController { @RequestMapping("/save") public String save(DemoClass demoClass){ System.out.println(demoClass); return "success"; } }
注意:解決POST請(qǐng)求中文亂碼:添加過(guò)濾器,在web.xml中添加
<!--配置解決中文亂碼的過(guò)濾器--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <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>
請(qǐng)求參數(shù)綁定集合類型:
1、發(fā)送請(qǐng)求
</form> 用戶id:<input type="text" name="list[0].id"/><br> 用戶年齡:<input type="text" name="list[0].age"/><br> </form>
2、創(chuàng)建對(duì)應(yīng)的實(shí)體類
3、自動(dòng)進(jìn)行參數(shù)綁定
自定義內(nèi)容轉(zhuǎn)換器:解決數(shù)據(jù)內(nèi)容轉(zhuǎn)換異常問(wèn)題
第一步:定義一個(gè)類,實(shí)現(xiàn)Convrter接口,該接口有兩個(gè)泛型,分別表示接受的類型和目標(biāo)類型
//自定義類型轉(zhuǎn)換器 public class StringToDateConverter implements Converter <String , Date> { @Override public Date convert(String s) { if (s == null){ throw new RuntimeException("請(qǐng)傳入數(shù)據(jù)"); } DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = df.parse(s); return date; } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("數(shù)據(jù)類型轉(zhuǎn)換異常"); } } }
第二步:注冊(cè)類型轉(zhuǎn)換器
<!--開(kāi)啟-springmvc框架注解支持 自動(dòng)配置處理器映射器和處理器適配器--> <mvc:annotation-driven conversion-service="cs"/> <!--配置類型轉(zhuǎn)換器--> <bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters" > <set> <bean class="lianbang.wu.utils.StringToDateConverter"></bean> </set> </property> </bean>
獲取servlet原生API
//獲取原生API public String testServlet(HttpServletRequest request, HttpServletResponse response){ return "success"; }
常用注解:
@RequsetParams
作用:把請(qǐng)求中指定名稱的參數(shù)給控制器中的形參賦值。
屬性:value,請(qǐng)求參數(shù)中的名稱
required,請(qǐng)求參數(shù)重是否必須提供此參數(shù),默認(rèn)值:true,表示必須提供,如果不提供將報(bào)錯(cuò)。
//@RequestParam public String testRequestParam(@RequestParam(name = "name") String username){ return "success"; }
@RequsetBody
作用:用于獲取請(qǐng)求體內(nèi)容,直接使用得到是key=value&key=value···結(jié)構(gòu)的數(shù)據(jù),get請(qǐng)求不適用
屬性:required;是否必須有請(qǐng)求體,默認(rèn)值是true,當(dāng)取值為true時(shí),get請(qǐng)求方式會(huì)報(bào)錯(cuò),如果取值為false,get請(qǐng)求得到null。
//@RequestBody public String testRequestBody(@RequestBody String body){ System.out.println(body); return "success"; }
@PathVariable
作用:用于綁定url中的占位符的
屬性:value:指定url中的占位符名稱
Restful風(fēng)格的URL:
1、請(qǐng)求路徑一樣,可以根據(jù)不同的請(qǐng)求方式去執(zhí)行后臺(tái)的不同方法
2、restful風(fēng)格的URL優(yōu)點(diǎn):1、結(jié)構(gòu)清晰,2、符合標(biāo)準(zhǔn),3、易于理解,4、擴(kuò)展方便
//@PathVariable @RequestMapping("/testPathVariable/{uid}") public String testPathVariable(@PathVariable(name = "uid") String id){ System.out.println(id); return "success"; }
@HiddentHttpMethodFilter
作用;由于瀏覽器的form表單只支持GET和POST請(qǐng)求,而DELETE、PUT等method并不支持,spring3.0添加了一個(gè)過(guò)濾器,可以將瀏覽器請(qǐng)求改為指定的請(qǐng)求方式,發(fā)送給我們的控制器方法,使得支持GET,POST,PUT和DELETE
使用方法:
第一步:在web. xml中配置該過(guò)濾器
第二步:請(qǐng)求方式必須使用POST請(qǐng)求
第三步:按照要求提供_method請(qǐng)求參數(shù),該參數(shù)的取值就是我們需要的請(qǐng)求方式。
@RequestHeader
作用:用于獲取請(qǐng)求消息頭
屬性:value:提供消息頭名稱
required:是否必須有此消息頭
//@RequestHeader public String testRequestHeader(@RequestHeader(value = "Accept") String header){ System.out.println(header); return "success"; }
@CookieValue
作用:用于把指定cookie名稱的值傳入控制器方法參數(shù)
屬性:value:指定cookie的名稱
required:是否必須有此cookie
//@CookieValue public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookie){ System.out.println(cookie); return "success"; }
@ModelAttribute
作用:用于修飾方法和參數(shù),出現(xiàn)在方法上,表示當(dāng)前方法會(huì)在控制器的方法執(zhí)行之前,先執(zhí)行。它可以修飾沒(méi)有返回值的方法,也可以修飾有具體返回值的方法。出現(xiàn)在參數(shù)上,獲取指定的數(shù)據(jù)給參數(shù)賦值
屬性:value,用于獲取數(shù)據(jù)的key,key可以上POJO的屬性名稱,也可以上map結(jié)構(gòu)的key
應(yīng)用場(chǎng)景:當(dāng)表當(dāng)提交數(shù)據(jù)不是完整的實(shí)體類數(shù)據(jù)時(shí),保證沒(méi)有提交數(shù)據(jù)的字段使用數(shù)據(jù)庫(kù)對(duì)象原來(lái)的數(shù)據(jù)。
//@ModelAttribute @ModelAttribute public void MyShow(){ System.out.println("MyShow執(zhí)行了"); }
@SessionAttribute
作用:用于多次執(zhí)行控制器方法間的參數(shù)共享
屬性:value:用于指定存入的屬性名稱
type:用于指定存入的數(shù)據(jù)類型
作用于類上。
Springmvc的響應(yīng)數(shù)據(jù)和結(jié)果視圖
響應(yīng)返回值是String類型:
//返回值為String @RequestMapping("/testString") public String testString(Model model){ System.out.println("testString執(zhí)行了"); return "success"; }
響應(yīng)返回值是void類型:
//返回值為void public void testvoid(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException { System.out.println("testvoid方法執(zhí)行"); request.getRequestDispatcher("/WEB-INF/Pages/success.jsp").forward(request,response);//請(qǐng)求轉(zhuǎn)發(fā) response.sendRedirect(request.getContextPath()+"/success.jsp");//重定向 //直接響應(yīng) response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.getWriter().print("hello"); }
文件上傳
傳統(tǒng)方式代碼:
<h4>文件上傳:傳統(tǒng)方式</h4> <form action="/user/fileupload1" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/> <input type="submit" value="上傳"/> </form>
@RequestMapping("/fileupload1") public String fileUpLoad(HttpServletRequest request) throws Exception { System.out.println("文件上傳"); //使用fileupload組件 String realPath = request.getSession().getServletContext().getRealPath("/uploads"); File file = new File(realPath); if (!(file.exists())){ file.mkdirs(); } //解析request對(duì)象,獲取上傳文件想 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems = upload.parseRequest(request); for (FileItem item : fileItems){ //進(jìn)行判斷,當(dāng)前item對(duì)象是否是上傳文件 if (item.isFormField()){ //普通表單項(xiàng) }else { //上傳文件項(xiàng) String filename = item.getName(); String uuid = UUID.randomUUID().toString().replace("-"," "); filename=uuid+"_"+filename; item.write(new File(realPath,filename)); item.delete(); } } return "success"; }
springMVC方式代碼:
<h4>文件上傳:springmvc</h4> <form action="/user/fileupload2" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/> <input type="submit" value="上傳"/> </form>
@RequestMapping("/fileupload2") public String fileUpLoad2(HttpServletRequest request,MultipartFile upload) throws IOException { System.out.println("springmvc文件上傳"); String path = request.getSession().getServletContext().getRealPath("/uploads/"); File file = new File(path); if (!file.exists()){ file.mkdirs(); } String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-"," "); filename = uuid+"_"+filename; upload.transferTo(new File(path,filename)); return "success"; }
跨服務(wù)方式代碼:
<h4>文件上傳:跨服務(wù)器</h4> <form action="/user/fileupload3" method="post" enctype="multipart/form-data"> 選擇文件:<input type="file" name="upload"/><br/> <input type="submit" value="上傳"/> </form>
@RequestMapping("/fileupload3") public String fileUpLoad3(MultipartFile upload) throws IOException { System.out.println("跨服務(wù)器文件上傳"); //定義上傳文件的服務(wù)器路徑 String path = "http://localhost:9090/uploads/"; String filename = upload.getOriginalFilename(); String uuid = UUID.randomUUID().toString().replace("-"," "); filename = uuid+"_"+filename; //創(chuàng)建客戶端對(duì)象 Client client = Client.create(); //和圖片服務(wù)器進(jìn)行連接 WebResource resource = client.resource(path + filename); // 上傳文件 resource.put(upload.getBytes()); return "success"; }
在實(shí)際開(kāi)發(fā)中,我們會(huì)有很多處理不同功能的服務(wù)器,例如:
應(yīng)用服務(wù)器:負(fù)責(zé)部署我們的應(yīng)用
數(shù)據(jù)庫(kù)服務(wù)器:運(yùn)行我們的數(shù)據(jù)庫(kù)
緩存和消息服務(wù)器:負(fù)責(zé)處理大并發(fā)訪問(wèn)的緩存和消息
文件服務(wù)器:負(fù)責(zé)存儲(chǔ)用戶上傳文件的服務(wù)器
SpringMVC的攔截器:類似于servlet的Filter
1、編寫(xiě)攔截器類
/* 自定義攔截器 */ public class MyInterceptor implements HandlerInterceptor { /** * 預(yù)處理,controller方法執(zhí)行前 * 如果return true 放行,執(zhí)行下一個(gè)攔截器,如果沒(méi)有,執(zhí)行controller中的方法 * 如果return false 不放行 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("MyInterceptor執(zhí)行了"); return true; } /** * 后處理方法 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 跳轉(zhuǎn)頁(yè)面后執(zhí)行 * * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2、配置攔截器
<!--配置攔截器--> <mvc:interceptors> <mvc:interceptor> <!--要攔截的具體方法--> <mvc:mapping path="/user/*"/> <!--不要攔截的方法--> <!--<mvc:exclude-mapping path=""/>--> <!--配置攔截器對(duì)象--> <bean class="lianbang.wu.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
SpringMVC的異常處理:
1、編寫(xiě)自定義異常類
public class SysException extends Exception { private String message; @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public SysException(String message) { this.message = message; } }
2、編寫(xiě)異常處理器
public class SysExceptionResolver implements HandlerExceptionResolver { /** * 處理異常的業(yè)務(wù) * @param httpServletRequest * @param httpServletResponse * @param o * @param e * @return */ @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { //獲取異常對(duì)象 SysException exception = null; if (e instanceof SysException){ exception= (SysException)e; }else { exception= new SysException("系統(tǒng)維護(hù)"); } ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",exception.getMessage()); mv.setViewName("error"); return mv; } }
3、配置異常處理器
<!--配置異常處理器--> <bean id="sysExceptionResolver" class="lianbang.wu.exception.SysExceptionResolver"></bean>
關(guān)于springMVC框架是什么樣的就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。