<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    yxhxj2006

    常用鏈接

    統計

    最新評論

    基于注解的 Spring MVC 簡單入門

    以下內容是經過自己整理資料、官方文檔所得:


    web.xml 配置:

     

    <servlet> 	<servlet-name>dispatcher</servlet-name> 	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 	<init-param> 		<description>加載/WEB-INF/spring-mvc/目錄下的所有XML作為Spring MVC的配置文件</description> 		<param-name>contextConfigLocation</param-name> 		<param-value>/WEB-INF/spring-mvc/*.xml</param-value> 	</init-param> 	<load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> 	<servlet-name>dispatcher</servlet-name> 	<url-pattern>*.htm</url-pattern> </servlet-mapping>

     

    這樣,所有的.htm的請求,都會被DispatcherServlet處理;

    初始化 DispatcherServlet 時,該框架在 web 應用程序WEB-INF 目錄中尋找一個名為[servlet-名稱]-servlet.xml的文件,并在那里定義相關的Beans,重寫在全局中定義的任何Beans,像上面的web.xml中的代碼,對應的是dispatcher-servlet.xml;當然也可以使用<init-param>元素,手動指定配置文件的路徑;

    dispatcher-servlet.xml 配置:

     

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xmlns:p="http://www.springframework.org/schema/p"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:tx="http://www.springframework.org/schema/tx"        xsi:schemaLocation="http://www.springframework.org/schema/beans 			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 			http://www.springframework.org/schema/context  			http://www.springframework.org/schema/context/spring-context-3.0.xsd 			http://www.springframework.org/schema/aop  			http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 			http://www.springframework.org/schema/tx  			http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 			http://www.springframework.org/schema/mvc  			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 			http://www.springframework.org/schema/context  			http://www.springframework.org/schema/context/spring-context-3.0.xsd">     <!--         使Spring支持自動檢測組件,如注解的Controller     -->     <context:component-scan base-package="com.minx.crm.web.controller"/>         <bean id="viewResolver"           class="org.springframework.web.servlet.view.InternalResourceViewResolver"           p:prefix="/WEB-INF/jsp/"           p:suffix=".jsp" /> </beans>

     

    第一個Controller

    package com.minx.crm.web.controller;  import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class IndexController {     @RequestMapping("/index")     public String index() {         return "index";     } }

    @Controller注解標識一個控制器,@RequestMapping注解標記一個訪問的路徑(/index.htm),return "index"標記返回視圖(index.jsp);

    注:如果@RequestMapping注解在類級別上,則表示一相對路徑,在方法級別上,則標記訪問的路徑;

    @RequestMapping注解標記的訪問路徑中獲取參數:

    Spring MVC 支持RESTful風格的URL參數,如:

    @Controller public class IndexController {      @RequestMapping("/index/{username}")     public String index(@PathVariable("username") String username) {         System.out.print(username);         return "index";     } }

    @RequestMapping中定義訪問頁面的URL模版,使用{}傳入頁面參數,使用@PathVariable 獲取傳入參數,即可通過地址:http://localhost:8080/crm/index/tanqimin.htm 訪問;

    根據不同的Web請求方法,映射到不同的處理方法:

    使用登陸頁面作示例,定義兩個方法分辨對使用GET請求和使用POST請求訪問login.htm時的響應。可以使用處理GET請求的方法顯示視圖,使用POST請求的方法處理業務邏輯

    @Controller public class LoginController {     @RequestMapping(value = "/login", method = RequestMethod.GET)     public String login() {         return "login";     }     @RequestMapping(value = "/login", method = RequestMethod.POST)     public String login2(HttpServletRequest request) {             String username = request.getParameter("username").trim();             System.out.println(username);         return "login2";     } }

    在視圖頁面,通過地址欄訪問login.htm,是通過GET請求訪問頁面,因此,返回登陸表單視圖login.jsp;當在登陸表單中使用POST請求提交數據時,則訪問login2方法,處理登陸業務邏輯;

    防止重復提交數據,可以使用重定向視圖:

    return "redirect:/login2"

    可以傳入方法的參數類型:

    @RequestMapping(value = "login", method = RequestMethod.POST) public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) { 	String username = request.getParameter("username"); 	System.out.println(username); 	return null; }

     

    可以傳入HttpServletRequestHttpServletResponseHttpSession,值得注意的是,如果第一次訪問頁面,HttpSession沒被創建,可能會出錯;

    其中,String username = request.getParameter("username");可以轉換為傳入的參數:

     

    @RequestMapping(value = "login", method = RequestMethod.POST) public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) { 	String username = request.getParameter("username"); 	System.out.println(username); 	return null; }

     

    使用@RequestParam 注解獲取GET請求或POST請求提交的參數;

    獲取Cookie的值:使用@CookieValue 

    獲取PrintWriter

    可以直接在Controller的方法中傳入PrintWriter對象,就可以在方法中使用:

    @RequestMapping(value = "login", method = RequestMethod.POST) public String testParam(PrintWriter out, @RequestParam("username") String username) { 	out.println(username); 	return null; }

     

     

    獲取表單中提交的值,并封裝到POJO中,傳入Controller的方法里:

    POJO如下(User.java):

    public class User{ 	private long id; 	private String username; 	private String password;  	…此處省略getter,setter... }

     

     

    通過表單提交,直接可以把表單值封裝到User對象中:

    @RequestMapping(value = "login", method = RequestMethod.POST) public String testParam(PrintWriter out, User user) { 	out.println(user.getUsername()); 	return null; }

     

     

    可以把對象,put 入獲取的Map對象中,傳到對應的視圖:

    @RequestMapping(value = "login", method = RequestMethod.POST) public String testParam(User user, Map model) { 	model.put("user",user); 	return "view"; }

     

    在返回的view.jsp中,就可以根據key來獲取user的值(通過EL表達式,${user }即可);

    Controller中方法的返回值:

    void:多數用于使用PrintWriter輸出響應數據;

    String 類型:返回該String對應的View Name

    任意類型對象:

    返回ModelAndView

    自定義視圖(JstlViewExcelView):

    攔截器(Inteceptors):

    public class MyInteceptor implements HandlerInterceptor { 	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o)  		throws Exception { 		return false; 	} 	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav)  		throws Exception { 	} 	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn)  		throws Exception { 	} }

     

    攔截器需要實現HandleInterceptor接口,并實現其三個方法:

    preHandle:攔截器的前端,執行控制器之前所要處理的方法,通常用于權限控制、日志,其中,Object o表示下一個攔截器;

    postHandle:控制器的方法已經執行完畢,轉換成視圖之前的處理;

    afterCompletion:視圖已處理完后執行的方法,通常用于釋放資源;

    MVC的配置文件中,配置攔截器與需要攔截的URL

    <mvc:interceptors> 	<mvc:interceptor> 		<mvc:mapping path="/index.htm" /> 		<bean class="com.minx.crm.web.interceptor.MyInterceptor" /> 	</mvc:interceptor> </mvc:interceptors>

     

    國際化:

    MVC配置文件中,配置國際化屬性文件:

    <bean id="messageSource" 	class="org.springframework.context.support.ResourceBundleMessageSource" 	p:basename="message"> </bean>

     

    那么,Spring就會在項目中搜索相關的國際化屬性文件,如:message.propertiesmessage_zh_CN.properties

    VIEW中,引入Spring標簽:<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>,使用<spring:message code="key" />調用,即可;

    如果一種語言,有多個語言文件,可以更改MVC配置文件為:

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 	<property name="basenames"> 		<list> 			<value>message01</value> 			<value>message02</value> 			<value>message03</value> 		</list> 	</property> </bean>

    posted on 2013-11-04 23:23 奮斗成就男人 閱讀(295) 評論(0)  編輯  收藏 所屬分類: J2EE

    主站蜘蛛池模板: 青娱乐在线视频免费观看| 鲁死你资源站亚洲av| 午夜精品射精入后重之免费观看| 国产成人精品亚洲精品| 人人公开免费超级碰碰碰视频| 成人免费视频国产| 亚洲精品乱码久久久久蜜桃| 国产jizzjizz免费看jizz| 最好2018中文免费视频| 亚洲国产午夜中文字幕精品黄网站| 男女作爱免费网站| 亚洲熟女一区二区三区| 四虎影视在线影院在线观看免费视频 | 亚洲国产中文v高清在线观看| 亚洲精品久久无码| 免费一级毛片免费播放| 久久久久国色AV免费观看| 亚洲国产精品va在线播放| 99re在线视频免费观看| 亚洲一区无码中文字幕乱码| 在线成人a毛片免费播放| 免费国产黄网站在线看| 亚洲av无码一区二区三区不卡 | 久久久久久噜噜精品免费直播| 亚洲AV永久青草无码精品| 四虎在线成人免费网站| 蜜芽亚洲av无码一区二区三区| 国产亚洲精品无码专区| 久久国产乱子伦精品免费看| 亚洲人成图片网站| 亚洲阿v天堂在线2017免费| 亚洲精品免费视频| 亚洲av纯肉无码精品动漫| 亚洲无码高清在线观看| 中文字幕无码播放免费| 黄页免费视频播放在线播放| 亚洲不卡中文字幕无码| 免费无码又爽又高潮视频 | 中文字幕无码免费久久99| 日本激情猛烈在线看免费观看| 久久精品国产亚洲AV香蕉|