一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|

服務器之家 - 編程語言 - JAVA教程 - 史上最全最強SpringMVC詳細示例實戰教程(圖文)

史上最全最強SpringMVC詳細示例實戰教程(圖文)

2020-07-09 11:16java教程網 JAVA教程

這篇文章主要介紹了史上最全最強SpringMVC詳細示例實戰教程(圖文),需要的朋友可以參考下

一、springmvc基礎入門,創建一個helloworld程序

  1.首先,導入springmvc需要的jar包。

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  2.添加web.xml配置文件中關于springmvc的配置

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--configure the setting of springmvcdispatcherservlet and configure the mapping-->
<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
  <init-param>
     <param-name>contextconfiglocation</param-name>
     <param-value>classpath:springmvc-servlet.xml</param-value>
   </init-param>
   <!-- <load-on-startup>1</load-on-startup> -->
</servlet>
 
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

  3.在src下添加springmvc-servlet.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
<?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:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">         
 
  <!-- scan the package and the sub package -->
  <context:component-scan base-package="test.springmvc"/>
 
  <!-- don't handle the static resource -->
  <mvc:default-servlet-handler />
 
  <!-- if you use annotation you must configure following setting -->
  <mvc:annotation-driven />
  
  <!-- configure the internalresourceviewresolver -->
  <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"
      id="internalresourceviewresolver">
    <!-- 前綴 -->
    <property name="prefix" value="/web-inf/jsp/" />
    <!-- 后綴 -->
    <property name="suffix" value=".jsp" />
  </bean>
</beans>

  4.在web-inf文件夾下創建名為jsp的文件夾,用來存放jsp視圖。創建一個hello.jsp,在body中添加“hello world”。

  5.建立包及controller,如下所示

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  6.編寫controller代碼

?
1
2
3
4
5
6
7
8
9
@controller
@requestmapping("/mvc")
public class mvccontroller {
 
  @requestmapping("/hello")
  public string hello(){   
    return "hello";
  }
}

  7.啟動服務器,鍵入 http://localhost:8080/項目名/mvc/hello

 二、配置解析

  1.dispatcherservlet

  dispatcherservlet是前置控制器,配置在web.xml文件中的。攔截匹配的請求,servlet攔截匹配規則要自已定義,把攔截下來的請求,依據相應的規則分發到目標controller來處理,是配置spring mvc的第一步。

  2.internalresourceviewresolver

  視圖名稱解析器

  3.以上出現的注解

  @controller 負責注冊一個bean 到spring 上下文中

  @requestmapping 注解為控制器指定可以處理哪些 url 請求

 三、springmvc常用注解

  @controller

  負責注冊一個bean 到spring 上下文中

  @requestmapping

  注解為控制器指定可以處理哪些 url 請求

  @requestbody

  該注解用于讀取request請求的body部分數據,使用系統默認配置的httpmessageconverter進行解析,然后把相應的數據綁定到要返回的對象上 ,再把httpmessageconverter返回的對象數據綁定到 controller中方法的參數上

  @responsebody

  該注解用于將controller的方法返回的對象,通過適當的httpmessageconverter轉換為指定格式后,寫入到response對象的body數據區

  @modelattribute    

  在方法定義上使用 @modelattribute 注解:spring mvc 在調用目標處理方法前,會先逐個調用在方法級上標注了@modelattribute 的方法

  在方法的入參前使用 @modelattribute 注解:可以從隱含對象中獲取隱含的模型數據中獲取對象,再將請求參數 –綁定到對象中,再傳入入參將方法入參對象添加到模型中 

  @requestparam 

  在處理方法入參處使用 @requestparam 可以把請求參 數傳遞給請求方法

  @pathvariable

  綁定 url 占位符到入參

  @exceptionhandler

  注解到方法上,出現異常時會執行該方法

  @controlleradvice

  使一個contoller成為全局的異常處理類,類中用@exceptionhandler方法注解的方法可以處理所有controller發生的異常

 四、自動匹配參數

?
1
2
3
4
5
6
//match automatically
@requestmapping("/person")
public string toperson(string name,double age){
  system.out.println(name+" "+age);
  return "hello";
}

 五、自動裝箱

  1.編寫一個person實體類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package test.springmvc.model;
 
public class person {
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public int getage() {
    return age;
  }
  public void setage(int age) {
    this.age = age;
  }
  private string name;
  private int age;
  
}

  2.在controller里編寫方法

?
1
2
3
4
5
6
//boxing automatically
@requestmapping("/person1")
public string toperson(person p){
  system.out.println(p.getname()+" "+p.getage());
  return "hello";
}

 六、使用initbinder來處理date類型的參數

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//the parameter was converted in initbinder
@requestmapping("/date")
public string date(date date){
  system.out.println(date);
  return "hello";
}
 
//at the time of initialization,convert the type "string" to type "date"
@initbinder
public void initbinder(servletrequestdatabinder binder){
  binder.registercustomeditor(date.class, new customdateeditor(new simpledateformat("yyyy-mm-dd"),
      true));
}

 七、向前臺傳遞參數

?
1
2
3
4
5
6
7
8
9
//pass the parameters to front-end
@requestmapping("/show")
public string showperson(map<string,object> map){
  person p =new person();
  map.put("p", p);
  p.setage(20);
  p.setname("jayjay");
  return "show";
}

  前臺可在request域中取到"p"

 八、使用ajax調用

?
1
2
3
4
5
6
7
8
9
//pass the parameters to front-end using ajax
@requestmapping("/getperson")
public void getperson(string name,printwriter pw){
  pw.write("hello,"+name);   
}
@requestmapping("/name")
public string sayhello(){
  return "name";
}

  前臺用下面的jquery代碼調用

?
1
2
3
4
5
6
7
$(function(){
  $("#btn").click(function(){
   $.post("mvc/getperson",{name:$("#name").val()},function(data){
      alert(data);
    });
  });
});

 九、在controller中使用redirect方式處理請求

?
1
2
3
4
5
//redirect
@requestmapping("/redirect")
public string redirect(){
  return "redirect:hello";
}

 十、文件上傳

  1.需要導入兩個jar包

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  2.在springmvc配置文件中加入

?
1
2
3
4
<!-- upload settings -->
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
  <property name="maxuploadsize" value="102400000"></property>
</bean>

  3.方法代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@requestmapping(value="/upload",method=requestmethod.post)
public string upload(httpservletrequest req) throws exception{
  multiparthttpservletrequest mreq = (multiparthttpservletrequest)req;
  multipartfile file = mreq.getfile("file");
  string filename = file.getoriginalfilename();
  simpledateformat sdf = new simpledateformat("yyyymmddhhmmss");   
  fileoutputstream fos = new fileoutputstream(req.getsession().getservletcontext().getrealpath("/")+
      "upload/"+sdf.format(new date())+filename.substring(filename.lastindexof('.')));
  fos.write(file.getbytes());
  fos.flush();
  fos.close();
  
  return "hello";
}

  4.前臺form表單

?
1
2
3
4
<form action="mvc/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="file"><br>
  <input type="submit" value="submit">
</form>

 十一、使用@requestparam注解指定參數的name

?
1
2
3
4
5
6
7
8
9
10
@controller
@requestmapping("/test")
public class mvccontroller1 {
  @requestmapping(value="/param")
  public string testrequestparam(@requestparam(value="id") integer id,
      @requestparam(value="name")string name){
    system.out.println(id+" "+name);
    return "/hello";
  
}

 十二、restful風格的sringmvc

  1.restcontroller

?
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
@controller
@requestmapping("/rest")
public class restcontroller {
  @requestmapping(value="/user/{id}",method=requestmethod.get)
  public string get(@pathvariable("id") integer id){
    system.out.println("get"+id);
    return "/hello";
  }
  
  @requestmapping(value="/user/{id}",method=requestmethod.post)
  public string post(@pathvariable("id") integer id){
    system.out.println("post"+id);
    return "/hello";
  }
  
  @requestmapping(value="/user/{id}",method=requestmethod.put)
  public string put(@pathvariable("id") integer id){
    system.out.println("put"+id);
    return "/hello";
  }
  
  @requestmapping(value="/user/{id}",method=requestmethod.delete)
  public string delete(@pathvariable("id") integer id){
    system.out.println("delete"+id);
    return "/hello";
  }
  
}

  2.form表單發送put和delete請求

  在web.xml中配置

?
1
2
3
4
5
6
7
8
9
<!-- configure the hiddenhttpmethodfilter,convert the post method to put or delete -->
<filter>
  <filter-name>hiddenhttpmethodfilter</filter-name>
  <filter-class>org.springframework.web.filter.hiddenhttpmethodfilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>hiddenhttpmethodfilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

  在前臺可以用以下代碼產生請求

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form action="rest/user/1" method="post">
  <input type="hidden" name="_method" value="put">
  <input type="submit" value="put">
</form>
 
<form action="rest/user/1" method="post">
  <input type="submit" value="post">
</form>
 
<form action="rest/user/1" method="get">
  <input type="submit" value="get">
</form>
 
<form action="rest/user/1" method="post">
  <input type="hidden" name="_method" value="delete">
  <input type="submit" value="delete">
</form>

 十三、返回json格式的字符串

  1.導入以下jar包

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  2.方法代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@controller
@requestmapping("/json")
public class jsoncontroller {
  
  @responsebody
  @requestmapping("/user")
  public user get(){
    user u = new user();
    u.setid(1);
    u.setname("jayjay");
    u.setbirth(new date());
    return u;
  }
}

 十四、異常的處理

  1.處理局部異常(controller內)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@exceptionhandler
public modelandview exceptionhandler(exception ex){
  modelandview mv = new modelandview("error");
  mv.addobject("exception", ex);
  system.out.println("in testexceptionhandler");
  return mv;
}
 
@requestmapping("/error")
public string error(){
  int i = 5/0;
  return "hello";
}

  2.處理全局異常(所有controller)

?
1
2
3
4
5
6
7
8
9
10
@controlleradvice
public class testcontrolleradvice {
  @exceptionhandler
  public modelandview exceptionhandler(exception ex){
    modelandview mv = new modelandview("error");
    mv.addobject("exception", ex);
    system.out.println("in testcontrolleradvice");
    return mv;
  }
}

  3.另一種處理全局異常的方法

  在springmvc配置文件中配置

?
1
2
3
4
5
6
7
8
<!-- configure simplemappingexceptionresolver -->
<bean class="org.springframework.web.servlet.handler.simplemappingexceptionresolver">
  <property name="exceptionmappings">
    <props>
      <prop key="java.lang.arithmeticexception">error</prop>
    </props>
  </property>
</bean>

  error是出錯頁面

 十五、設置一個自定義攔截器

  1.創建一個myinterceptor類,并實現handlerinterceptor接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class myinterceptor implements handlerinterceptor {
 
  @override
  public void aftercompletion(httpservletrequest arg0,
      httpservletresponse arg1, object arg2, exception arg3)
      throws exception {
    system.out.println("aftercompletion");
  }
 
  @override
  public void posthandle(httpservletrequest arg0, httpservletresponse arg1,
      object arg2, modelandview arg3) throws exception {
    system.out.println("posthandle");
  }
 
  @override
  public boolean prehandle(httpservletrequest arg0, httpservletresponse arg1,
      object arg2) throws exception {
    system.out.println("prehandle");
    return true;
  }
 
}

  2.在springmvc的配置文件中配置

?
1
2
3
4
5
6
7
<!-- interceptor setting -->
<mvc:interceptors>
  <mvc:interceptor>
    <mvc:mapping path="/mvc/**"/>
    <bean class="test.springmvc.interceptor.myinterceptor"></bean>gt;
  </mvc:interceptor>   
</mvc:interceptors>

  3.攔截器執行順序

史上最全最強SpringMVC詳細示例實戰教程(圖文)

 十六、表單的驗證(使用hibernate-validate)及國際化

  1.導入hibernate-validate需要的jar包

史上最全最強SpringMVC詳細示例實戰教程(圖文)

(未選中不用導入)

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  2.編寫實體類user并加上驗證注解

?
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
public class user {
  public int getid() {
    return id;
  }
  public void setid(int id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public date getbirth() {
    return birth;
  }
  public void setbirth(date birth) {
    this.birth = birth;
  }
  @override
  public string tostring() {
    return "user [id=" + id + ", name=" + name + ", birth=" + birth + "]";
  
  private int id;
  @notempty
  private string name;
 
  @past
  @datetimeformat(pattern="yyyy-mm-dd")
  private date birth;
}

  ps:@past表示時間必須是一個過去值

  3.在jsp中使用springmvc的form表單

?
1
2
3
4
5
6
<form:form action="form/add" method="post" modelattribute="user">
  id:<form:input path="id"/><form:errors path="id"/><br>
  name:<form:input path="name"/><form:errors path="name"/><br>
  birth:<form:input path="birth"/><form:errors path="birth"/>
  <input type="submit" value="submit">
</form:form>

  ps:path對應name

  4.controller中代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@controller
@requestmapping("/form")
public class formcontroller {
  @requestmapping(value="/add",method=requestmethod.post) 
  public string add(@valid user u,bindingresult br){
    if(br.geterrorcount()>0){     
      return "adduser";
    }
    return "showuser";
  }
  
  @requestmapping(value="/add",method=requestmethod.get)
  public string add(map<string,object> map){
    map.put("user",new user());
    return "adduser";
  }
}

  ps:

  1.因為jsp中使用了modelattribute屬性,所以必須在request域中有一個"user".

  2.@valid 表示按照在實體上標記的注解驗證參數

  3.返回到原頁面錯誤信息回回顯,表單也會回顯

  5.錯誤信息自定義

  在src目錄下添加locale.properties

?
1
2
3
4
5
notempty.user.name=name can't not be empty
past.user.birth=birth should be a past value
datetimeformat.user.birth=the format of input is wrong
typemismatch.user.birth=the format of input is wrong
typemismatch.user.id=the format of input is wrong

  在springmvc配置文件中配置

?
1
2
3
4
<!-- configure the locale resource -->
<bean id="messagesource" class="org.springframework.context.support.resourcebundlemessagesource">
  <property name="basename" value="locale"></property>
</bean>

  6.國際化顯示

  在src下添加locale_zh_cn.properties

?
1
2
username=賬號
password=密碼

  locale.properties中添加

?
1
2
username=user name
password=password

  創建一個locale.jsp

?
1
2
3
4
<body>
 <fmt:message key="username"></fmt:message>
 <fmt:message key="password"></fmt:message>
</body>

  在springmvc中配置

?
1
2
<!-- make the jsp page can be visited -->
<mvc:view-controller path="/locale" view-name="locale"/>

  讓locale.jsp在web-inf下也能直接訪問

  最后,訪問locale.jsp,切換瀏覽器語言,能看到賬號和密碼的語言也切換了

 十七、壓軸大戲--整合springioc和springmvc

  1.創建一個test.springmvc.integrate的包用來演示整合,并創建各類

史上最全最強SpringMVC詳細示例實戰教程(圖文)

  2.user實體類

?
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
public class user {
  public int getid() {
    return id;
  }
  public void setid(int id) {
    this.id = id;
  }
  public string getname() {
    return name;
  }
  public void setname(string name) {
    this.name = name;
  }
  public date getbirth() {
    return birth;
  }
  public void setbirth(date birth) {
    this.birth = birth;
  }
  @override
  public string tostring() {
    return "user [id=" + id + ", name=" + name + ", birth=" + birth + "]";
  
  private int id;
  @notempty
  private string name;
 
  @past
  @datetimeformat(pattern="yyyy-mm-dd")
  private date birth;
}

  3.userservice類

?
1
2
3
4
5
6
7
8
9
10
@component
public class userservice {
  public userservice(){
    system.out.println("userservice constructor...\n\n\n\n\n\n");
  }
  
  public void save(){
    system.out.println("save");
  }
}

  4.usercontroller

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@controller
@requestmapping("/integrate")
public class usercontroller {
  @autowired
  private userservice userservice;
  
  @requestmapping("/user")
  public string saveuser(@requestbody @modelattribute user u){
    system.out.println(u);
    userservice.save();
    return "hello";
  }
}

  5.spring配置文件

  在src目錄下創建springioc的配置文件applicationcontext.xml

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    "
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    >
  <context:component-scan base-package="test.springmvc.integrate">
    <context:exclude-filter type="annotation"
      expression="org.springframework.stereotype.controller"/>
    <context:exclude-filter type="annotation"
      expression="org.springframework.web.bind.annotation.controlleradvice"/>   
  </context:component-scan>
  
</beans>

  在web.xml中添加配置

?
1
2
3
4
5
6
7
8
<!-- configure the springioc -->
<listener>
  <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
</listener>
<context-param>
 <param-name>contextconfiglocation</param-name>
 <param-value>classpath:applicationcontext.xml</param-value>
</context-param>

  6.在springmvc中進行一些配置,防止springmvc和springioc對同一個對象的管理重合

?
1
2
3
4
5
6
7
<!-- scan the package and the sub package -->
  <context:component-scan base-package="test.springmvc.integrate">
    <context:include-filter type="annotation"
      expression="org.springframework.stereotype.controller"/>
    <context:include-filter type="annotation"
      expression="org.springframework.web.bind.annotation.controlleradvice"/>
  </context:component-scan>

 十八、springmvc詳細運行流程圖

史上最全最強SpringMVC詳細示例實戰教程(圖文)

 十九、springmvc與struts2的區別

  1、springmvc基于方法開發的,struts2基于類開發的。springmvc將url和controller里的方法映射。映射成功后springmvc生成一個handler對象,對象中只包括了一個method。方法執行結束,形參數據銷毀。springmvc的controller開發類似web service開發。

  2、springmvc可以進行單例開發,并且建議使用單例開發,struts2通過類的成員變量接收參數,無法使用單例,只能使用多例。

  3、經過實際測試,struts2速度慢,在于使用struts標簽,如果使用struts建議使用jstl。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品igao视频网网址 | 男gay网站视频免费观看 | 美女伊人网 | 亚洲天堂影院 | 国产精品99久久免费观看 | 日韩精品高清自在线 | 天天曰天天干 | 成熟女人50岁一级毛片不卡 | 日本视频在线免费播放 | 91麻豆国产精品91久久久 | 免费观看www视频 | 扒开胸流出吃奶 | 图片专区小说专区卡通动漫 | 精品国产区一区二区三区在线观看 | 古代翁熄系小说辣文 | 欧美一区二区三区gg高清影视 | 成年人免费观看 | 四虎成人国产精品视频 | 国产亚洲精aa在线观看不卡 | 国产90后美女露脸在线观看 | 男插女的下面免费视频夜色 | ass亚洲熟妇毛茸茸pics | 俄罗斯女同和女同xx | 456亚洲老头视频 | 亚洲精品丝袜在线一区波多野结衣 | 精品国产免费久久久久久 | 青草草在线 | 美女逼逼软件 | 国产综合色在线视频区色吧图片 | 精品久久成人 | 新影音先锋男人色资源网 | 99在线精品视频 | 好大好爽好涨太深了小喜 | 99看视频| 久久丫线这里只精品 | 亚洲乱亚洲乱妇41p 亚洲乱码一区二区三区国产精品 | 久久精品国产清白在天天线 | 秋霞理论一级在线观看手机版 | 咪咪爱在线视频 | avav男人天堂 | 四虎影院久久 |