主頁 >  其他 > SpringMVC

SpringMVC

2020-09-23 01:46:08 其他

SSM框架之SpringMvc

springmvc

  • Spring需要匯入的Jar包

    1.jar
    spring-aop.jar
    spring-bean.jar
    spring-context.jar
    spring-core.jar
    spring-web.jar

  • SpringMvc框架需要匯入的Jar包

    spring-webmvc.jar
    commons-logging.jar

報錯NoClassDefFoundError:缺少jar

SpringMvc的意義

Servet - Springmvc
jsp ->Servlet (Springmvc)->Jsp

url

springmvc組態檔 springmvc.xml
選中常用的命名空間:beans aop context mvc

普通的servlet流程:
請求-url-pattern -交給對應的servlet去處理

如果現在想用springmvc,而不是普通的servlet,如何告知程式?-如何讓springmvc 介入程式:
需要配置一個 Springmvc自帶的servlet

通過以下配置,攔截所有請求,交給SpringMVC處理:

<servlet>
  	<servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

其中:

<url-pattern>.action</url-pattern>
  • /:一切請求 ,注意不是 /*
  • /user:攔截以 /user開頭的請求
  • /user/abc.do :只攔截該請求
  • .action:只攔截 .action結尾的請求

專案中同時兼容 springMVC和Servlet

 <servlet-mapping>
  	<servlet-name>springDispatcherServlet</servlet-name>
  	<url-pattern>.action</url-pattern>
  </servlet-mapping>

  <servlet>
  	<servlet-name>springDispatcherServlet</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>

通過

指定springmvc組態檔的路徑,如果要省略,必須放到 默認路徑:
/WEB-INF/springDispatcherServlet-servlet.xml

映射是去匹配@RequestMapping注解,可以和方法名、類名不一致
通過method指定 請求方式(get post delete put)
@RequestMapping(value=“welcome”,method=RequestMethod.POST) //映射

  • 設定name="xxxx"的情況:
    params= {“name2=zs”,“age!=23”}

    name2:必須有name="name2"引數

    age!=23 : a.如果有name=“age”,則age值不能是23
    b.沒有age
    !name2 :不能name="name2"的屬性

  • ant風格的請求路徑

    ? 單字符

    任意個字符(0或多個)
    ** 任意目錄

@RequestMapping(value=“welcome3/**/test”)
接受示例:

a href=“welcome3/abc/xyz/abccc/test”

  • 通過@PathVariable獲取動態引數
    public String welcome5(@PathVariable(“name”) String name ) {
    System.out.println(name);
    return “success” ;
    }

  • Springmvc: REST風格 :軟體編程風格

    • GET : 查

    • POST :增

    • DELETE :刪

    • PUT :改

  • 普通瀏覽器 只支持get post方式 ;其他請求方式 如 delelte|put請求是通過 過濾器新加入的支持,

    springmvc實作 :put|post請求方式的步驟
    a.增加過濾器

<!-- 增加HiddenHttpMethodFilte過濾器:目的是給普通瀏覽器 增加 put|delete請求方式 -->
<filter>
		<filter-name>HiddenHttpMethodFilte</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

</filter>

<filter-mapping>
		<filter-name>HiddenHttpMethodFilte</filter-name>
		<url-pattern>/*</url-pattern>
</filter-mapping>

b.表單

<form action="handler/testRest/1234" method="post">
	<input type="hidden"  name="_method" value="DELETE"/>
	<input type="submit" value="">
</form>

i:必須是post方式
ii:通過隱藏域 的value值 設定實際的請求方式 DELETE|PUT

c.控制器

@RequestMapping(value="testRest/{id}",method=RequestMethod.DELETE)
		public String  testDelete(@PathVariable("id") Integer id) {
			System.out.println("delete:刪 " +id);
			//Service層實作 真正的增
			return "success" ;//  views/success.jsp,默認使用了 請求轉發的 跳轉方式
		}

通過 method=RequestMethod.DELETE 匹配具體的請求方式

此外,可以發現 ,當映射名相同時@RequestMapping(value="testRest),可以通過method處理不同的請求,

過濾器中 處理put|delete請求的部分原始碼:

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	HttpServletRequest requestToUse = request;
	if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
		String paramValue = request.getParameter(this.methodParam);
		if (StringUtils.hasLength(paramValue)) {
			requestToUse = new HttpMethodRequestWrapper(request, paramValue);
		}
	}
	filterChain.doFilter(requestToUse, response);
}

原始請求:request,改請求 ,默認只支持get post header
但是如果 是"POST" 并且有隱藏域

<input type="hidden"  name="_method" value="DELETE"/>

則,過濾器 將原始的請求 request加入新的請求方式DELETE,并將原始請求 轉為 requestToUse 請求(request+Delete請求)
最后將requestToUse 放入 請求鏈中, 后續再請求request時 實際就使用改造后的 requestToUse

@RequestParam("uname")String name
@RequestParam(value="uage",required=false,defaultValue="23")
@RequestParam("uname"):   接受前臺傳遞的值,等價于request.getParameter("uname");
required=false:該屬性 不是必須的,
defaultValue="23":默認值23

獲取請求頭資訊

@RequestHeader
public String  testRequestHeader(@RequestHeader("Accept-Language")  String al  ) {

    通過@RequestHeader("Accept-Language")  String al   獲取請求頭中的Accept-Language值,并將值保存再al變數中

?

通過mvc獲取cookie值(JSESSIONID)
@CookieValue
(前置知識: 服務端在接受客戶端第一次請求時,會給該客戶端分配一個session (該session包含一個sessionId)),并且服務端會在第一次回應客戶端時 ,請該sessionId賦值給JSESSIONID 并傳遞給客戶端的cookie中

小結:
SpringMVC處理各種引數的流程/邏輯:
請求: 前端發請求a-> @RequestMappting(“a”)
處理請求中的引數xyz:

@RequestMappting("a") 
	public String  aa(@Xxx注解("xyz")  xyz)
	{
}

使用物件(物體類Student)接受請求引數

在SpringMVC中使用原生態的Servlet API :HttpServletRequest :直接將 servlet-api中的類、介面等 寫在springMVC所映射的方法引數中即可:

@RequestMapping(value="testServletAPI")
		public String testServletAPI(HttpServletRequest  request,HttpServletResponse response) {
//			request.getParameter("uname") ;
			System.out.println(request);
			return "success" ;
		}

1.處理模型資料
如果跳轉時需要帶資料:V、M,則可以使用以下方式:
ModelAndView、ModelMap 、Map、Model -資料放在了request作用域

@SessionAttributes、@ModelAttribute

示例:

public String testModel(Model model|	Map<String,Object> m) {

m.put(x,".."); 就會將x物件 放入request域中

如何將上述資料放入session中?@SessionAttributes(..)
}

@ModelAttribute
i.經常在 更新時使用
ii.在不改變原有代碼的基礎之上,插入一個新方法,

通過@ModelAttribute修飾的方法 ,會在每次請求前先執行
并且該方法的引數map.put()可以將 物件 放入 即將查詢的引數中;
必須滿足的約定:
map.put(k,v) 其中的k 必須是即將查詢的方法引數 的首字母小寫
testModelAttribute(Student xxx) ,即student;
如果不一致,需要通過@ModelAttribute宣告,如下:

	@ModelAttribute//在任何一次請求前,都會先執行@ModelAttribute修飾的方法
		public void queryStudentById(Map<String,Object> map) {
			//StuentService stuService = new StudentServiceImpl();
			//Student student = stuService.queryStudentById(31);
			//模擬呼叫三層查詢資料庫的操作
			Student student = new Student();
			student.setId(31);
			student.setName("zs");
			student.setAge(23);
			map.put("stu", student) ;//約定:map的key 就是方法引數 型別的首字母小寫
		}
	//修改:Zs-ls
	@RequestMapping(value="testModelAttribute")
	public String testModelAttribute(@ModelAttribute("stu")Student student) {
		student.setName(student.getName());//將名字修改為ls
		System.out.println(student.getId()+","+student.getName()+","+student.getAge());
		return "success";
	}

一個Servlet 對應一個功能:
增刪改查 對應于 4個Servlet

更新: Servlet - SpringMVC的Controller

查詢
@ModelAttribute
public void query()
{

}

修改
public String update()
{

}

@ModelAttribute會在 該類的每個方法執行前 均被執行一次,因為使用時需要注意,

2.視圖、視圖決議器

視圖的頂級介面: View
視圖決議器:ViewResolver

常見的視圖和決議器:
InternalResourceViewInternalResourceViewResolver

public class JstlView extends InternalResourceView

springMVC決議jsp時 會默認使用InternalResourceView
如果發現Jsp中包含了jstl語言相關的內容,則自動轉為JstlView

JstlView 可以決議jstl\實作國際化操作

國際化: 針對不同地區、不同國家 ,進行不同的顯示

中國:(大陸、香港) 歡迎
美國: welcome

  • i18n_zh_CH.properties
  • resource.welcome=你好
  • resource.exist=退出
  • i18n.properties

具體實作國際化步驟:

  • a.創建資源檔案
    基名_語言_地區.properties
    基名_語言.properties

  • b.配置springmvc.xml,加載資源檔案

<!-- 加載國際化資源檔案 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18n"></property>
</bean>

ResourceBundleMessageSource會在springmvc回應程式時 介入(決議國際化資源檔案)

c.通過jstl使用國際化
jstl.jar standar.jar

springmvc在啟動時,會自動查找一個id="messageSource"的bean,如果有 則自動加載


InternalResourceViewResolver其他功能:

  • 在組態檔中填寫映射地址

1.<mvc:view-controller …>
index.jsp -> Controller(@RequsetMapping(“a”)) ->succes.jsp

要用SpringMVC實作:index.jsp -> succes.jsp :
<mvc:view-controller path=“a” view-name=“success” />

以上注解 ,會讓所有的請求 轉入mvc:..中匹配映射地址,而會忽略調@RequsetMapping();
如果想讓 @RequsetMapping(“a”) 和mvc:..共存,則需要加入一個注解:mvc:annotation-driven</mvc:annotation-driven>

2.指定請求方式

指定跳轉方式:return “forward:/views/success.jsp”;

forward: redirect: ,需要注意 此種方式,不會被視圖決議器加上前綴(/views)、后綴(.jsp)

3.處理靜態資源:html css js 圖片 視頻

可以與用戶互動、因為時間/地點的不同 而結果不同的內容:動態(百度:天氣 )

在SpringMVC中,如果直接訪問靜態資源:404 ,原因:之前將所有的請求 通過通配符“、” 攔截,進而交給 SPringMVC的入口DispatcherServlet去處理:找該請求映射對應的 @requestMapping

http://localhost:8888/SpringMVCProject/img.png

@RequsetMapping(“img.png”)
return sucess

解決:如果是 需要mvc處理的,則交給@RequsetMapping(“img.png”)處理;如果不需要springmvc處理,則使用 tomcat默認的Servlet去處理,
tomcat默認的Servlet去處理:如果有 對應的請求攔截,則交給相應的Servlet去處理;如果沒有對應的servlet,則直接訪問,
tomcat默認的Servlet在哪里?在tomcat組態檔\conf\web.xml中

<servlet>
	<servlet-name>abc</servlet-name>
	<servlet-class>xxx.xxx.xx.ABCServlet</servlet-class>
</servlet>

<servlet-mapping>
	<servlet-name>abc</servlet-name>
	<url-pattern>/abc</url-pattern>
</servlet-mapping>

解決靜態資源方案:如果有springmvc對應的@requestMapping則交給spring處理;如果沒有對應@requestMapping,則交給服務器tomcat默認的servlet去處理 :實作方法,只需要增加2個注解即可

springmvc.xml: 
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven></mvc:annotation-driven>
總結:要讓springmvc訪問靜態資源,只需要加入以下2個注解:

<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:annotation-driven></mvc:annotation-driven>

4.型別轉換

  • a.Spring自帶一些 常見的型別轉換器:
    public String testDelete(@PathVariable(“id”) String id) ,即可以接受int型別資料id 也可以接受String型別的id

  • b.可以自定義型別轉換器
    i.撰寫 自定義型別轉器的類 (實作Converter介面)
    public class MyConverter implements Converter<String,Student>{

@Override
public Student convert(String source) {//source:2-zs-23
	//source接受前端傳來的String:2-zs-23
	String[] studentStrArr = source.split("-") ;
	Student student = new Student();
	student.setId(  Integer.parseInt(  studentStrArr[0]) );
	student.setName(studentStrArr[1]);
	student.setAge(Integer.parseInt(studentStrArr[2] ));
	return student;
}

}

ii.配置:將MyConverter加入到springmvc中

<bean  id="myConverter" class="org.lanqiao.converter.MyConverter"></bean>
<!-- 2將myConverter再納入 SpringMVC提供的轉換器Bean -->
<bean id="conversionService"  class="org.springframework.context.support.ConversionServiceFactoryBean">
	<property name="converters">
		<set>
			<ref bean="myConverter"/>
		</set>
	</property>
</bean>

<!-- 3將conversionService注冊到annotation-driven中 -->
<!--此配置是SpringMVC的基礎配置,很功能都需要通過該注解來協調  -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

測驗轉換器:

@RequestMapping(value="testConverter")
		public String testConverter(@RequestParam("studentInfo")  Student student) {// 前端:2-zs-23  		System.out.println(student.getId()+","+student.getName()+","+student.getAge());
		
		return "success";
	}

其中@RequestParam(“studentInfo”)是觸發轉換器的橋梁:
@RequestParam(“studentInfo”)接受的資料 是前端傳遞過來的:2-zs-23 ,但是 需要將該資料 復制給 修飾的目的物件Student;因此SPringMVC可以發現 接收的資料 和目標資料不一致,并且 這兩種資料分別是 String、Student,正好符合public Student convert(String source)轉換器,

5.資料格式化
SimpleDateForamt sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
SPringMVC提供了很多注解,方便我們資料格式化
實作步驟:
a.配置

	<!-- 配置 資料格式化 注解 所依賴的bean -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
	</bean>

b.通過注解使用
@DateTimeFormat(pattern=“yyyy-MM-dd”)
@NumberFormat(parttern="###,#")


1.錯誤訊息:
public String testDateTimeFormat(Student student, BindingResult result ,Map<String,Object> map) {
需要驗證的資料是 Student中的birthday, SPringMVC要求 如果校驗失敗 則將錯誤資訊 自動放入 該物件之后緊挨著的 BindingResult中,
Student student, BindingResult result之間 不能有其他引數,

如果要將控制臺的錯誤訊息 傳到jsp中顯示,則可以將 錯誤訊息物件放入request域中,然后 在jsp中 從request中獲取,

  1. 資料校驗
    JSR303
    Hibernate Validator

使用Hibernate Validator步驟:

a.jar(注意各個jar之間可能存在版本不兼容)
hibernate-validator-5.0.0.CR2.jar classmate-0.8.0.jar jboss-logging-3.1.1.GA.jar
validation-api-1.1.0.CR1.jar hibernate-validator-annotation-processor-5.0.0.CR2.jar

b配置

<mvc:annotation-driven ></mvc:annotation-driven>

此時mvc:annotation-driven的作用:要實作Hibernate Validator/JSR303 校驗(或者其他各種校驗),必須實作SpringMVC提供的一個介面:ValidatorFactory

LocalValidatorFactoryBeanValidatorFactory的一個實作類,

<mvc:annotation-driven ></mvc:annotation-driven>

會在springmvc容器中 自動加載一個LocalValidatorFactoryBean類,因此可以直接實作資料校驗,

會在springmvc容器中 自動加載一個LocalValidatorFactoryBean類,因此可以直接實作資料校驗,

c.直接使用注解

public class Student {

@Past//當前系統時間以前
private Date birthday ;

}

在校驗的Controller中 ,給校驗的物件前增加 @Valid
		public String testDateTimeFormat(@Valid Student student, BindingResult result ,Map<String,Object> map) {
			{...}
  • 3.Ajax請求SpringMVC,并且JSON格式的資料

    a.jar
    jackson-annotations-2.8.9.jar
    jackson-core-2.8.9.jar
    jackson-databind-2.8.9.jar

    b.

@ResponseBody修飾的方法,會將該方法的回傳值 以一個json陣列的形式回傳給前臺

@ResponseBody//告訴SpringMVC,此時的回傳 不是一個 View頁面,而是一個 ajax呼叫的回傳值(Json陣列)
		@RequestMapping(value="testJson")
		public List<Student> testJson() {
			//Controller-Service-dao
			//StudentService studentService = new StudentServiceImp();
//			List<Student> students =  studentService.qeuryAllStudent();
			//模擬呼叫service的查詢操作
		List<Student> students = new ArrayList<>();
		students.add(stu1) ;
		students.add(stu2) ;
		students.add(stu3) ;
		
		return students;
	}

前臺:服務端將回傳值結果 以json陣列的形式 傳給了result,

$("#testJson").click(function(){
					//通過ajax請求springmvc
					$.post(
						"handler/testJson",//服務器地址
						//{"name":"zs","age":23}
						function(result){//服務端處理完畢后的回呼函式 List<Student> students, 加上@ResponseBody后, students實質是一個json陣列的格式
							for(var i=0;i<result.length ;i++){
								alert(result[i].id +"-"+result[i].name +"-"+result[i].age);
							}
						}
					);

1.SpringMVC實作檔案上傳:
和Servlet方式的本質一樣,都是通過commons-fileupload.jar和commons-io.jar
SpringMVC可以簡化檔案上傳的代碼,但是必須滿足條件:實作MultipartResolver介面 ;而該介面的實作類SpringMVC也已經提供了CommonsMultipartResolver

具體步驟:(直接使用CommonsMultipartResolver實作上傳)
a.jar包
commons-fileupload.jar、commons-io.jar
b.配置CommonsMultipartResolver
將其加入SpringIOC容器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 上傳單個檔案的最大值,單位Byte;如果-1,表示無限制 -->
		<property name="maxUploadSize"  value="102400"></property>
</bean>

c.處理方法
//檔案上傳處理方法

@RequestMapping(value="testUpload") //abc.png
		public String testUpload(@RequestParam("desc") String desc  , @RequestParam("file") MultipartFile file  ) throws IOException {	
    System.out.println("檔案描述資訊:"+desc);
		//jsp中上傳的檔案:file
		
		InputStream input = file.getInputStream() ;//IO
		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();
		//將file上傳到服務器中的 某一個硬碟檔案中
	System.out.println("上傳成功!");
		
		return "success";
	}
<form action="handler/testUpload" method="post"  enctype="multipart/form-data">
	<input type="file" name="file" />
描述:<input name="desc" type="text" />
	<input type="submit" value="上傳">
</form>

框架: 將原來自己寫的1000行代碼,變成:框架幫你寫900行,剩下100行自己寫

控制器:handler servlet controller action

2.攔截器

攔截器的原理和過濾器相同,

SpringMVC:要想實作攔截器,必須實作一個介面HandlerInterceptor

ctrl+shift+r :自己撰寫的代碼.java .jsp .html
ctrl+shift+t :jar中的代碼

a.撰寫攔截器implements HandlerInterceptor
b.配置:將自己寫的攔截器 配置到springmvc中(spring)

攔截器1攔截請求- 攔截器2攔截請求 - 請求方法 - 攔截器2處理相應-攔截器1處理相應- 只會被 最后一個攔截器的afterCompletion()攔截

如果有多個攔截器,則每個攔截器的preHandle postHandle 都會在相應時機各被觸發一次;但是afterCompletion, 只會執行最后一個攔截器的該方法,

3.例外處理
SpringMVC: HandlerExceptionResolver介面,

該介面的每個實作類 都是例外的一種處理方式:

a.
ExceptionHandlerExceptionResolver: 主要提供了**@ExceptionHandler**注解,并通過該注解處理例外

//該方法 可以捕獲本類中  拋出的ArithmeticException例外
@ExceptionHandler({ArithmeticException.class,ArrayIndexOutOfBoundsException.class  })
public String handlerArithmeticException(Exception e) {
	System.out.println(e +"============");
	return "error" ;
}

@ExceptionHandler標識的方法的引數 必須在例外型別(Throwable或其子類) ,不能包含其他型別的引數

例外處理路徑:最短優先
如果有方法拋出一個ArithmeticException例外,而該類有2個對應的例外處理都可以處理:

@ExceptionHandler({Exception.class  })
	public ModelAndView handlerArithmeticException2(Exception e) {}
@ExceptionHandler({ArithmeticException.class  })
public ModelAndView handlerArithmeticException1(Exception e) {}

則優先級: 最短優先,

@ExceptionHandler默認只能捕獲 當前類中的例外方法,
如果發生例外的方法 和處理例外的方法 不在同一個類中:@ControllerAdvice

總結:如果一個方法用于處理例外,并且只處理當前類中的例外:@ExceptionHandler
如果一個方法用于處理例外,并且處理所有類中的例外: 類前加@ControllerAdvice、 處理例外的方法前加@ExceptionHandler

b.
ResponseStatusExceptionResolver:自定義例外顯示頁面 @ResponseStatus

@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="陣列越界222!!!")
public class MyArrayIndexOutofBoundsException extends Exception {//自定義例外

}

@ResponseStatus也可以標志在方法前:

@RequestMapping("testMyException")
	public String testMyException(@RequestParam("i") Integer i) throws MyArrayIndexOutofBoundsException {
		if(i == 3) {
			throw new MyArrayIndexOutofBoundsException();//拋出例外
		}
		return "success" ;
	}
@RequestMapping("testMyException2")
public String testMyException2(@RequestParam("i") Integer i) {
	if(i == 3) {
		return "redirect:testResponseStatus" ;//跳轉到某一個 例外處理方法里
	}
	return "success" ;
}


c.例外處理的實作類:
DefaultHandlerExceptionResolver:SPringMVC在一些常見例外的基礎上(300 500 405),新增了一些例外,例如:

  • @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
  • @see #handleNoSuchRequestHandlingMethod
  • @see #handleHttpRequestMethodNotSupported :如果springmvc的處理方法限制為post方式,如果實際請求為get,則會觸發此例外顯示的頁面
  • @see #handleHttpMediaTypeNotSupported
  • @see #handleMissingServletRequestParameter
  • @see #handleServletRequestBindingException
  • @see #handleTypeMismatch
  • @see #handleHttpMessageNotReadable
  • @see #handleHttpMessageNotWritable
  • @see #handleMethodArgumentNotValidException
  • @see #handleMissingServletRequestParameter
  • @see #handleMissingServletRequestPartException
  • @see #handleBindException

d.
SimpleMappingExceptionResolver:通過配置來實作例外的處理

?

<!-- SimpleMappingExceptionResolver:以配置的方式 處理例外 -->
	<bean  class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<!-- 如果發生例外,例外物件會被保存在  exceptionAttribute的value值中;并且會放入request域中 ;例外變數的默認值是 exception-->
		<!--<property name="exceptionAttribute" value="exception"></property>-->
			<property name="exceptionMappings">
					<props>
						<!-- 相當于catch(ArithmeticException ex){ 跳轉:error } -->
						<prop key="java.lang.ArithmeticException">
							error
						</prop>
						<prop key="java.lang.NullPointerException">
							error
						</prop>				
				</props>
		</property>
</bean>

SSM整合:
Spring - SpringMVC - MyBatis

Spring - MyBatis : 需要整合:將MyBatis的SqlSessionFactory 交給Spring

2
Spring - SpringMVC : 就是將Spring - SpringMVC 各自配置一遍

思路:
SqlSessionFactory -> SqlSession ->StudentMapper ->CRUD
可以發現 ,MyBatis最終是通過SqlSessionFactory來操作資料庫,
Spring整合MyBatis 其實就是 將MyBatis的SqlSessionFactory 交給Spring

S(Spring)M整合步驟:
1.jar
mybatis-spring.jar spring-tx.jar spring-jdbc.jar spring-expression.jar
spring-context-support.jar spring-core.jar spring-context.jar
spring-beans.jar spring-aop.jar spring-web.jar commons-logging.jar
commons-dbcp.jar ojdbc.jar mybatis.jar log4j.jar commons-pool.jar

2.類-表

Student類 -student表

3.-(與Spring整合時,conf.xml可省)–MyBatis組態檔conf.xml(資料源、mapper.xml) --可省,將該檔案中的配置 全部交由spring管理

spring組態檔 applicationContext.xml

4.通過mapper.xml將 類、表建立映射關系

之前使用MyBatis: conf.xml ->SqlSessionFacotry

現在整合的時候,需要通過Spring管理SqlSessionFacotry ,因此 產生qlSessionFacotry 所需要的資料庫資訊 不在放入conf.xml 而需要放入spring組態檔中

配置Spring組態檔(applicationContext.xml) (Web專案):
web.xml
監聽器必須配置

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

6.使用Spring整合MyBatis :將MyBatis的SqlSessionFactory 交給Spring

7.繼續整合SpringMVC:將springmvc加入專案即可
a.加入SpringMVC需要的jar
spring-webmvc.jar

b.給專案加入SpringMVC支持
web.xml: dispatcherServlet

c.撰寫springmvc組態檔:
applicationContext-controller.xml:視圖決議器、基礎配置

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/108426.html

標籤:其他

上一篇:作業3年去大廠面試Java開發,被Spring問自閉了...

下一篇:選擇IPFS/Filecoin的九大理由!

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more