1.SpringMVCの基本を始める、HelloWorldプログラムを作成する
1.最初に、SpringMVCが必要とするJARパッケージをインポートします。
2。web.xml構成ファイルにspringmvcに関する構成を追加します
<! - springmvcdispatcherservletの設定を構成し、マッピングを構成します - > <servlet> <servlet-name> springmvc </servlet-class> org.springframework.web.servlet.dispatcherservlet> <param-value> classpath:springmvc-servlet.xml </param-value> </init-param> <! - <load-on-startup> 1 </load-on-startup> - > </servlet> <servlet-name> springmvc </servlet-name> <url-pittern>
3。SRCの下にSpringMVC-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:Context = "http://www.springframework.org/schema/context" xmlns:mvc = "http://www.springframework.org/schema/mvc" xsi:schemalocation = " http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-contex http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd "> <! - パッケージとサブパッケージをSCAN-> <静的リソース - > <MVC:デフォルト - サーブレットハンドラー /> <! - アノテーションを使用する場合は、次の設定を設定する必要があります - > <MVC:annotation-driven /> <! - internalResourceViewResolver-> <bean id = "internalResourceViewResolver"> < <プロパティ名= "suffix" value = "。jsp"/> </bean> </bean>
4.Web-INFフォルダーにJSPという名前のフォルダーを作成して、JSPビューを保存します。 hello.jspを作成し、あなたの体に「hello world」を追加します。
5.以下に示すように、パッケージとコントローラーを作成します
6.コントローラーコードを書き込みます
@controller @requestmapping( "/mvc")public class mvccontroller {@requestmapping( "/hello")public string hello(){return "hello"; }}7.サーバーを起動し、http:// localhost:8080/project name/mvc/helloと入力します
1.DispatcherServlet
DispatcherServletは、web.xmlファイルで構成されたプリコントローラーです。一致するリクエストの傍受。一致するルールを傍受するサーブレットの傍受は、それ自体で定義する必要があります。傍受された要求は、処理の対応するルールに従ってターゲットコントローラーに配布されます。これは、スプリングMVCの構成の最初のステップです。
2. InternalresourceViewResolver
名前のリゾルバーを表示します
3。上記の注釈
@Controllerは、Beanをスプリングコンテキストに登録する責任があります
@RequestMappingアノテーションコントローラーのためにどのURL要求を処理できるかを指定します
@コントローラ
Beanを春のコンテキストに登録する責任があります
@RequestMapping
注釈は、どのURL要求をコントローラー用に処理できるかを指定します
@RequestBody
この注釈は、リクエスト要求のボディデータの一部を読み取るために使用され、システムによって構成されたhttpmessageconverterを使用して解析用に使用し、対応するデータをオブジェクトにバインドしてから、httpmessageconverterによって返されるオブジェクトデータをコントロールラーラーのパラメーターにバインドします。
@ResponseBody
この注釈は、適切なhttpmessageConverterに指定された形式に変換した後、応答オブジェクトのボディデータ領域にコントローラーメソッドによって返されるオブジェクトを書き込むために使用されます
@modelattribute
メソッド定義で@modelattributeアノテーションを使用:スプリングMVCターゲット処理メソッドを呼び出す前に、メソッドレベルで@modelattributeを注釈する方法は1つずつ呼び出されます。
メソッドパラメーターを入力する前に@modelattributeアノテーションを使用します。暗黙のオブジェクトからオブジェクトを取得し、要求パラメーターをオブジェクトにバインドし、メソッドをパラメーターオブジェクトに渡してモデルにメソッドを追加できます。
@RequestParam
@RequestParamを使用して、リクエストパラメーターをリクエストメソッドに渡す
@pathvariable
URLプレースホルダーを入力パラメーターにバインドします
@exceptionhandler
メソッドで注釈が付けられて、例外が発生するとメソッドが実行されます
@ControllerAdvice
コントローラーをグローバル例外処理クラスにします。クラスの@exceptionHandlerメソッドで注釈が付けられたメソッドは、コントローラーで発生するすべての例外を処理できます。
//自動的に@RequestMapping( "/person")public string toperson(string name、double age){system.out.println(name+""+age); 「こんにちは」を返します。 }1.個人エンティティクラスを書いてください
パッケージ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; }プライベート文字列名;プライベートインクエイジ; }2。コントローラーにメソッドを書き込みます
//自動的に@RequestMapping( "/person1")public string toperson(person p){system.out.println(p.getname()+""+p.getage()); 「こんにちは」を返します。 }//パラメーターはinitbinder @requestmapping( "/date")public string date(date date){system.out.println(date);で変換されました。 「こんにちは」を返します。 } //初期化の時点で、型「文字列」を「string」@initbinder public void initbinder(servletrequestdatabinder binder)に変換します。 }//パラメーターをフロントエンドに渡します@RequestMapping( "/show")public string showserson(map <string、object> map){person p = new person(); map.put( "p"、p); P.Setage(20); P.SetName( "Jayjay"); 「show」を返します。 }フロントデスクはリクエストドメインで「P」を取得できます
// ajax @requestmapping( "/getPerson")public void getPerson(string name、printwriter pw){pw.write( "hello、"+name); } @RequestMapping( "/name")public string sayshello(){return "name"; }フロントデスクは次のjQueryコードでそれを呼び出します
$(function(){$( "#btn")。クリック(function(){$ .post( "mvc/getPerson"、{name:$( "#name")。val()}、function(data){alert(data);});});});// Redirect @RequestMapping( "/redirect")public string redirect(){return "redirect:hello"; }1. 2つのJARパッケージをインポートする必要があります
2。SpringMVC構成ファイルを追加します
<! - アップロード設定 - > <bean id = "multipartresolver"> <プロパティ名= "maxuploadsize" value = "102400000"> </property> </bean>
3。メソッドコード
@RequestMapping(value = "/upload"、method = requestmethod.post)public string upload(httpservletrequest req)スロー例外{multiparthttpservletrequest mreq =(multiparthttpservletrequest)req; MultiPartFile file = mreq.getFile( "ファイル"); string filename = file.getoriginalFileName(); SimpleDateFormat sdf = new SimpledateFormat( "yyyymmddhhmmss"); fileoutputStream fos = new fileoutputStream(req.getSession()。getRealPath( "/")+"upload/"+sdf.format(new date())+filename.substring(filename.lastindexof( '。')); fos.write(file.getBytes()); fos.flush(); fos.close(); 「こんにちは」を返します。 }4。フロントデスクフォーム
<form action = "mvc/upload" method = "post" enctype = "multipart/form-data"> <入力タイプ= "file" name = "file"> <br> <入力タイプ= "submit" value = "submit"> </form>
@controller @requestmapping( "/test")public class mvccontroller1 {@requestmapping(value = "/param")public string testrequestparam(@requestparam(value = "id")integer id、 @requestparam(value = "name")string name){system.out.out.out.out.out; "/hello"を返します。 }}1.RestController
@controller@requestmapping( "/ret")public class restcontroller {@requestmapping(value = "/user/{id}"、method = requestmethod.get)public string get(@pathvariable( "id")integer id){system.out.println( "get"+id); "/hello"を返します。 } @RequestMapping(value = "/user/{id}"、method = requestmethod.post)public string post( @pathvariable( "id")integer id){system.out.println( "post"+id); "/hello"を返します。 } @RequestMapping(value = "/user/{id}"、method = requestmethod.put)public string put( @pathvariable( "id")integer id){system.out.println( "put"+id); "/hello"を返します。 } @requestMapping(value = "/user/{id}"、method = requestmethod.delete)public string delete( @pathvariable( "id")integer id){system.out.println( "delete"+id); "/hello"を返します。 }}2.フォームは、リクエストを送信および削除します
web.xmlで構成します
<! - hiddenhttpmethodfilterを構成し、postメソッドを置くか削除するように変換 - > <filter> <filter-name> hiddenhttpmethodfilter </filter-name> <filter-class> org.springframework.web.filter.hiddenhttpmethodfilter < <filter-name> hiddenhttpmethodfilter </filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
手前では、次のコードを使用してリクエストを生成できます
<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="post"> <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>
1.次のJARパッケージをインポートします
2。メソッドコード
@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()); uを返します。 }}1.ローカルの例外を処理する(コントローラー内)
@exceptionHandler public ModelandView ExceptionHandler(Exception ex){modelandView MV = new ModelAndView( "ERROR"); mv.addobject( "Exception"、ex); system.out.println( "in testexceptionhandler"); MVを返します。 } @RequestMapping( "/error")public string error(){int i = 5/0; 「こんにちは」を返します。 }2。グローバル例外(すべてのコントローラー)を処理する
@ControllerAdvicePublic Class TestControllerAdvice {@exceptionHandler public ModelandView ExceptionHandler(Exception ex){ModelandView MV = new ModelAndView( "ERROR"); mv.addobject( "Exception"、ex); System.out.println( "In testControllerAdvice"); MVを返します。 }}3.グローバルな例外に対処する別の方法
SpringMVC構成ファイルで構成します
<! - simplemappingexceptionResolver - > <bean> <プロパティ名= "excepsionmappings"> <props> <prop key = "java.lang.arithmeticexception">エラー</prop> </props> </jeber> </bean> </bean>
エラーはエラーページです
1. MyInterceptorクラスを作成し、HandlerInterceptorインターフェイスを実装します
パブリッククラスMyInterceptorは、HandlerInterceptorを実装します{@Override public void aftercompletion(httpservletrequest arg0、httpservletresponse arg1、object arg2、例外arg3)をスロー{system.out.println( "afcompleted"); } @Override public void posthandle(httpservletrequest arg0、httpservletresponse arg1、object arg2、modelandview arg3)をスロー{system.out.println( "posthandle"); } @Override public boolean prehandle(httpservletrequest arg0、httpservletresponse arg1、object arg2)strows {system.out.println( "prehandle"); trueを返します。 }}2。springmvc構成ファイルで構成します
<! - インターセプター設定 - > <MVC:インターセプター> <MVC:インターセプター> <MVC:マッピングpath = "/mvc/**"/> <bean> </bean> gt; </MVC:インターセプター> </MVC:インターセプター>
3.インターセプター実行順序
1. Hibernate-Validateで必要なJARパッケージをインポートします
(選択されていない、インポートする必要はありません)
2。エンティティクラスユーザーを書き込み、検証アノテーションを追加します
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(日付出生){this.birth = birth; } @Override public String toString(){return "user [id =" + id + "、name =" + name + "、birth =" + birts + "]"; } private int id; @notemptyプライベート文字列名; @past @datetimeformat(pattern = "yyyy-mm-dd")private date birt;}PS:@pastは、時間が過去の価値でなければならないことを意味します
3。JSPでSpringMVCのフォームを使用します
<form Action = "form/add" method = "modelattribute =" user "> id:<form:input path =" id "/> <form:errors path =" id "/> <br> name:<form:form =" name "/> <form:errors path =" name "/> <br> birth = <form ="/> <form "/>> <form"/>> <form "/>> <form" path = "birth"/> <form:errors path = "birth"/> <form:errors path = "birth"/> <input type = "submit" value = "submit"> </form>
PS:名前に対応するパス
4。コントローラーのコード
@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"; }「showuser」を返します。 } @requestMapping(value = "/add"、method = requestmethod.get)public string add(map <string、object> map){map.put( "user"、new user()); 「adduser」を返します。 }}PS:
1. ModelAttribute属性はJSPで使用されるため、リクエストドメインに「ユーザー」が必要です。
2.@有効な手段エンティティにマークされた注釈に従ってパラメーターを検証する
3。元のページに戻って再拡張すると、フォームも再発現します。
5.エラーメッセージをカスタマイズします
SRCディレクトリにLocale.Propertiesを追加します
notempty.user.name = name beemhtypast.user.user.birth =出生は過去のVoluedateTimeformat.user.user.birthである必要があります=入力の形式は誤っています。
SpringMVC構成ファイルで構成します
<! - ロケールリソースの構成 - > <bean id = "sassageSource"> <プロパティname = "basename" value = "locale"> </property> </bean>
6。国際的なディスプレイ
srcの下にlocale_zh_cn.propertiesを追加します
username =アカウントパスワード=パスワード
locale.propertiesに追加されました
username = user namepassword =パスワード
locale.jspを作成します
<body> <fmt:message key = "username"> </fmt:message> <fmt:message key = "password"> </fmt:message> </body>
springmvcで構成します
<! - jspページにアクセスできるようにする - > <mvc:view-controller path = "/locale" view-name = "locale"/>
locale.jspをWeb-infで直接アクセスします
最後に、locale.jspにアクセスして、ブラウザ言語を切り替え、アカウントとパスワードを見ることができる言語も切り替えられています。
1. test.springmvc.Integrateパッケージを作成して統合を示し、さまざまなタイプを作成します
2.ユーザーエンティティクラス
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(日付出生){this.birth = birth; } @Override public String toString(){return "user [id =" + id + "、name =" + name + "、birth =" + birts + "]"; } private int id; @notemptyプライベート文字列名; @past @datetimeformat(pattern = "yyyy-mm-dd")private date birt;}3.UserServiceクラス
@componentPublic class userservice {public userservice(){system.out.println( "userservice constructor .../n/n/n/n/n/n/n/n/n/n"); } public void save(){system.out.println( "save"); }}4.USERCONTROLLER
@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(); 「こんにちは」を返します。 }}5.Spring構成ファイル
SRCディレクトリにSpringioC構成ファイルApplicationContext.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" xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/util http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " xmlns:p = "http://www.springframework.org/schema/p" xmlns:context = "http://www.springframework.org/schema/context"> <context:component-scan base-package = "ext.springmvc.integrate"> type = "annotation" expression = "org.springframework.stertype.controller"/> <context:explude-filter type = "annotation" expression = "org.springframework.web.annotation.controlleradvice"/>> </context:component-scan> </beans>
web.xmlに構成を追加します
<! - springiocを構成 - > <リスナー> <リスナークラス> org.springframework.web.context.contextloaderlistener </ristener-class> </context-name> contextconfiglocation </parm-name> <param-value:classContext.xml </paramvalue>
6. SpringMVCとSpringIOCが同じオブジェクトの管理を重複させないように、SpringMVCで構成を作成します
<! - パッケージとサブパッケージをスキャン - > <コンテキスト:Component-ScanScansaber-Package = "test.springmvc.integrate"> <context:inclute-filter type = "annotation" expression = "org.springframework.tertype.controller"/> <context:includ-filter type = "annotation" expression = "org.springframework.web.bind.annotation.controlleradvice"/> </context:component-scan>
1。SprutMVCはメソッドに基づいて開発され、Struts2はクラスに基づいて開発されます。 SpringMVCは、コントローラーのURLとメソッドをマップします。マッピングが成功した後、SpringMVCはメソッドのみを含むハンドラーオブジェクトを生成します。メソッドの実行が終了し、正式なパラメーターデータが破壊されます。 SpringMVCのコントローラー開発は、Webサービス開発に似ています。
2。SpringMVCはSingleton Developmentを実行でき、Singleton Developmentを使用することをお勧めします。 Struts2は、クラスのメンバー変数を介してパラメーターを受信します。 Singletonは使用できません。複数のケースのみを使用できます。
3。実際のテストの後、Struts2はStrutsタグを使用するため、遅いです。 Strutsを使用する場合は、JSTLを使用することをお勧めします。