這篇文章給大家介紹springMVC框架是什么樣的,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

創(chuàng)新互聯(lián)專注于濟寧企業(yè)網(wǎng)站建設(shè),自適應網(wǎng)站建設(shè),成都做商城網(wǎng)站。濟寧網(wǎng)站建設(shè)公司,為濟寧等地區(qū)提供建站服務。全流程定制設(shè)計,專業(yè)設(shè)計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務
SpringMVC
概念:SpringMVC是一種基于java的實現(xiàn)MVC設(shè)計模型的請求驅(qū)動類型的輕量級web框架,屬于springFramework的后續(xù)產(chǎn)品,已經(jīng)融合在Spring Web Flow里面,Spring框架提供了構(gòu)建web應用程序的全功能MVC模塊,使用Spring可插入的MVC框架,從而在使用Spring進行WEB開發(fā)時,可以選擇使用Spring的SpringMVC框架或集成其他MVC框架。
它通過一套注解,讓一個簡單的Java類成為處理請求的控制器,而無序?qū)崿F(xiàn)任何接口,同時它還支持RESTful編程風格的請求。
入門代碼:
第一步:配置前端控制器,在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")//用于建立請求URL和處理請求方法之間的對應關(guān)系
/*
* 屬性;path/value ,映射路徑
* method,當前方法可以接受怎么樣的請求方式
* params,用于請求參數(shù)的條件
* handers,發(fā)送的請求必須包含請求頭
* */
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> <!--視圖解析器對象--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <!--開啟-springmvc框架注解支持 自動配置處理器映射器和處理器適配器--> <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、啟動服務器,加載一些配置文件
2、發(fā)送請求,后臺處理請求
組件介紹:springmvc框架基于組件方式執(zhí)行流程
前端控制器:DispatcherServlet,它相當于mvc中的c,由它調(diào)用其他組件處理用戶的請求,降低組件間的耦合性
處理器映射器:HandlerMapping,負責根據(jù)用戶請求找到handler(處理器)
處理器適配器:HandlerAdapter,對處理器進行執(zhí)行
處理器:Handler,它就是我們開發(fā)中要編寫的具體業(yè)務控制器
視圖解析器:ViewResolver,負責處理結(jié)果生成view視圖
請求參數(shù)綁定
入門代碼:
1、發(fā)送請求參數(shù)
<form action="/param/testParam" method="post"> 用戶名:<input type="text" name="username"/><br> </form>
2、請求參數(shù)綁定,自動進行同名參數(shù)的綁定
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/testParam")
public String testParam(String username){
System.out.println("執(zhí)行了。。。"+username);
return "success";
}
}請求參數(shù)綁定實體類:
1、創(chuàng)建實體類
public class DemoClass implements Serializable {
private String username;
private String password;
private Double money;
//------省略get,set方法,自行添加
}2、發(fā)送請求
<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、自動進行實體類型綁定
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/save")
public String save(DemoClass demoClass){
System.out.println(demoClass);
return "success";
}
}注意:解決POST請求中文亂碼:添加過濾器,在web.xml中添加
<!--配置解決中文亂碼的過濾器--> <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>
請求參數(shù)綁定集合類型:
1、發(fā)送請求
</form> 用戶id:<input type="text" name="list[0].id"/><br> 用戶年齡:<input type="text" name="list[0].age"/><br> </form>
2、創(chuàng)建對應的實體類
3、自動進行參數(shù)綁定
自定義內(nèi)容轉(zhuǎn)換器:解決數(shù)據(jù)內(nèi)容轉(zhuǎn)換異常問題
第一步:定義一個類,實現(xiàn)Convrter接口,該接口有兩個泛型,分別表示接受的類型和目標類型
//自定義類型轉(zhuǎn)換器
public class StringToDateConverter implements Converter <String , Date> {
@Override
public Date convert(String s) {
if (s == null){
throw new RuntimeException("請傳入數(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)換異常");
}
}
}第二步:注冊類型轉(zhuǎn)換器
<!--開啟-springmvc框架注解支持 自動配置處理器映射器和處理器適配器--> <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
作用:把請求中指定名稱的參數(shù)給控制器中的形參賦值。
屬性:value,請求參數(shù)中的名稱
required,請求參數(shù)重是否必須提供此參數(shù),默認值:true,表示必須提供,如果不提供將報錯。
//@RequestParam
public String testRequestParam(@RequestParam(name = "name") String username){
return "success";
}@RequsetBody
作用:用于獲取請求體內(nèi)容,直接使用得到是key=value&key=value···結(jié)構(gòu)的數(shù)據(jù),get請求不適用
屬性:required;是否必須有請求體,默認值是true,當取值為true時,get請求方式會報錯,如果取值為false,get請求得到null。
//@RequestBody
public String testRequestBody(@RequestBody String body){
System.out.println(body);
return "success";
}@PathVariable
作用:用于綁定url中的占位符的
屬性:value:指定url中的占位符名稱
Restful風格的URL:
1、請求路徑一樣,可以根據(jù)不同的請求方式去執(zhí)行后臺的不同方法
2、restful風格的URL優(yōu)點:1、結(jié)構(gòu)清晰,2、符合標準,3、易于理解,4、擴展方便
//@PathVariable
@RequestMapping("/testPathVariable/{uid}")
public String testPathVariable(@PathVariable(name = "uid") String id){
System.out.println(id);
return "success";
}@HiddentHttpMethodFilter
作用;由于瀏覽器的form表單只支持GET和POST請求,而DELETE、PUT等method并不支持,spring3.0添加了一個過濾器,可以將瀏覽器請求改為指定的請求方式,發(fā)送給我們的控制器方法,使得支持GET,POST,PUT和DELETE
使用方法:
第一步:在web. xml中配置該過濾器
第二步:請求方式必須使用POST請求
第三步:按照要求提供_method請求參數(shù),該參數(shù)的取值就是我們需要的請求方式。
@RequestHeader
作用:用于獲取請求消息頭
屬性: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)在方法上,表示當前方法會在控制器的方法執(zhí)行之前,先執(zhí)行。它可以修飾沒有返回值的方法,也可以修飾有具體返回值的方法。出現(xiàn)在參數(shù)上,獲取指定的數(shù)據(jù)給參數(shù)賦值
屬性:value,用于獲取數(shù)據(jù)的key,key可以上POJO的屬性名稱,也可以上map結(jié)構(gòu)的key
應用場景:當表當提交數(shù)據(jù)不是完整的實體類數(shù)據(jù)時,保證沒有提交數(shù)據(jù)的字段使用數(shù)據(jù)庫對象原來的數(shù)據(jù)。
//@ModelAttribute
@ModelAttribute
public void MyShow(){
System.out.println("MyShow執(zhí)行了");
}@SessionAttribute
作用:用于多次執(zhí)行控制器方法間的參數(shù)共享
屬性:value:用于指定存入的屬性名稱
type:用于指定存入的數(shù)據(jù)類型
作用于類上。
Springmvc的響應數(shù)據(jù)和結(jié)果視圖
響應返回值是String類型:
//返回值為String
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("testString執(zhí)行了");
return "success";
}響應返回值是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);//請求轉(zhuǎn)發(fā)
response.sendRedirect(request.getContextPath()+"/success.jsp");//重定向
//直接響應
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對象,獲取上傳文件想
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
for (FileItem item : fileItems){
//進行判斷,當前item對象是否是上傳文件
if (item.isFormField()){
//普通表單項
}else {
//上傳文件項
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";
}跨服務方式代碼:
<h4>文件上傳:跨服務器</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("跨服務器文件上傳");
//定義上傳文件的服務器路徑
String path = "http://localhost:9090/uploads/";
String filename = upload.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-"," ");
filename = uuid+"_"+filename;
//創(chuàng)建客戶端對象
Client client = Client.create();
//和圖片服務器進行連接
WebResource resource = client.resource(path + filename);
// 上傳文件
resource.put(upload.getBytes());
return "success";
}在實際開發(fā)中,我們會有很多處理不同功能的服務器,例如:
應用服務器:負責部署我們的應用
數(shù)據(jù)庫服務器:運行我們的數(shù)據(jù)庫
緩存和消息服務器:負責處理大并發(fā)訪問的緩存和消息
文件服務器:負責存儲用戶上傳文件的服務器
SpringMVC的攔截器:類似于servlet的Filter
1、編寫攔截器類
/*
自定義攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
/**
* 預處理,controller方法執(zhí)行前
* 如果return true 放行,執(zhí)行下一個攔截器,如果沒有,執(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)頁面后執(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=""/>--> <!--配置攔截器對象--> <bean class="lianbang.wu.interceptor.MyInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
SpringMVC的異常處理:
1、編寫自定義異常類
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、編寫異常處理器
public class SysExceptionResolver implements HandlerExceptionResolver {
/**
* 處理異常的業(yè)務
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//獲取異常對象
SysException exception = null;
if (e instanceof SysException){
exception= (SysException)e;
}else {
exception= new SysException("系統(tǒng)維護");
}
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)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
網(wǎng)站名稱:springMVC框架是什么樣的
標題路徑:http://www.chinadenli.net/article0/gpdcio.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、動態(tài)網(wǎng)站、定制網(wǎng)站、微信公眾號、網(wǎng)站維護、小程序開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)