深入springmvc

1.springMVC控制器:
非註解使用:
繼承自Controller和MultiActionController
單個Controller,實現handleRequest方法
多個Controller, 實現自定義方法
註解使用:
spring配置文件中配置:
<!-- 註解掃描包 -->
<context:component-scan base-package="com.tgb.web.controller.annotation" />
<!-- 開啓註解:方式一-->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean>
<!-- 開啓註解:方式二 -->
<mvc:annotation-driven/>

方式二包含了方式一中的兩個bean
直接加 @Controller, @RequestMapping等註釋就行
方式一的返回值:
Controller中返回值是ModelAndView類型
方式一的返回值:
Controller中返回值直接是String類型,Controller本身要加 @RequestMapping(...)註釋

常見的註解:
@Controller 聲明Action組件
@Service 聲明Service組件 @Service("myMovieLister")
@Repository 聲明Dao組件
@Component 泛指組件, 當不好歸類時.
@RequestMapping("/menu") 請求映射
@Resource 用於注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName")
@Autowired 用於注入,(srping提供的) 默認按類型裝配
@Transactional( rollbackFor={Exception.class}) 事務管理
@ResponseBody
@Scope("prototype") 設定bean的作用域

2.訪問靜態資源:
<!-- 靜態資源訪問 方式一-->
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
匹配URL /img/** 的URL被當做靜態資源,由Spring讀出到內存中再響應http。

<!-- 靜態資源訪問 方式二-->
<mvc:default-servlet-handler/> 使用默認的Servlet來響應靜態文件。

另外一種加載靜態資源的方式:激活Tomcat的defaultServlet來處理靜態文件
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
要配置多個,每種文件配置一個
要寫在DispatcherServlet的前面, 讓 defaultServlet先攔截請求,這樣請求就不會進入Spring了,我想性能是最好的吧。

Tomcat, Jetty, JBoss, and GlassFish 自帶的默認Servlet的名字 -- "default"
Google App Engine 自帶的 默認Servlet的名字 -- "_ah_default"
Resin 自帶的 默認Servlet的名字 -- "resin-file"
WebLogic 自帶的 默認Servlet的名字 -- "FileServlet"
WebSphere 自帶的 默認Servlet的名字 -- "SimpleFileServlet"



3.視圖解析器
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>

4.參數訪問Cotroller
<bean name="/test1/multi" class="com.tgb.web.controller.MultiController">
<property name="methodNameResolver">
<ref bean="paramMethodResolver"/>
</property>
</bean>
<bean id="paramMethodResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="param"></property>
</bean>

5.@RequestMapping 參數說明
value
定義處理方法的請求的 URL 地址。
method
定義處理方法的 http method 類型,如 GET、POST 等,作用縮小訪問方式範圍,如果不寫,則默認POST、GET都可以。
params
定義請求的 URL 中必須包含的參數。
headers
定義請求中 Request Headers 必須包含的參數。

6.web.xml常用字符編碼配置
<filter>
<filter-name>encodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!-- encoding filter for jsp page -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

7.參數傳遞
提交數據:
可以直接通過form表單來提交數據或者ajax提交數據,也可以直接在url中通過get方式附加參數,在controller中在request中獲取

在Controller中也可以直接定義參數類型來獲取請求的參數
@RequestMapping("/addUserJson")
public void addUserJson(User user,HttpServletRequest request,HttpServletResponse response){
}

8.文件上傳
增加多部件分解器配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="104857600000000000" />
<property name="maxInMemorySize" value="4096000" />
</bean>

form表單上傳
<form name="userForm" action="/springMVC7/file/upload2" method="post" enctype="multipart/form-data" >
選擇文件:<input type="file" name="file">
<input type="submit" value="上傳" >
</form>

Controller處理(重命名保存到本地)

第一種:原始方式(適合小文件)
@RequestMapping("/upload")
public String addUser(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
System.out.println("fileName---->" + file.getOriginalFilename());
if(!file.isEmpty()){
try {
FileOutputStream os = new FileOutputStream("E:/002/" + new Date().getTime() + file.getOriginalFilename());
InputStream in = file.getInputStream();
int b = 0;
while((b=in.read()) != -1){
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
System.out.println("fileSize="+file.getSize());
return "/success";
}

第二種:新方式(適合較大文件)
@RequestMapping("/upload2")
public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if(multipartResolver.isMultipart(request)){
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
MultipartFile file = multiRequest.getFile((String)iter.next());
if(file != null){
String fileName = "demoUpload" + file.getOriginalFilename();
String path = "E:/002/" + fileName;
File localFile = new File(path);
file.transferTo(localFile);
}
}
}
}

9.web.xml配置文件中classpath*:和classpath:的區別
前者會將所有同名的文件都加載,後者同名配置文件只加載第一個
10.在一個總配置文件中導入多個子配置文件
<import resource="classpath*:config/springAnnotation-import.xml"/>
<import resource="classpath*:config/springAnnotation-import2.xml"/>
11.springMVC與Spring的集成
XXXXXXX

12.過濾器filter,攔截器interceptor與監聽器listener
servlet是單例的,Servlet可通過單實例多線程模式處理多個請求參考:http://www.cnblogs.com/yxnchinahlj/p/4132917.html
過濾器filter: 對目標資源的請求和響應進行截取。簡單說,就是可以實現web容器對某資源的訪問前截獲進行相關的處理,
還可以在某資源向web容器返回響應前進行截獲進行處理。簡單的說,對資源的請求訪問進行的處理。
攔截器interceptor: 在AOP(Aspect-Oriented Programming)中用於在某個方法或字段被訪問之前,進行攔截然後在之前或之後加入某些操作。
攔截是AOP的一種實現策略。常常用在一些方法上的session檢查,權限攔截等等。可聯想到權限攔截AOP。
AOP簡介:一般而言,我們管切入到指定類指定方法的代碼片段稱爲切面,而切入到哪些類、哪些方法則叫切入點。
有了AOP,我們就可以把幾個類共有的代碼,抽取到一個切片中,等到需要時再切入對象中去,從而改變其原有的行爲。
監聽器: 監聽--就是在進行某種各個範圍(application,session,request)中有相關值的設置、修改、替換的時候,這些操作都會觸發事件,
而Java中事件的代理機制,事件處理是利用listener機制,所以爲了在事件觸發的時候能夠使自己能夠採取相應的措施,
就需要---->繼承這樣的listener,在listener中覆寫相應的方法,覆寫相應的事件處理方法,在對應的方法中處理對應的事件,
也就是進行了監聽。

二者區別:
1. 攔截器是基於java的反射機制的,而過濾器是基於函數回調。
2. 攔截器不依賴與servlet容器,過濾器依賴與servlet容器。
3. 攔截器只能對action請求起作用,而過濾器則可以對幾乎所有的請求起作用。
4. 攔截器可以訪問action上下文、值棧裏的對象,而過濾器不能訪問。
5. 在action的生命週期中,攔截器可以多次被調用,而過濾器只能在容器初始化時被調用一次

Spring中的攔截器:

Spring爲我們提供了:
org.springframework.web.servlet.HandlerInterceptor接口,
org.springframework.web.servlet.handler.HandlerInterceptorAdapter適配器,
實現這個接口或繼承此類,可以非常方便的實現自己的攔截器。
有以下三個方法:
Action之前執行:
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler);
生成視圖之前執行
public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler,ModelAndView modelAndView);
最後執行,可用於釋放資源
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
分別實現預處理、後處理(調用了Service並返回ModelAndView,但未進行頁面渲染)、返回處理(已經渲染了頁面)
在preHandle中,可以進行編碼、安全控制等處理;
在postHandle中,有機會修改ModelAndView;
在afterCompletion中,可以根據ex是否爲null判斷是否發生了異常,進行日誌記錄。
參數中的Object handler是下一個攔截器。


配置文件中攔截器的配置:

方案一,(近似)總攔截器,攔截所有url
Java代碼 收藏代碼
<mvc:interceptors>
<bean class="com.app.mvc.MyInteceptor" />
</mvc:interceptors>
爲什麼叫“近似”,前面說了,Spring沒有總的攔截器。
<mvc:interceptors/>會爲每一個HandlerMapping,注入一個攔截器。總有一個HandlerMapping是可以找到處理器的,最多也只找到一個處理器,所以這個攔截器總會被執行的。起到了總攔截器的作用。
如果是REST風格的URL,靜態資源也會被攔截。
方案二, (近似) 總攔截器, 攔截匹配的URL。
Xml代碼 收藏代碼
<mvc:interceptors >
<mvc:interceptor>
<mvc:mapping path="/user/*" /> <!-- /user/* -->
<bean class="com.mvc.MyInteceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
就是比 方案一多了一個URL匹配。
如果是REST風格的URL,靜態資源也會被攔截。

13.springMVC給Action做Junit單元測試參考:
http://elf8848.iteye.com/blog/875830/



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章