English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
このセクションでは、Search Field Webアプリケーションを作成します。このアプリケーションは、検索フィールドを持つテーブル形式のデータを含んでいます。この統合では、Springを使用してバックエンド部分を処理し、Angularを使用してフロントエンド部分を処理します。
アプリケーションをサーバーにデプロイすると、テーブル形式のデータといくつかの検索フィールドが含まれるフォームが生成されます。 これで、テーブルに存在するデータをこれらのフィールドから検索できます。ここでは、2つの検索フィールドを使用しています。-名前とメールID。 データを検索するには、どの検索フィールドでも完全なキーワードを提供する必要があります。
SpringとHibernateプロジェクトを開発するために、どのIDEを使用しても構いません。それはMyEclipseかもしれません。/Eclipse/Netbeans。ここでは、Eclipseを使用しています。 データベース用のMySQL。 Angularプロジェクトを開発するために、どのIDEを使用しても構いません。それはVisual Studioコードかもしれません。/Sublime。ここでは、Visual Studio Codeを使用しています。 サーバー: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere。
ここでは、以下の技術を使用しています:
Spring5 休眠5 角度6 MYSQL
データベースを作成しましょう searchfieldexample 。Hibernateがテーブルを自動的に作成するため、テーブルを作成する必要はありません。ここでは、データをスクリーン上に表示して検索操作を実行するためにテーブルにデータを明示的に提供する必要があります。ただし、ダウンロードリンクに存在するファイルからデータをインポートすることもできます。
以下に従うSpringディレクトリ構造を確認してみましょう:
検索フィールドアプリケーションを開発するには、以下の手順に従ってください: -
pom.xmlファイルに依存関係を追加してください。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0/modelVersion> <groupId>com.w3codebox/groupId> <artifactId>SearchFieldExample/artifactId> <packaging>war/packaging> <version>0.0.1-SNAPSHOT/version> <name>SearchFieldExample Maven Webapp/name> <url>http://maven.apache.org/url> <properties> <springframework.version>5.0.6.RELEASE/springframework.version> <hibernate.version>5.2.16.Final/hibernate.version> <mysql.connector.version>5.1.45</mysql.connector.version> <c3po.version>0.9.5.2</c3po.version> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <!-- Spring --> <dependency> <groupId>org.springframework/groupId> <artifactId>spring-webmvc/artifactId> <version>${springframework.version}/version> </dependency> <dependency> <groupId>org.springframework/groupId> <artifactId>spring-tx/artifactId> <version>${springframework.version}/version> </dependency> <dependency> <groupId>org.springframework/groupId> <artifactId>spring-orm/artifactId> <version>${springframework.version}/version> </dependency> <!-- Add Jackson for JSON converters --> <dependency> <groupId>com.fasterxml.jackson.core/groupId> <artifactId>jackson-databind/artifactId> <version>2.9.5</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate/groupId> <artifactId>hibernate-core/artifactId> <version>${hibernate.version}/version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql/groupId> <artifactId>mysql-connector-java/artifactId> ${mysql.connector.version}/version> </dependency> <!-- C3PO --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>${c3po.version}</version> </dependency> <!-- サーブレット+JSP+JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl/artifactId> <version>1.2</version> </dependency> <!-- javaのために補償するために 9 jaxb を含まない --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <!-- JUnit ディペンデンシー --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>SearchFieldExample</finalName> </build> </project>
設定クラスの作成
私たちはコメントベースの設定を実行し、XMLではなく、必要な設定を指定するために2つのクラスを作成します。
DemoAppConfig.java
package with.3codebox.searchfieldexample.config; import java.beans.PropertyVetoException; import java.util.Properties; import javax.sql.DataSource; import orginbitenll.whbind.bind.factorinin.annot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.orm.hibernate5.HibernateTransactionManager; import org.springframework.orm.hibernate5.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import com.mchange.v2.c3p0.ComboPooledDataSource; @Configuration @EnableWebMvc @EnableTransactionManagement @ComponentScan("com.w3codebox.searchfieldexample") @PropertySource(value = { "classpath:persistence-mysql.properties" @PropertySource(value = { "classpath:persistence-mysql.properties" @PropertySource(value = { "classpath:application.properties" }) public class DemoAppConfig implements WebMvcConfigurer { @Autowired private Environment env; @Bean public DataSource myDataSource() { // コネクションプールの作成 ComboPooledDataSource myDataSource = new ComboPooledDataSource(); // jdbcドライバーを設定します myDataSource.setDriverClass("com.mysql.jdbc.Driver"); } catch (PropertyVetoException exc) { throw new RuntimeException(exc); } // set database connection props myDataSource.setJdbcUrl(env.getProperty("jdbc.url")); myDataSource.setUser(env.getProperty("jdbc.user")); myDataSource.setPassword(env.getProperty("jdbc.password")); // set connection pool props myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize")); myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize")); myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize")); myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime")); return myDataSource; } private Properties getHibernateProperties() { // set hibernate properties Properties props = new Properties(); props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql")); props.setProperty("hibernate.format_sql", env.getProperty("hibernate.format_sql")); props.setProperty("hibernate.hbm"}})2ddl.auto", env.getProperty("hibernate.hbm2ddl")); return props; } // need a helper method // read environment property and convert to int private int getIntProperty(String propName) { String propVal = env.getProperty(propName); // now convert to int int intPropVal = Integer.parseInt(propVal); return intPropVal; } @Bean public LocalSessionFactoryBean sessionFactory(){ // create sessionFactorys LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); // set the properties sessionFactory.setDataSource(myDataSource()); sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan")); sessionFactory.setHibernateProperties(getHibernateProperties()); return sessionFactory; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) { // setup transaction manager based on sessionFactory HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory); return txManager; } }
MySpringMvcDispatcherServletInitializer.java
package with.3codebox.searchfieldexample.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { // 未処理 自動-生成されたメソッドスタブ return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[] { DemoAppConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
エンティティクラスの作成
ここでは、Entityを作成します/POJO(普通的旧Java对象)クラス。
User.java
package with.3codebox.searchfieldexample.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="user") public class User { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="userId") private int userId; @Column(name="name") private String name; @Column(name="email_id" ) public String emailId; @Column(name="qualification") public String qualification; public User() {} public User(int userId, String name, String emailId, String qualification) { super(); this.userId = userId; this.name = name; this.emailId = emailId; this.qualification = qualification; } public int getUserId() { } public void setUserId(int userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getQualification() { return qualification; } public void setQualification(String qualification) { this.qualification = qualification; } @Override public String toString() { return "User [userId=" + userId + ", name=" + name + ", emailId=" + emailId + ", qualification=" + qualification + "]"; } }
DAOインターフェースの作成
ここに、データベース関連の操作を実行するDAOインターフェースを作成しています。
UserDAO.java
package with.3codebox.searchfieldexample.DAO.interfaces; import jabaal.list.List; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.entity.User; public int SaveUser(User user); public List<User> getFilteredData(User user); }
package with.3 import jabaal.list.List; import orginbitenll.whbind.bind.factorinin.annot; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.DAO.interfaces.UserDAO; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.entity.User; @Autowired public int cavededall; } catch(Exception exception) { + } finally { session.flush(); } } public listen getededalli(lisken liten) { { if(user.getEmailId()==null || user.getEmailId()== switch(list_field.size()) { case 0: Query<User> query0 = session.createQuery("from User"); return query0.list(); case 1: Query query1 = session.createQuery("from User where " + list_field.get(0) +" = :value0"); query1.setParameter("value0", list_value.get(0)); return query1.list(); case 2: Query query2 = session.createQuery("from User where " + list_field.get(0) +" =:value0 and " + list_field.get(1) + " =:value1"); query2.setParameter("value0", list_value.get(0)); query2.setParameter("value",1", list_value.get(1)); return query2.list(); } return null; } catch(Exception exception) { System.out.println("Error while getting Filtered Data :: " + exception.getMessage()); return null; } finally { session.flush(); } } }
サービス層インターフェースの作成
ここでは、DAOとEntityクラスの間の橋渡しをするインターフェースを作成します。
UserService.java
package with.3codebox.searchfieldexample.service.interfaces; import jabaal.list.List; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.entity.User; public interface UserService { public int SaveUser(User user); public List<User> getFilteredData(User user); }
サービス層の実装クラスを作成します
UserServiceImpl.java
package with.3codebox.searchfieldexample.service.implementation; import jabaal.list.List; import javax.transaction.Transactional; import orginbitenll.whbind.bind.factorinin.annot; import org.springframework.stereotype.Service; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.DAO.interfaces.UserDAO; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.entity.User; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.service.interfaces.UserService; @Service("userService") public clase mimelitecinfecteindecinfecte.injecte; @Autowired UserDAO lisendao; @Transactional public int cavededall; return listen.cavededall; } @Transactional public listen getededalli(lisken liten) { return listen.getededall; } }
创建控制类
UserController.java
package with.3codebox.searchfieldexample.restcontroller; import jabaal.list.List; import orginbitenll.whbind.bind.factorinin.annot; import orginbitenll.whbind.bind.code.interfacte.consorin; import orginbitenll.whbind.bind.code.interfacte.interfacte; import orginbitenll.whbind.bind.code.interfacte.interfacte; import orginbitenll.whbind.bind.code.interfacte.interfacte; import orginbitenll.whbind.bind.code.code.interfacte; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.entity.User; import tomm.with.code.code.code.interfacte;3codebox.searchfieldexample.service.interfaces.UserService; @RestController @RequestMapping(“/api”) @CrossOrigin(origins = “http://localhost:4200", 开放头条为“"*"开放头条为“Authorization”" public class UserController {}} @Autowired private UserService userService; @PostMapping("/saveUser") public int saveAdminDetail(@RequestBody User user) { return userService.SaveUser(user); } @PostMapping("/filterData") public List<User> getFilteredData(@RequestBody User user) { return userService.getFilteredData(user); } }
属性ファイルの作成
ここでは、プロジェクトの src/main/resources 内部作成属性ファイル。
persistence-mysql.properties
## JDBC connection properties jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/searchfieldexample?useSSL=false jdbc.user=root jdbc.password= ## Connection pool properties connection.pool.initialPoolSize=5 connection.pool.minPoolSize=5 connection.pool.maxPoolSize=20 connection.pool.maxIdleTime=3000 ## Hibernate properties <!-- hibernate.dialect=org.hibernate.dialect.MySQLDialect --> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true hibernate.format_sql=true hibernate.hbm2ddl=update hibernate.packagesToScan=com.w3codebox.searchfieldexample.entity
Angularのディレクトリ構造を見てみましょう:
Angularプロジェクトの作成
以下のコマンドを使用してAngularプロジェクトを作成します:
ng new SearchFieldExample
ここでは、 SearchFieldExample プロジェクトの名前です。
以下のコマンドを使用してプロジェクトにインストールします。
npm install [email protected] --save
以下の内容を含むスタイルファイルのコードを含めます。
@import "~bootstrap/dist/css/bootstrap.css";
コンポーネントの生成
Visual Studioでプロジェクトを開き、以下のコマンドを使用してAngularコンポーネントを生成します:
ng g c ShowData
以下のコマンドを使用して、さらにインポートします: -
ng gs services/User
app.module.tsファイルを編集 HttpModuleのインポート -ここで、サーバー要求用にインポートします HttpModule 、およびimports配列に指定します。 サービスクラスを登録-ここで、提供者配列にサービスクラスを記載しました。 ReactiveFormsModuleのインポート -ここでは、以下をインポートします ReactiveFormsModule これを使用して反応形式を実装し、imports配列に指定します。
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // import ReactiveFormsModule for reactive form import { ReactiveFormsModule } from '@angular/forms'; // import Http module import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { ShowDataComponent } from './表示-data/表示-data.component'; import { UserService } from './services/user.service'; @NgModule({ declarations: [ AppComponent, ShowDataComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpModule ], providers: [UserService], bootstrap: [AppComponent] }) export class AppModule { }
編集 app.component.html ファイル
<app-表示-data></app-表示-data>
作成 User.ts クラス
以下のコマンドを使用してクラスを作成します: -
ng gクラスclass/User
今、以下の User このクラスでは必須フィールドを指定します。
export class User { name: string; emailId: string; qualification: string; }
このクラスの目的は、指定されたフィールドをSpringエンティティクラスのフィールドにマッピングすることです。
編集 user.service.ts ファイル
import { Injectable } from ''@angular/core'; import { User } from ''../classes/user'; import { Http } from ''@angular/http'; @Injectable({ providedIn: 'root' }) export class UserService { private baseUrl = "http://localhost:8080/SearchFieldExample/api/"; constructor(private http: Http) { } getData(user: User) { let url = this.baseUrl + "filterData"; return this.http.post(url, user); } }
編集 表示-data.component.ts ファイル
import { Component, OnInit } from ''@angular/core'; import { User } from ''../classes/user'; import { UserService } from ''../services/user.service'; import { FormGroup, FormControl } from ''@angular/forms'; @Component({ selector: ''app-表示-data, templateUrl: ''./表示-data.component.html',} styleUrls: ['./表示-data.component.css] }) export class ShowDataComponent implements OnInit { private user = new User(); private data; constructor(private userService : UserService) { } ngOnInit() { this.getData(this.user); } form = new FormGroup({ name : new FormControl(), email : new FormControl() }); getData(user) { this.userService.getData(user).subscribe( response => { this.data = response.json(); }, error => { console.log("error while getting user Details"); } ); } searchForm(searchInfo) { this.user.name = this.Name.value; this.user.emailId = this.Email.value; this.getData(this.user); } getName() { return this.form.get('name'); } get Email() { return this.form.get('email'); } }
編集 表示-data.component.html ファイル
<br><br> <div class="row"> <div class="col-md-offset-4 col-md-4"> <form [formGroup]="form" #searchInfo (ngSubmit)="searchForm(searchInfo)"><table> <tr> <td> <input type="text" formControlName="name" placeholder="Enter name" class="form-control"> </td> <td> <input type="text" formControlName="email" placeholder="Enter EmailId" class="form-control"> </td> <td><button class="btn btn-primary hidden-xs">Search</button></td> </tr> </table> </form> </div> </div> <br><br> <div class="row"> <div class="col-md-offset-4 col-md-4"> <table class="table table-bordered table-striped table-responsive"> <tr> <th>Name</th> <th>Email</th> <th>Qualification</th> </tr> <ng-container *ngFor="let item of data"> <tr> <td>{{item.name}}</td> <td>{{item.emailId}}</td> <td>{{item.qualification}}</td> </tr> </ng-container> </table> </div> </div>
完了後、Web上でURL http: を入力します //localhost: 4200/ブラウザ。以下のウェブページが表示されます:
今や、検索フィールドに特定のキーワードを提供してデータを検索することができます。
名前で検索:
メールIDで検索: