免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
Spring MVC 注解開發(fā)備忘錄
此文章不是Spirng MVC講解,相關(guān)文章大家可以自行Google。
先來看一下Spring MVC注解開發(fā)中常用標(biāo)簽,如下表:
編號(hào)
注解
說明
位置
備注
1
@Controller
將類變成 Spring Bean
現(xiàn)階段 @Controller 、 @Service 以及 @Repository 和 @Component 注解的作用是等價(jià)的
2
@RequestMapping
請(qǐng)求映射
類、方法
標(biāo)注在類上意指類實(shí)現(xiàn) Controller 接口
標(biāo)注在方法上意指擴(kuò)展 Spring 預(yù)定義 Controller ( 如 :SimpleFormController)
3
@RequestParam
入?yún)⒔壎?URL
入?yún)?div style="height:15px;">
指定 URL 參數(shù)與方法入?yún)⒌慕壎ㄒ?guī)則
4
@SessionAttributes
設(shè)定 Session 范圍屬性
如: @SessionAttributes("user") ,將把 ModelMap 中的 user 屬性添加到 Session 范圍
5
@InitBinder
注冊(cè) Controller 級(jí)的自定義屬性編輯器
方法
@InitBinder 注解的方法必須擁有一個(gè) WebDataBinder 類型的入?yún)?,以?Spring MVC 框架將注冊(cè)屬性編輯器的 WebDataBinder 對(duì)象傳遞進(jìn)來
6
@ModelAttribute
準(zhǔn)備引用數(shù)據(jù) / 將 ModelMap 屬性綁定到入?yún)?div style="height:15px;">
方法、入?yún)?div style="height:15px;">
標(biāo)注在方法上:準(zhǔn)備引用數(shù)據(jù)
標(biāo)注在入?yún)⑸希簩?ModelMap 中的屬性綁定到請(qǐng)求處理方法的入?yún)⒅?div style="height:15px;">
再來看一下Controller中方法的入?yún)㈩愋停?div style="height:15px;">編號(hào)
請(qǐng)求處理方法入?yún)⒌目蛇x類型
說明
1
Java 基本數(shù)據(jù)類型和 String
默認(rèn)情況下將按名稱匹配的方式綁定到 URL 參數(shù)上,可以通過 @RequestParam 注解改變默認(rèn)的綁定規(guī)則
2
request/response/session
既可以是 Servlet API 的也可以是 Portlet API 對(duì)應(yīng)的對(duì)象, Spring 會(huì)將它們綁定到 Servlet 和 Portlet 容器的相應(yīng)對(duì)象上
3
org.springframework.web.context.request.WebRequest
內(nèi)部包含了 request 對(duì)象
4
java.io.InputStream/java.io.Reader
可以借此訪問 request 的內(nèi)容
5
java.io.OutputStream / java.io.Writer
可以借此操作 response 的內(nèi)容
6
任何標(biāo)注了 @RequestParam 注解的入?yún)?div style="height:15px;">被標(biāo)注 @RequestParam 注解的入?yún)⒔壎ǖ教囟ǖ?request 參數(shù)上。
7
java.util.Map / org.springframework.ui.ModelMap
它綁定 Spring MVC 框架中每個(gè)請(qǐng)求所創(chuàng)建的潛在的模型對(duì)象,它們可以被 Web 視圖對(duì)象訪問(如 JSP )
8
命令 / 表單對(duì)象(注:一般稱綁定使用 HTTP GET 發(fā)送的 URL 參數(shù)的對(duì)象為命令對(duì)象,而稱綁定使用 HTTP POST 發(fā)送的 URL 參數(shù)的對(duì)象為表單對(duì)象)
它們的屬性將以名稱匹配的規(guī)則綁定到 URL 參數(shù)上,同時(shí)完成類型的轉(zhuǎn)換。而類型轉(zhuǎn)換的規(guī)則可以通過 @InitBinder 注解或通過 HandlerAdapter 的配置進(jìn)行調(diào)整
9
org.springframework.validation.Errors / org.springframework.validation.BindingResult
為屬性列表中的命令 / 表單對(duì)象的校驗(yàn)結(jié)果,注意檢驗(yàn)結(jié)果參數(shù)必須緊跟在命令 / 表單對(duì)象的后面
10
rg.springframework.web.bind.support.SessionStatus
可以通過該類型 status 對(duì)象顯式結(jié)束表單的處理,這相當(dāng)于觸發(fā) session 清除其中的通過 @SessionAttributes 定義的屬性
再來看一下Controller中方法的返回類型:
編號(hào)
請(qǐng)求處理方法入?yún)⒌目蛇x類型
說明
1
void
此時(shí)邏輯視圖名由請(qǐng)求處理方法對(duì)應(yīng)的 URL 確定,如以下的方法:
@RequestMapping("/welcome.do")
public void welcomeHandler() {
}
對(duì)應(yīng)的邏輯視圖名為“ welcome ”
2
String
此時(shí)邏輯視圖名為返回的字符,如以下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
對(duì)應(yīng)的邏輯視圖名為“ ownerForm ”
3
org.springframework.ui.ModelMap
和返回類型為 void 一樣,邏輯視圖名取決于對(duì)應(yīng)請(qǐng)求的 URL ,如下面的例子:
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
對(duì)應(yīng)的邏輯視圖名為“ vets ”,返回的 ModelMap 將被作為請(qǐng)求對(duì)應(yīng)的模型對(duì)象,可以在 JSP 視圖頁面中訪問到。
4
org.springframework.web.servlet.ModelAndView
當(dāng)然還可以是傳統(tǒng)的 ModelAndView 。
具體使用請(qǐng)參考如下LoginController
Java代碼
package com.zhang.controller.anno;       import javax.servlet.ServletRequest;    import javax.servlet.http.HttpSession;       import org.springframework.stereotype.Controller;    import org.springframework.ui.ModelMap;    import org.springframework.validation.BindingResult;    import org.springframework.web.bind.annotation.ModelAttribute;    import org.springframework.web.bind.annotation.RequestMapping;    import org.springframework.web.bind.annotation.RequestMethod;    import org.springframework.web.bind.annotation.SessionAttributes;    import org.springframework.web.bind.support.SessionStatus;    import org.springframework.web.servlet.ModelAndView;    import org.springframework.web.servlet.view.RedirectView;       import com.zhang.bean.User;    import com.zhang.validator.UserValidator;       @Controller   // 聲明為Spring Bean    @SessionAttributes({ "usersession","testSession" })    // 將model特定屬性綁定到session中    public class LoginController {           /**        * 此方法判斷參數(shù)中是否包含"CE"字參數(shù),如果包換將CE參數(shù)放入Model中,并渲染login視圖        *         * 這里僅僅為測(cè)試使用,獲取Redirect后的URL參數(shù)放入model中再轉(zhuǎn)發(fā)出去        *         * @param request        * @param model        * @return        */       @RequestMapping(value = "/login2.htm", params = { "CE" }, method = RequestMethod.GET)        public String redirect(ServletRequest request, ModelMap model) {            model.addAttribute("user", new User());            String ce;            try {                ce = new String(request.getParameter("CE").getBytes("ISO-8859-1"),                        "utf8");                model.addAttribute("CE", ce);            } catch (Exception e) {                e.printStackTrace();            }               return "login";        }           /**        *         * 此方法為login.htm首頁面使用        *         * 因?yàn)閘ogin中需要User信息回顯(校驗(yàn)),故此處需必須傳入一個(gè)空User 否則頁面報(bào)異常        *         * @param request        * @param model        * @return        */       @RequestMapping(value = "/login2.htm", method = RequestMethod.GET)        public String test(ServletRequest request, ModelMap model) {            model.addAttribute("user", new User());            return "login";        }           /**        *         * @param session        *            Http Session        * @param user        *            表單模型User,@ModelAttribute表示user來源于model(request\session)        * @param result        *            表單驗(yàn)證結(jié)果,必須放在user之后        * @param model        *            數(shù)據(jù)模型        * @param status        *            可清除由@SessionAttributes定義的session范圍的屬性        * @return        */          @RequestMapping(value = "login2.htm", method = RequestMethod.POST)        public ModelAndView login(HttpSession session, ServletRequest request,                @ModelAttribute("user") User user, BindingResult result,                ModelMap model, SessionStatus status) {            ModelAndView ret = new ModelAndView();            // 驗(yàn)證用戶,此處UserValidator為自定義驗(yàn)證類            new UserValidator().validate(user, result);            if (!result.hasErrors()) {// 如果校驗(yàn)通過,重定向到指定頁面                model.addAttribute("CE", "測(cè)試");                ret.setView(new RedirectView("login.htm"));            } else {                ret.setViewName("login");            }               /*            * 測(cè)試@SessionAttributes            */              // 第一次為空            String sessionValue = (String) session.getAttribute("testSession");            System.out.println("sessionValue:" + sessionValue);            // 將值放入模型(request范圍),同時(shí)由于@SessionAttributes的作用,也放入了session范圍            model.addAttribute("testSession", "My_SessionValue");               /*            * 測(cè)試@SessionAttributes結(jié)束            */              // status.setComplete();//清除此次請(qǐng)求@SessionAttributes            // 指定的session值(此處沒有作用,因?yàn)閡ser并未綁定到session)            try {                // request.setCharacterEncoding("utf8");//可以使用此方法避免Post亂碼,或者配置filter            } catch (Exception e) {                e.printStackTrace();            }            return ret;        }    }
web.xml配置
Xml代碼
<?xml version="1.0" encoding="UTF-8"?>   <!-- 在tomcat5.5下運(yùn)行,需要使用Servlet 2.4版本(jstl1.1.jar,standard.jar)tomcat6可以使用默認(rèn)的2.5 -->   <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">       <display-name></display-name>          <!-- 注冊(cè)配置文件讀取器 -->       <listener>           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>       </listener>               <!-- 添加Spring過濾器,解決POST時(shí)亂碼問題,但GET方式需要自己手工處理 -->       <filter>           <filter-name>Set Character Encoding</filter-name>           <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>           <init-param>               <param-name>encoding</param-name>               <param-value>utf8</param-value>           </init-param>       </filter>       <filter-mapping>           <filter-name>Set Character Encoding</filter-name>           <url-pattern>/*</url-pattern>       </filter-mapping>          <!-- 配置文件列表,加載相關(guān)xml文件,其中springapp-servlet.xml可以不配置,DispatcherServlet配置中會(huì)自動(dòng)加載 -->       <context-param>           <param-name>contextConfigLocation</param-name>           <param-value>classpath:applicationContext.xml</param-value>       </context-param>             <!-- Spring MVC 的Servlet,它將加載WEB-INF/xxx-servlet.xml 的 配置文件,以啟動(dòng)Spring MVC模塊 -->       <servlet>           <servlet-name>springapp</servlet-name>           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>           <load-on-startup>1</load-on-startup>       </servlet>       <servlet-mapping>           <servlet-name>springapp</servlet-name>           <url-pattern>*.htm</url-pattern>       </servlet-mapping>          <!-- 使用Srping 標(biāo)簽時(shí)需配置 -->       <jsp-config>           <taglib>               <taglib-uri>/spring</taglib-uri>               <taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>           </taglib>       </jsp-config>          <welcome-file-list>           <welcome-file>index.jsp</welcome-file>       </welcome-file-list>   </web-app>
下面給出Spring MVC 相關(guān)配置文件
springapp-servlet.xml
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:p="http://www.springframework.org/schema/p"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-2.5.xsd">          <!-- 1:對(duì)web包中指定包中所有類進(jìn)行掃描,以完成Bean創(chuàng)建和自動(dòng)依賴注入的功能 -->       <context:component-scan base-package="com.zhang.controller.anno" />          <!-- 2:?jiǎn)?dòng)Spring MVC的注解功能,完成請(qǐng)求和注解POJO的映射 -->       <bean           class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />          <!-- Spirng 默認(rèn)啟動(dòng)三個(gè)apapter 如果自定義了一個(gè)會(huì)忽略其他的,當(dāng) beanNameUrlMapping 與annotation同時(shí)存在時(shí)要顯示聲明             所有 即:當(dāng)注解形式與聲明形式同時(shí)開發(fā)時(shí)需要執(zhí)行一下三行 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"             /> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"             /> <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"             /> -->             <!-- 3:對(duì)模型視圖名稱的解析,即在模型視圖名稱添加前后綴 -->       <bean id="viewResolver"           class="org.springframework.web.servlet.view.InternalResourceViewResolver">           <property name="viewClass">               <value>org.springframework.web.servlet.view.JstlView</value>           </property>           <property name="prefix">               <value>/WEB-INF/jsp/</value>           </property>           <property name="suffix">               <value>.jsp</value>           </property>       </bean>          <!-- 定義消息源,用于國(guó)際化 -->       <bean id="messageSource"           class="org.springframework.context.support.ResourceBundleMessageSource">           <property name="basename">               <value>messages</value>           </property>       </bean>   </beans>
視圖部分文件:
include.jsp
Java代碼
<%@ page session="false"%>    <%@ page isELIgnored ="true" %>    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
login.jsp
Java代碼
<%@ include file="/WEB-INF/jsp/include.jsp"%>    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>    <%@ page contentType="text/html; charset=utf8"%>    <html>        <head>            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />            <style type="text/css">    .error {        color: red;    }    </style>            <title>Login</title>        </head>        <body>            <form:form method="post" commandName="user">                <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0"                   cellpadding="5">                    <tr>                        <td align="left" width="30%">                            username:                            <form:input path="username" />                        </td>                           <td width="30%">                            <form:errors path="username" />                        </td>                    </tr>                    <tr>                        <td align="left" width="30%">                            password:                            <form:input path="password" />                        </td>                        <td width="30%">                            <form:errors path="password" />                        </td>                    </tr>                    <tr>                        <td>                            <form:errors path="validatorMessage" />                        </td>                    </tr>                   </table>                <input type="submit" value="Execute">            </form:form>            <a href="<c:url value="hello.htm"/>">Home</a>            <c:out value="${CE}"></c:out>        </body>    </html>
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
spring3 MVC實(shí)戰(zhàn),手工搭建Spring3項(xiàng)目demo
spring Mvc 教程框架實(shí)例以及系統(tǒng)演示下載
史上最全最強(qiáng)SpringMVC詳細(xì)示例實(shí)戰(zhàn)教程
Spring MVC3.0.5搭建全程
jsp中script引入url項(xiàng)目名${appName}或${app}等
使用annotation注解,整合DWR3 + Spring3 + Hibernate3
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服