春の学習実際には、このシリーズの究極の目標は、ユーザーの登録とログイン機能を実装するプロジェクトを完了することです。
予想される基本プロセスは次のとおりです。
1.ユーザーWebサイトを登録し、ユーザー名、パスワード、電子メール、および携帯電話番号情報を入力し、バックグラウンドのデータベースにデポジットした後、OKを返します。 (IOC、MyBatis、SpringMVC、フォームデータ検証、ファイルアップロードなどの基本的な知識を学びます。)
2.サーバーは、登録ユーザーに非同期に電子メールを送信します。 (メッセージキューを学ぶ)
3。ユーザーログイン。 (学習キャッシュ、スプリングセキュリティ)
4。その他。
研究と要約、および時々更新します。プロジェクト環境はIntellij + Spring4です。
1。準備作業。
1. mysqlでデータベースとテーブルを作成します。
2。IntellijでMaven WebAppプロジェクトを作成します。
(1)pom.xmlに必要な依存関係パッケージをインポートします。
<?xml version = "1.0" encoding = "utf-8"?> <プロジェクトxmlns = "http://maven.apache.org/pom/4.0.0" xmlns:xsi = "http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation = "http://maven.apache.org/4.0. http://maven.apache.org/xsd/maven-4.0.0.xsd "> <modelversion> 4.0.0 </modelversion> <groupid> com.everseeker < /groupid> <artifactid> register</artifactid> <packaging>war</packaging> <version>1.0</version> <name> register Maven webApp </name> <url> http://maven.apache.org </url> <properties> <spring.version> 4.3.1.release </spring.version> </properties> <コンテキスト - > <依存関係> <groupId> org.springframework </groupid> <artifactid> spring-context </artifactid> <version> $ {spring.version} </version> </dependency> <ependency> org.springframework </groupid> <artifa ctid> spring-context-support </artifactid> <version> $ {spring.version} </version> </dependency> <dependency> <expendency> <groupid> org.springframework </groupid> <artifactid> spring-core </artifactid> <バージョン> $ {spring.version} </ve rsion> </dependency> <dependency> <groupid> org.springframework </groupid> <artifactid> spring-beans </artifactid> <バージョン> $ {spring.version} </version> </depence> < tifactid> junit </artifactid> <バージョン> 4.12 </version> <! - <scope> test </scope> - > </dependency> <dependency> <groupid> org.springframework </groupid> <artifactid> spring-test </artifactid> <バージョン> {spring.version} </ve rsion> </dependency> <! - springmvc-> <dependency> groupid> org.springframework </groupid> <artifactid> spring-webmvc </artifactid> <version> $ {spring.version} </version> </dependency> <redency> org.springfr amework </groupid> <artifactid> spring-web </artifactid> <version> $ {spring.version} </version} </dependency> <dependency> javax.validation </groupid> <artifactid> validation-api </artifactid> <バージョン> 1.0.fin al </version> </dependency> <dependency> <groupid> org.hibernate </groupid> <artifactid> hibernate-validator </artifactid> <bersion> 5.2.4.final </version> </depence> <! - サーブレット - > <依存関係> <依存関係> javax.servlet < /groupid> <artifactid> javax.servlet-api</artifactid> <version>3.1.0</version> </dependency> <dependency> <groupid> javax.servlet.servlet.> <artifactid> jstl</artifactid> <version>.2</version> mybatis - > <dependency> groupid> org.springframework </groupid> <artifactid> spring-jdbc </artifactid> <bersion> $ {spring.version} </version} </dependency> <dependency> <groupid> mysql </groupid> <artifactid> mysql-connector-java </artifactid> id> <version> 6.0.3 </version> </dependency> <dependency> <groupid> org.mybatis </groupid> <artifactid> mybatis </artifactid> <バージョン> 3.4.1 </version> </dependency> <依存関係> <groupid> org.mybatis </groupid> <artifactid> mybatis-spring ifactid> <bersion> 1.3.0 </version> </dependency> <dependency> <segrougid> c3p0 </groupid> <artifactid> c3p0 </artifactid> <バージョン> 0.9.1.2 </version> </dependency> </dependencies> <build> <build> <finalname> java_config_web </finalname> <plugin n> <groupid> org.apache.maven.plugins </groupid> <artifactid> maven-war-plugin </artifactid> <version> 2.2 </version> <configuration> <failonmissingwebxml> false </faileonmissingwebxml> </configuration> </plumin> </bulicins> </butivins> (2)プロジェクトディレクトリ構造は次のとおりです。
2。マイバティス
1。MySQLデータベースの基本情報を構成します。
#databasedb.mysql.driverclass = com.mysql.jdbc.driverdb.mysql.jdbcurl = jdbc:mysql:// localhost:3306/registy_notice?useunicode = true&charaterencoding = utf-8&aoptemultiqueries = truedb.mysql.user = rootdb.mysql.password = 333db.minPoolSize = 10db.maxPoolSize = 100db.initialPoolSize = 20db.maxIdleTime = 60db.acquireIncrement = 5db.maxStatements = 100db.idleConnectionTestPeriod = 60db.acquireRetryAttempts = 30db.breakafteracquirefailure = truedb.testConnectionOnCheckout = falsedB.Properties
2。mybatis.xmlとspring-mybatis.xmlを構成します。
<?xml version = "1.0" encoding = "utf-8"?> <!doctype configurationpublic " - // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtdエイリアス - > <typealiase> <! - 次の2つの方法のいずれかを選択します。方法1:TypeAliasを使用して、単一のクラスのエイリアスを設定します。 - > <! - <typealias type = "com.everseeker.entity.user" alias = "user" /> ---メソッド2:パッケージを使用してパッケージの下のすべてのクラスのエイリアスを設定します。デフォルトのルールはcom.everseeker.entity.userがユーザーに設定され、前のパッケージ名を削除します。 - > <パッケージname = "com.everseeker.entity" /></typealiase></configuration> mybatis.xml<?xmlバージョン= "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://ww.springframework. /schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:p="http://www.springframework.org/schema/p"xsi: ringframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.spring framework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/tx/spring-tx.xsd"> <!-----------このファイルにdb.propertiesファイルを導入すると、対応する値が$ {db.mysql.driverclass}などの後続の構成にあることを確認できます。そうしないと、db.propertiesとspring-mybatis.xmlがrootconfig.javaでdb.propertiesに保証できない場合、spring-mybatis.xmlがエラー - > <コンテキスト:プロパティプレイスホルダーlocation = "classpath:db.properties"/> <! - データソース構成c3p0には2つの共通データソース実装クラスパッケージがあります。 - > <bean id = "dataSource" Destroy-method = "close"> <プロパティ名= "driverclass" value = "$ {db.mysql.driverclass}" /> <プロパティ名= "jdbcurl" value = "$ {db.mysql.jdbcurl}" /> <Property name = "password" value = "$ {db.mysql.password}" /> <! - 接続プールに保持されている接続の最小数。 - > <プロパティname = "minpoolsize" value = "$ {db.minpoolsize}" /> <! - 接続プールに保持されている接続の最大数。デフォルト:15-> <プロパティ名= "maxpoolsize" value = "$ {db.maxpoolsize}" /> <! - 初期化中に得られた接続の数は、Minpoolsizeとmaxpoolsizeの間である必要があります。デフォルト:3-> <プロパティname = "initialpoolsize" value = "$ {db.initialpoolsize}" /> <! - 最大自由時間は60秒以内に使用されない場合、接続は破棄されます。 0の場合、破棄されることはありません。デフォルト:0-> <プロパティ名= "maxidletime" value = "$ {db.maxidletime}" /> <! - 接続プールの接続が使い果たされたときに一度にC3P0によって得られた接続の数。デフォルト:3-> <プロパティname = "acchireincrement" value = "$ {db.acquireincrement}" /> <! - jdbcの標準パラメーターを使用して、データソースにロードされた準備の数を制御します。ただし、Precacheステートメントは、接続プール全体ではなく、単一の接続に属しているためです。したがって、このパラメーターを設定するには、多くの要因を考慮する必要があります。 maxStatementsとmaxstatementsperconnectionの両方が0の場合、キャッシュは閉じられます。デフォルト:0-> <プロパティ名= "maxstatements" value = "$ {db.maxstatements}" /> <! - 60秒ごとに接続プールのすべての接続を確認します。デフォルト:0-> <プロパティ名= "idleconnectionTestPeriod" value = "$ {db.idleconnectionTestPeriod}" /> <! - 新しい接続がデータベースから取得できなかった後に繰り返し試みの数を定義します。デフォルト:30-> <プロパティname = "AcquireretryThempts" value = "$ {db.AcquirerThyAttempts}" /> <! - 接続を取得すると、すべてのスレッドが接続プールが接続を取得するのを待っているすべてのスレッドが例外を取得するようになります。ただし、データソースはまだ有効であり、GetConnection()を次に呼び出すときに接続を取得しようとします。 trueに設定されている場合、データソースは、接続を取得しようとした試みに失敗した後、切断され、永続的に閉じられていることを宣言します。デフォルト:false - > <プロパティ名= "Breakafteracquirefailure" value = "$ {db.breakafteracquirefailure}" /> <! - 必要なときにのみ使用してください。 Trueに設定されている場合、その有効性は各接続の提出時に検証されます。接続テストのパフォーマンスを向上させるために、IdleConnectionTestPeriodまたはAutomateStEStTableを使用することをお勧めします。デフォルト:false - > <プロパティ名= "testConnectionOnCheckout" value = "$ {db.testconnectionOnCheckout}"/> </bean> <! - Mybatis configuration.classpath.classpathとclasspath*の違い*、http://blog.csdn.net/zl3450345341/article/details.最初のマッチングリソースのみを返します。パスを決定する単一のドキュメントにClassPathを使用することをお勧めします。 use classpath* when matching multiple documents.--><bean id="sqlSessionFactory"p:dataSource-ref="dataSource"p:configLocation="classpath:mybatis.xml"p:mapperLocations="classpath*:mapper/*Mapper.xml" /><bean><!--basePackage specifies the package to be scanned, and the mappers under this package検索されます。複数のパッケージを指定できます。 MapperScannerConfigurerは、BasePackageで指定されたパッケージの下で、すべてのインターフェイスクラス(サブパッケージを含む)をスキャンします。それらがSQLマッピングファイルで定義されている場合、それらはスプリングビーンとして動的に定義されます。 - > <プロパティ名= "basepackage" value = "com.everseeker.dao" /> <プロパティ名= "sqlsessionfactorybeanname" value = "sqlsessionfactory" /> < /bean> <! - JDBCトランザクションを使用してトランザクションマネージャーの構成 - > <bean id = "transactionManager" class = "org.springframework.jdbc.datasource.datasourcetransactionmanager"> <プロパティ名= "datasource" ref = "datasource" /> < /bean> <! - @transactional transactional transaction management spessive to weaueにマークを付けた@transactional beanを定義します。デフォルトでは、TransactionManagerという名前のトランザクションマネージャーが自動的に使用されます。プロキシターゲットクラスは真であり、Springがサブクラスを作成することでビジネスクラスをプロキシにすることを示しており、cglib.jarクラスライブラリをクラスパスに追加する必要があることを示しています。 - > <TX:Annotation-Driven Transaction-Manager = "TransactionManager" Proxy-Target-Class = "true" /></beans> spring-mybatis.xml3.ユーザークラスとuserDaoインターフェイスを作成します。
public class user {@size(min = 32、max = 32、message = "uuidは32ビット文字列である必要があります")private string id; @size(min = 1、max = 32、 "アカウントの長さは1-32ビット間")プライベート文字列ユーザー名;フォーマットは間違っています ")プライベート文字列メール; @size(min = 11、max = 11、message ="携帯電話番号の長さは11桁です ")プライベート文字列携帯電話; private long regdate; public user(){this.id = uuid.randomuid()。 string携帯電話){this(username、password、email、携帯電話、new date()。gettime());} public user(string username、string password、string email、string携帯電話、long regdate){this.id = uuid.randomuid()。 email; this.cellphone =携帯電話; this.regdate = regdate;} public string getid(){return id;} public void setid(string id){this.id = id;} public string getusername(){return username;} public void setUsername( setPassWord(String Password){this.PassWord = password;} public String getEmail(){return email;} public void setemail(string email){this.email = email = email;} public string getCellphone(){return携帯電話;} public void setCellphone(this.cellphone;} public getRegdate(this.cellphone;} setRegdate(long regdate){this.regdate = regdate;}@overridepublic string toString(){return "[user:id =" + id + "、username =" + username + "、password =" + password + "、email =" + email + "、cellphone =" + cellphone +@notnull、@notempty、@size、@email in user.javaなどのコメントは一時的に無視され、後で説明されます。
@RepositoryPublic Interface userdao {void adduser(user user); user getuserbyusername(string username);}4. src/main/resources/mapperディレクトリにusermapper.xmlマッピングファイルを作成して、userdaoインターフェイスにメソッドを実装します。注: *mapper.xmlファイルはSRC/Main/Resourcesディレクトリに配置する必要があり、以前はSRC/Main/Java/com/everseeker/daoディレクトリに配置されていたため、不可解なエラーが発生しました。
<?xml version = "1.0" encoding = "utf-8"?> <!doctype mapper public " - // mybatis.org//dtd mapper 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "com.everseeker.dao.userdao"> <resultmap id = "resultmapuser" type = "com.everseeker.entity.user"> </resultmap> <id = "adduser" parametertype = "user">ユーザー(id、username、username、userphone、regdate)に挿入#{password}、#{email}、#{携帯電話}、#{regdate})</insert> <select id = "getuserbyusername" parametertype = "string" resultmapuser "> select * select * select * select * select * iii。 IOC
1. IOCコンテナを作成し、注釈法を使用してrootconfig.javaを使用します。
@configurations@componentscan(basepackages = {"com.everseeker"}、excludefilters = {@componentscan.filter(type = filtertype.custom、value = rootconfig.webpackage.class)})@comportresource({"classpath:spring-mybatis.xml"} class.xxml "} webパッケージはregexpatterntypefilter {public webpackage(){super(pattern.compile( "com //。everseeker//。web");}}}}} @configuration:これが構成クラスであることを示します。
@componentscan:コンポーネントスキャン、ベースパッケージを有効にする:スキャンする必要がある基本的なパッケージ。 Filtersを除外:フィルターがフィルター条件を満たしている場合はスキャンしないでください。
@importresource:XMLファイルを紹介します。
@PropertySource:プロパティファイルを導入します。
2。WebAppプロジェクトが作成され、SpringMVCが使用されるため、DispatcherServletがコアです。以前の春のバージョンでは、通常はWeb.xmlで構成されていました。春4では、Javaコードに実装できます。 webappinitializer.java。
パブリッククラスのWebAppInitializerは、AbstractAnnotationConfigdiservletinitializer {// AbstractAnnotationConfigDisPatcherSertInitializerを継承するクラスは、DispatcherServletとSpring Application Context @OverRideRideTected String [] GetServletMappings(){// Map {// Map {// Map "/"/"/" };}/*** rootconfigクラスは、contextloaderlistenerによって作成されたアプリケーションコンテキストで豆を構成するために使用されます。たとえば、 @repository、@service、その他のコンポーネント*/ @overridedotected class <?アプリケーションのコンテキスト、WebConfig Configurationクラスで定義された豆の使用 *は、コントローラー、ビューパーサー、プロセッサマッピング、@Controller、@RequestMappingなどのWebコンポーネントを含むBeanをロードするために使用されます。 };}@overridedotected void customizeregistration(servletregistration.dynamic登録){//アップロードされたファイルサイズを2MB以下に制限します。リクエスト全体は4Mを超えず、すべてのアップロードされたファイルはディスク登録に書き込まなければなりません。 4194304、0));}}3。WebConfig.javaを作成します。
@configuration@enablewebmvc@componentscan( "com.everseeker.web")public class webconfigの拡張webmvcconfigureradapter {// jsp viewsolver viewresolver(){internalresourceviewResolver = new = new new internalResourceViewResolver(); resourceViewResolver.setPrefix( "/web-inf/views/"); resourceViewResolver.setsuffix( "。JSP"); ResourceViewResolver.setExposeContBeanSaSattributes(true); Return resourceViewResolver;} MultiPartresolver()throws ioException {return new Stardenterservletmultipartresolver();} //静的リソースの構成@overridepublic void configuredefaultservlethandling(defaultservlethandlerconfigurer configure){configurer.enable();}@Bean:このメソッドを宣言すると、スプリングアプリケーションのコンテキストで、目的のタイプとレジスタのインスタンスがBeanとして作成されます。
上記は、編集者によって紹介された春学習ノート1のIOCの詳細な説明です。アノテーションとJavaコードを可能な限り使用してみてください。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!