Spring+SpringMVC常見注解及作用和配置文件的一些常見配置


Spring常用注解以及作用:

 1.@Component在類定義之前添加@Component注解,它會被SpringIoC容器識別,並轉為bean。
 2.@Repository對Dao實現類進行注解(特殊的@Component)。
 3.@Service用於對業務邏輯層進行注解(特殊的@Component)。
 4.@Controller用於控制層注解(特殊的@Component)。
 5.@RequestMapping:用於處理請求地址映射,可以作用於類和方法上。
       其屬性有:value:定義request請求的映射地址
                 method:定義request地址的請求方式(GET/POST/HEAD/PUT/DELETE/OPTIONS/PATCH)
                 param:定義request請求中必須包含的參數值,一般作用於表單。
                 headers:定義request請求中必須包含某些指定的請求頭,如text/html、text/plain等
                 consumes:定義請求提交內容的類型
                 produces:指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回
 6.@RequestParam:用於獲取前台參數,一般作用於表單。
       其屬性有:value:參數的名稱
                 required:定義傳入的該參數是否為必須,默認為true
 7.@RequestBody:用於獲取前台參數,一般作用於ajax、json。
 8.@PathVariable:用於接收瀏覽器地址中QueryString的參數。
       其屬性有:value:參數的名稱
                 required:輕易傳入參數是否為必須
 9.@ResponseBody:作用於方法上,將整個返回結果以某種格式返回,如json或xml。
 10.@CookieValue:用於獲取請求的Cookie值。
 11.@ModelAttribute:用於把參數保存到model中,可以注解方法或參數,注解在方法上的時候,該方法將在
                     處理器方法執行之前執行,然后把返回的對象存放在session(前提是要有@SessionAttributes注解)或模型屬性,
                     注解在標注方法的時候指定,如果沒有指定,則使用返回類型的類名稱作為屬性名稱。
 12.@SessionAttributes:用於使得模型中的數據存儲一份到session域中,配合@ModelAttribute使用的時候,
                        會將對應的名稱的model值存到session中。
 13.@Autowired:自動注入,如果按照byName來裝配,可以結合@Qualifier注解一起使用。
 14.@Resource:此注解和自動注入注解都是做bean的注入時使用。
 15.@RestController:使得當前的Controller層返回的全部都是Json類型的數據。
 16.@Transactional:將類中的方法變為事務。
        其屬性有:readOnly=false,意思為不為只讀,可以進行增刪改查
                   propagation=Propagation.REQUIRED,傳播行為
 17.@bean:等同於在spring配置文件中配置的bean....。
 18.@Configuration:用於定義配置類,可替換xml配置文件。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

關於Spring配置文件的一些常見應用:

1.自動裝配:
在這里插入圖片描述
聲明默認自動裝配的方式。

2.掃描器:
在這里插入圖片描述
掃描器通過包名進行掃描,進行匹配,然后放入IOC容器中。

3.聲明事務:
<tx:annotation-driven transaction-manager="transactionManager"/>
增加事務的命名空間,增加對事務的支持。
transaction為屬性(事務管理器)

4.配置事務管理器:

id值需要和事務的命名空間的transaction-manager的屬性值一致。

5.配置數據源:

事務管理器依賴於數據源,需要寫在事務管理器的配置里。

6.數據源的具體配置:
在這里插入圖片描述
需要寫在事務管理器的外面。

7. web.xml處理中文亂碼問題:
在這里插入圖片描述

8.監聽器監聽Tomcat,通過監聽器讓SpringIoCIoC容器初始化一次(只new一個對象):
在這里插入圖片描述

9.SpringMVC方式處理請求的入口:
在這里插入圖片描述
10.配置視圖解析器:
在這里插入圖片描述

11.@RequestMapping注解的value屬性的ant風格的請求路徑:
abc/*/c 意思是:abc里的任意中的c。
通配符:代表着在的前后中間,可以有多個子目錄

  • 代表通配符:任意,不限
    ? 代表任意一個單字符
  • 代表任意字符(0或多個)
    ** 代表任意個目錄

12.SpringMVC的REST風格(軟件編程風格):
四個常見請求方式:
GET 獲取 --》查詢
POST 增 --》增加
DELETE 刪 --》刪除
PUT 改 --》更新
一般普通瀏覽器只支持get和post,不支持delete和put。
若想要瀏覽器支持delte和put方式,可以使用filte過濾器,使用過濾器進行攔截並進行處理。

實現過程:

約定1:過濾器對請求進行攔截,
攔截隱藏域hidden,隱藏域的name字段的值必須是_method,
如果滿足這兩個條件,就對請求進行攔截,
攔截什么?看value值,如果value的值為delete,
過濾器就將請求方式變為delete,
那么,如果value的值為put,
過濾器就將請求方式變為put。
約定2:請求方式之前是post,然后加隱藏域和指定的value值。
delete:
put:

在web.xml中:
在這里插入圖片描述

注意:mvc所有請求為 /,過濾器的所有請求為 /*。

13.向頁面中帶數據的四種方式(放入request域):
1.ModelAndView
2.Model
3.ModelMap
4.Map

例(ModelAndView方式):

@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView(“success”); //加view
//告訴程序success就是view中的頁面,也需要在視圖解析器中配置前綴和后綴
Student student = new Student();
student.setId(2);
student.setName(“zs”); //addObject方法將數據放入request作用域中
modelAndView.addObject(“student1”,student); = request.setAttribute(“student”,student); //加model
return modelAndView;
}
}

例(Model方式):

@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(value=“testModel”)
public String testModel(Model model){
Student student = new Student();
student.setId(2);
student.setName(“zs”);
model.addAttribute(“student4”,student);
return “success”;
}
}

例(ModelMap方式):

@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(value=“testModelMap”)
public String testModelMap(ModelMap modelMap){
Student student = new Student();
student.setId(2);
student.setName(“zs”);
modelMap.put(“student2”,student);
return “success”;

    }

}
  • 1
  • 2
  • 3

例(Map方式):

@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(value=“testMap”)
public String testMap(Map<String,Object> map){
Student student = new Student();
student.setId(2);
student.setName(“zs”);
map.put(“student3”,student);
return “success”;

    }

}
  • 1
  • 2
  • 3

14.向頁面中帶數據的方式(放入session域):

例(@SessionAttributes方式):

寫@SessionAttributes(“student1”,可以放入多個) //數據本身放入了request里,這樣寫的話,就代表數據也放入了session里
或@SessionAttributes("types=Student.class) //將Student類型的數據全放入session中,是一個數組類型,可以這樣寫types={Student.class;Address.class}
@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(value=“testModel”)
public String testModel(Model model){
Student student = new Student();
student.setId(2);
student.setName(“zs”);
model.addAttribute(“student1”,student);
return “success”;
}
}

例(@ModelAttribute方式–經常在更新時使用):

發出更新請求,做一個更新修改,將zs改為ls。

 <form action="SpringMVC/testModelAttribute" method="post">
 id:<input type="text" name="id" />
 name:<input type="text" name="name" />
   <input type="submit" value="修改">
 </form>
  • 1
  • 2
  • 3
  • 4
  • 5

@SessionAttributes(“student”)
@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl {
@RequestMapping(value = “testModelAttribute”,method = RequestMethod.POST)
public String testModel(Model model){
Student student = new Student();
student.setName(“ls”);
model.addAttribute(“student”,student);
return “success”;
}
}

15.視圖解析器:InternalResourceViewResolver

   <mvc:view-controller path="請求路徑" view-name="視圖頁面" />
  • 1

注:springmvc的mvc:view-controller…標簽的優先級比較高,如果在springmvc.xml進行了配置,
就不會去Controller中找@RequestMapping()

經過視圖解析器處理,類中返回的jsp頁面地址,默認請求方式為請求轉發,可以指定。

return “forward:/view/success.jsp”; //請求轉發
return “redirect:/view/success.jsp”; //請求重定向

此種方式不會被視圖解析器加上前綴(/view/)和后綴(.jsp),所以,需要寫上路徑。

16.處理靜態資源:

何為靜態資源?
html css js 圖片 視頻。。。
也就是不會因為時間、地點等而產生變化,不與用戶進行交互。

在springMvc中,如果直接訪問靜態資源,就會404找不到。

原因:之前將所有的請求,通過通配符"/"進行攔截所有請求,
進而交給SpringMvc的入口DispatcherServlet去處理,
找該請求映射對應的@RequestMapping,也可以是mvc:view-controller…

解決方案:
在這里插入圖片描述
如果只加第一個配置,程序就只能訪問靜態資源,不能訪問動態資源了。
如果第一個和第二個配置都加了,程序就既可以訪問靜態資源又可以訪問動態資源。

17.類型轉換器:

自定義類型轉換器:

格式如下:

public class MyConverter implements Converter<S(原來需要轉換的,T(需要轉換成什么)>{
//該接口有泛型約束
@Override
public Object convert(Object source){

      //如果之前只實現接口,沒有進行泛型的約束,那么所實現的convert方法的類型就為Object,
        convert方法的參數也為Object類型。

      // //如果實現了接口並有泛型約束的話,所實現的convert方法的類型就為泛型約束的類型。
        return null;

           }

      }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

真實案例:將String轉為Model層的Student。

public class MyConverter implements Converter<String,Student>{

          @Override
     public Student convert(String source){
        String[] studentStrArr = source.split("-");
        Student student = new Student();
        student.setStudentId(Integer.parseInt(studentStrArr[0]));
    student.setStudentName(studentStrArr[1]);
        student.setStudentAge(Integer.parseInt(studentStrArr[2]));
        return student;
           }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在Springmvc.xml配置文件中進行配置:

1.將自定義轉換器納入springioc容器
在這里插入圖片描述

2.將myConverter再納入SpringMvc提供的轉換器bean中
在這里插入圖片描述

3.將conversionService注冊到annotation-driven中

在這里插入圖片描述

@Controller
@RequestMapping(value=“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(“testConverter”)
public String testConverter(@RequestParam(“studentInfo”) Student student){

   System.out.println(student.getId()+","+student.getName()+","+student.getAge());
  
   return "success";

   }
  • 1
  • 2
  • 3
  • 4
  • 5

}

 <form action="/SpringMVC/testConverter" method="post">
 學生信息:
<input name="studentInfo" type="text" /> //2-zs-23
                  <input type="submit" value="轉換" />
 </form>
  • 1
  • 2
  • 3
  • 4
  • 5

18.數據格式化:
FormattingConversionServiceFactoryBean 數據格式化的類 包括 ConversionServiceFactoryBean轉換器

19.錯誤消息的處理:

思路:把錯誤信息放入map中,也就是放入request域中,這樣就可以在前端頁面來取得錯誤信息了。

【SpringMvcControl】
@Controller
@RequestMapping(value=“SpringMVC”)
public class SpringMvcControl {
@RequestMapping(value = “testDataTimeFormat”,method = RequestMethod.POST)
public String testDataTimeFormat(Student student, BindingResult result, Map<String,Object> map){
System.out.println(student.getId()+","+student.getName()+","+student.getBirthday());
if(result.getErrorCount()>0){
for (FieldError error: result.getFieldErrors()) {
System.out.println(error.getDefaultMessage());
map.put(“errors”,result.getFieldErrors()); //將錯誤信息放入request域的errors中
}
}
return “redirect:/view/success.jsp”;
}
}

錯誤信息的處理:BindingResult必須要跟在校驗的student)后,不能夾雜任何的參數,是mvc的要求。

20.數據校驗:

@DateTimeFormat

1.JSR303方式

注解 注解的描述

@Null 被注解的元素必須為null
@NotNull 被注解的元素必須不為null
@AssertTrue 被注解的元素必須為true
@AssertFalse 被直接的元素必須為false
@Min(value) 被注解的元素必須是一個數字,其值必須大於或等於value
@Max(value) 被注解的元素必須是一個數字,其值必須小於或等於value
@DecimalMin(value) 被注解的元素必須是一個數字,其值必須大於或等於value
@DecimalMax(value) 被注解的元素必須是一個數字,其值必須小於或等於value
@Size(max,min) 被注解的元素的取值范圍必須是介於min和max之間
@Digits(integer,fraction)被注解的元素必須是一個數字,其值必須在可接受的范圍內
@Past 被注解的元素必須是一個過去的日期
@Future 被注解的元素必須是一個將來的日期
@Pattern(value) 被注解的元素必須符合指定的正則表達式

另外:
Hibernate Validator是JSR303的補充擴展

@Email 被注解的元素值必須是合法的電子郵箱地址
@Length 被注解的字符串的長度必須在指定的范圍內
@NotEmpty 被注解的字符串必須非空
@Range 被注解的元素必須在合適的范圍內

步驟:1.jar包的導入。
2.springmvc.xml中配置。
要實現JSR303 / Hibernate Validator校驗(或其它各種校驗),
必須實現SpringMvc提供的一個接口,ValidatorFactory。
SpringMvc已經把實現這個接口的實現類做過了,LocalValiDatorFactoryBean。
mvc:annotation-driven </mvc:annotation-driven>就會自動將ValidatorFactory的
實現類LocalValiDatorFactoryBean寫進去,因此可以直接實現數據校驗。
一句mvc:annotation-driven </mvc:annotation-driven>即可搞定。
3.直接使用注解。

21.SpringMVC處理Ajax或Json數據:

Ajax請求SpringMVC,並且返回Json格式的數據:

需要三個jar包:
jackson-annotations.jar
jackson-core.jar
jackson-databin.jar

JQuery形式的Ajax:

$(document.ready(function())){
$("#testJson").click(function(){
//通過ajax請求Springmvc
$.post(
//服務器地址
“SpringMVC/testJson”,
// {“name”:“zs”,“age”:23} 可以帶參數
//服務端處理完畢后的回調函數List
function(result){ //此時的result就是students
for(var i=0; i<result.length; i++){
window.alert(result[i].id+"-"+result[i].name+"-"
+result[i].age+"-")
}
});
});
)}
在這里插入圖片描述

@Controller
@ResponseBody //加完這個注解,在ajax里就可以調Json對象了,
//告訴SpringMvc此時的return 返回的不是一個字符串,不是像return "success"的一個view頁面,
//而是一個ajax調用的返回值,將返回的view頁面變成一個list數組
@RequestMapping(value=“SpringMVC”)
public class SpringMvcControl{
@RequestMapping("value=“testJson”)
public String testJson(){
//正規應該是Controller–>Service–>Dao,目前沒有這些,先模擬
Student stu1 = new Student(1,“zs”,20);
Student stu1 = new Student(2,“ls”,21);
Student stu1 = new Student(3,“ww”,22);

 List<Student> students = new ArrayList<>();
   student.add(stu1);
   student.add(stu2);
   student.add(stu3);
 
   return "students";

  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

private int id;
private String name;
private int age;

生成set get方法 和構造方法 和 無參構造

22.SpringMVC實現文件上傳:

  使用已經封裝好的組件來實現上傳步驟:

  1.1.jar包:commons-fileupload.jar和commons-io.jar

  2.配置CommonsMultipartResolver,加入到SpringIoC容器里

//CommonsMultipartResolver用於文件上傳
//id值不能亂寫,有固定寫法multipartResolver,SpringIOC容器在初始化時,會自動尋找一個id為multipartResolver的bean
    如果有,就自動加入IOC容器並生效,如果沒有,就不加入,不生效
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     //此類中有很多屬性,若類源代碼中沒有,就去父類或者所實現的接口中找
     //比如,可以設置文件上傳的默認編碼,上傳的最大值等等

   <property name="defaultEncoding" value="utf-8"> </property>   //設置屬性,文件上傳的默認編碼
   <property name="maxUploadSize" value="102400">  </property>   //設置屬性,文件上傳的最大值,單位為byte,若value為-1,就代表上傳文件的最大值沒有限制
   。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
</bean>

       3.處理的方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

@Controller
@RequestMapping(value=“SpringMVC”)
public class SpringMvcControl throws IOException{
@RequestMapping(value=“testUploadFile”,method=RequestMethod.POST)
//@RequestParam()指定表單中的某個name的值保存到desc屬性里,一般操作字符串使用@RequestParam()
public String testUploadFile(@RequestParam(“desc”)String desc,@RequestParam(“file”)MultipartFile file){ //通過參數來收上傳的字段
//將前端上傳的描述信息進行打印到控制台
System.out.println(“文件描述信息:”+desc); //file文件類型,要使用MultipartFile
//將file上傳到服務器的某一個地方
InputStream input = file.getInputStream(); //輸入流,不斷地往緩存區讀
String fileName = file.getOriginalFilename(); //獲取用戶上傳的原始名字
OutputStream out = new FileOutputStream(“d:\”+fileName); //輸出保存用戶上傳的原始文件名
byte[] bs = new byte[1024];
int len = -1;
while((len=input.read(bs) !=-1){
out.write(bs,0,len);
}
out.close();
input.close();
System.out.println(“上傳成功!”);
return “success”;
}
}

23.SpringMVC的攔截器:

實現攔截器的步驟:

編寫攔截器,實現接口HandlerInterceptor。

該接口中有三個方法:preHandle() 前,攔截請求。
postHandle() 后,攔截響應。
afterCompletion() 完畢,當服務器響應的頁面渲染完畢后就觸發afterCompletion()。
//渲染就是將jsp中的變量、css、js等全部組裝完畢,最終顯示出來:渲染。

public class MyInterceptor implements HandlerInterceptor{

  @Override
  public void preHandle(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView) throws Exception{
        System.out.println("攔截請求。");
  return true;  //若返回為true,表示攔截后要放行,若返回為false,表示攔截后不放行。
           }

  @Override
  public void postHandle(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView) throws Exception{
        System.out.println("攔截響應。");
           }

  @Override
  public void afterCompletion(HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView) throws Exception{
        System.out.println("視圖被渲染完畢。");
           }

}

 <mvc:interceptors>
   <bean class="com.zb.controller.MyInterceptor"> </bean>
</mvc:interceptors>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

@Controller
@RequestMapping(value=“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(value=“testInterceptor”)
public String testInterceptor(){
System.out.println(“普通處理請求的方法…”);
return “success”;
}
}

<mvc:interceptors>
//配置具體攔截的路徑
<mvc:interceptor>
//第一個是指定需要攔截的路徑,第二個是指定不攔截的路徑,二者取交集。風格為ant。
     <mvc:mapping path="/**" />                                 //攔截根目錄里的所有請求。
     <mvc:exclude-mapping path="SpringMVC/testUploadFile" />    //排除文件上傳的請求。
 <bean class="com.zb.controller.MyInterceptor"> </bean>
</mvc:interceptor>

</mvc:interceptors>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注意: 如果想要默認 攔截全部請求,就需要把
在這里插入圖片描述
但如果想要攔截指定的請求,就需要把
在這里插入圖片描述

如何做攔截器鏈(多個攔截器)?

先攔截第一個,然后再攔截第二個。

還是先做一個類,實現HandlerInterceptor接口。

然后在springmvc.xml中進行配置。

注意:多個攔截器的話,afterCompletion完畢后渲染只有一個。

24.SpringMVC處理異常:

要在SpringMVC中處理異常,必須實現HandlerExceptionResolver接口。
這個接口有一些實現類,每個實現類都是一種處理異常的方式。
實現類:

1.ExceptionHandleExceptionResolver

這個實現類提供了@ExceptionHandler注解,
並通過該注解處理異常。

@ExceptionHandler({ArithmeticException.class})
public ModelAndView handlerArithmeticException(Exception e){
ModelAndView modelAndView = new ModelAndView(“error”);
System.out.println(e);
modelAndView.addObject(“error”,e);
return modelAndView;

}
可以放入request域里,然后在Jsp頁面進行取得。
使用Model、Map、ModelAndView 都可以。

上面是做了一個Controller,在Controller中進行異常的捕捉和處理。

可以專門做一個處理異常的類。

@ControllerAdvice //與@Controller原理一致,被@Controller修飾的類,表明為一個控制器類。
//那么,被@ControllerAdvice修飾的類,就表明為一個處理異常捕獲異常的類。
public class MyExceptionHandler{ //用於處理異常的類

@ExceptionHandler({Exception.class})
public ModelAndView handlerArithmeticException(Exception e){
ModelAndView modelAndView = new ModelAndView(“error”);
System.out.println(e+"—該@ControllerAdvice中的異常處理方法,可以處理任何類中的異常");
modelAndView.addObject(“error”,e);
return modelAndView;

    }
  • 1

}

2.ResponseStatusExceptionResolver(異常狀態的提示)

比如,如果在瀏覽器的地址欄中隨便輸入一個asjkdkjsakdjas.jsp,
那么,在當前的項目中,必然是沒有這個頁面,所以瀏覽器會顯示
404 Not Found。。 找不到這個資源,
那么,是否可以自定義異常的顯示頁面?
就是通過ResponseStatusExceptionResolver來做,自定義異常顯示頁面。
同樣ResponseStatusExceptionResolver這個類,也提供了一個注解@ResponseStatus
那么,自定義異常顯示頁面就是通過@ResponseStatus 注解來實現的。

【MyMyArrayIndexOutofBoundsException】
//自定義一個數組越界異常
//用枚舉來實現:HttpStatus.NOT_FOUND就是404,HttpStatus.FPRNODDEM就是403
@ResponseStatus(value=HttpStatus.NOT_FOUND,reason=“對不起,數組越界了!”) //value就是瀏覽器顯示的類似於404,400的狀態碼,而reason就是瀏覽器顯示的類似於Not Found異常錯誤描述
public class MyArrayIndexOutofBoundsException extends Exception{ //變成自定義異常

}

【SpringMvcControl】
@Controller
@RequestMapping(“SpringMVC”)
public class SpringMvcControl{
@RequestMapping(“testExceptionHandler”)
public String testExceptionHandler(@RequestParam(“i”) Integer i) throws MyMyArrayIndexOutofBoundsException{
if(i==3){
throw new MyArrayIndexOutofBoundsException();
}
return “success”;
}
}

3.DefaultHandlerExceptionResolver(默認異常處理)

4.SimpleMappingExceptionResolver 通過配置來實現異常的處理

 

 

摘自 https://blog.csdn.net/zhang150114/article/details/88946850


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM