這篇文章給大家介紹springMVC框架是什么樣的,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
SpringMVC
概念:SpringMVC是一種基于java的實現MVC設計模型的請求驅動類型的輕量級web框架,屬于springFramework的后續產品,已經融合在Spring Web Flow里面,Spring框架提供了構建web應用程序的全功能MVC模塊,使用Spring可插入的MVC框架,從而在使用Spring進行WEB開發時,可以選擇使用Spring的SpringMVC框架或集成其他MVC框架。
它通過一套注解,讓一個簡單的Java類成為處理請求的控制器,而無序實現任何接口,同時它還支持RESTful編程風格的請求。
入門代碼:
第一步:配置前端控制器,在web.xml中
<!--配置前端控制權--> <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、創建控制類
@Controller
public class HelloController {
@RequestMapping(path = "/hello")//用于建立請求URL和處理請求方法之間的對應關系
/*
* 屬性;path/value ,映射路徑
* method,當前方法可以接受怎么樣的請求方式
* params,用于請求參數的條件
* handers,發送的請求必須包含請求頭
* */
public String sayHello(){
System.out.println("hello StringMvc");
return "success";
}
}3、在資源文件夾下創建配置文件
<?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 /> <!--配置類型轉換器--> <bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters" > <set> <bean class="lianbang.wu.utils.StringToDateConverter"></bean> </set> </property> </bean> <!--前端控制權哪些靜態資源不攔截--> <mvc:resources mapping="/js/**" location="/js/**"/> </beans>
程序解析:
1、啟動服務器,加載一些配置文件
2、發送請求,后臺處理請求
組件介紹:springmvc框架基于組件方式執行流程
前端控制器:DispatcherServlet,它相當于mvc中的c,由它調用其他組件處理用戶的請求,降低組件間的耦合性
處理器映射器:HandlerMapping,負責根據用戶請求找到handler(處理器)
處理器適配器:HandlerAdapter,對處理器進行執行
處理器:Handler,它就是我們開發中要編寫的具體業務控制器
視圖解析器:ViewResolver,負責處理結果生成view視圖
請求參數綁定
入門代碼:
1、發送請求參數
<form action="/param/testParam" method="post"> 用戶名:<input type="text" name="username"/><br> </form>
2、請求參數綁定,自動進行同名參數的綁定
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/testParam")
public String testParam(String username){
System.out.println("執行了。。。"+username);
return "success";
}
}請求參數綁定實體類:
1、創建實體類
public class DemoClass implements Serializable {
private String username;
private String password;
private Double money;
//------省略get,set方法,自行添加
}2、發送請求
<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>
請求參數綁定集合類型:
1、發送請求
</form> 用戶id:<input type="text" name="list[0].id"/><br> 用戶年齡:<input type="text" name="list[0].age"/><br> </form>
2、創建對應的實體類
3、自動進行參數綁定
自定義內容轉換器:解決數據內容轉換異常問題
第一步:定義一個類,實現Convrter接口,該接口有兩個泛型,分別表示接受的類型和目標類型
//自定義類型轉換器
public class StringToDateConverter implements Converter <String , Date> {
@Override
public Date convert(String s) {
if (s == null){
throw new RuntimeException("請傳入數據");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = df.parse(s);
return date;
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException("數據類型轉換異常");
}
}
}第二步:注冊類型轉換器
<!--開啟-springmvc框架注解支持 自動配置處理器映射器和處理器適配器--> <mvc:annotation-driven conversion-service="cs"/> <!--配置類型轉換器--> <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
作用:把請求中指定名稱的參數給控制器中的形參賦值。
屬性:value,請求參數中的名稱
required,請求參數重是否必須提供此參數,默認值:true,表示必須提供,如果不提供將報錯。
//@RequestParam
public String testRequestParam(@RequestParam(name = "name") String username){
return "success";
}@RequsetBody
作用:用于獲取請求體內容,直接使用得到是key=value&key=value···結構的數據,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、請求路徑一樣,可以根據不同的請求方式去執行后臺的不同方法
2、restful風格的URL優點:1、結構清晰,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添加了一個過濾器,可以將瀏覽器請求改為指定的請求方式,發送給我們的控制器方法,使得支持GET,POST,PUT和DELETE
使用方法:
第一步:在web. xml中配置該過濾器
第二步:請求方式必須使用POST請求
第三步:按照要求提供_method請求參數,該參數的取值就是我們需要的請求方式。
@RequestHeader
作用:用于獲取請求消息頭
屬性:value:提供消息頭名稱
required:是否必須有此消息頭
//@RequestHeader
public String testRequestHeader(@RequestHeader(value = "Accept") String header){
System.out.println(header);
return "success";
}@CookieValue
作用:用于把指定cookie名稱的值傳入控制器方法參數
屬性:value:指定cookie的名稱
required:是否必須有此cookie
//@CookieValue
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookie){
System.out.println(cookie);
return "success";
}@ModelAttribute
作用:用于修飾方法和參數,出現在方法上,表示當前方法會在控制器的方法執行之前,先執行。它可以修飾沒有返回值的方法,也可以修飾有具體返回值的方法。出現在參數上,獲取指定的數據給參數賦值
屬性:value,用于獲取數據的key,key可以上POJO的屬性名稱,也可以上map結構的key
應用場景:當表當提交數據不是完整的實體類數據時,保證沒有提交數據的字段使用數據庫對象原來的數據。
//@ModelAttribute
@ModelAttribute
public void MyShow(){
System.out.println("MyShow執行了");
}@SessionAttribute
作用:用于多次執行控制器方法間的參數共享
屬性:value:用于指定存入的屬性名稱
type:用于指定存入的數據類型
作用于類上。
Springmvc的響應數據和結果視圖
響應返回值是String類型:
//返回值為String
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("testString執行了");
return "success";
}響應返回值是void類型:
//返回值為void
public void testvoid(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
System.out.println("testvoid方法執行");
request.getRequestDispatcher("/WEB-INF/Pages/success.jsp").forward(request,response);//請求轉發
response.sendRedirect(request.getContextPath()+"/success.jsp");//重定向
//直接響應
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print("hello");
}文件上傳
傳統方式代碼:
<h4>文件上傳:傳統方式</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;
//創建客戶端對象
Client client = Client.create();
//和圖片服務器進行連接
WebResource resource = client.resource(path + filename);
// 上傳文件
resource.put(upload.getBytes());
return "success";
}在實際開發中,我們會有很多處理不同功能的服務器,例如:
應用服務器:負責部署我們的應用
數據庫服務器:運行我們的數據庫
緩存和消息服務器:負責處理大并發訪問的緩存和消息
文件服務器:負責存儲用戶上傳文件的服務器
SpringMVC的攔截器:類似于servlet的Filter
1、編寫攔截器類
/*
自定義攔截器
*/
public class MyInterceptor implements HandlerInterceptor {
/**
* 預處理,controller方法執行前
* 如果return true 放行,執行下一個攔截器,如果沒有,執行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執行了");
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 {
}
/**
* 跳轉頁面后執行
*
* @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 {
/**
* 處理異常的業務
* @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("系統維護");
}
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg",exception.getMessage());
mv.setViewName("error");
return mv;
}
}3、配置異常處理器
<!--配置異常處理器--> <bean id="sysExceptionResolver" class="lianbang.wu.exception.SysExceptionResolver"></bean>
關于springMVC框架是什么樣的就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。