English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Angular 검색 필드 애플리케이션

이 섹션에서는 Search Field 웹 응용 프로그램을 생성하겠습니다. 이 응용 프로그램은 검색 필드를 포함한 테이블 형식의 데이터를 포함하고 있습니다. 이 통합에서는 Spring이 백엔드 부분을 처리하고 Angular이 프론트엔드 부분을 처리합니다.

작업 응용 프로그램

응용 프로그램을 서버에 배포하면 테이블 형식의 데이터와 몇 가지 검색 필드를 포함한 양식이 생성됩니다. 이제 이 필드에서 테이블에 존재하는 데이터를 검색할 수 있습니다. 여기서는 두 개의 검색 필드를 사용합니다-이름과 이메일 ID. 데이터를 검색하려면 어떤 검색 필드에도 전체 키워드를 제공해야 합니다.

사용할 도구

Spring과 Hibernate 프로젝트를 개발하기 위해 어떤 IDE를 사용하든 상관없습니다. MyEclipse가 될 수 있습니다./Eclipse/Netbeans. 여기서는 Eclipse를 사용하고 있습니다. MySQL을 사용하는 데이터베이스. Angular 프로젝트를 개발하기 위해 어떤 IDE를 사용하든 상관없습니다. Visual Studio Code가 될 수 있습니다./Sublime. 여기서는 Visual Studio Code를 사용하고 있습니다. 서버: Apache Tomcat/JBoss/Glassfish/Weblogic/Websphere.

사용하는 기술

여기서는 다음 기술을 사용하고 있습니다:

Spring5 휴眠5 각도6 MYSQL

데이터베이스 생성

데이터베이스를 생성하겠습니다 searchfieldexample Hibernate이 테이블을 자동으로 생성하므로 테이블을 생성할 필요가 없습니다. 여기서는 테이블에 데이터를 명시적으로 제공해야 합니다. 이렇게 하면 검색 작업을 수행할 수 있습니다. 그러나 다운로드 링크에 있는 파일에서 데이터를 가져올 수도 있습니다.

Spring 모듈

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>
		<version>${mysql.connector.version}</version>
	</dependency>
	<!-- C3PO -->
	<dependency>
		<groupId>com.mchange</groupId>
		<artifactId>c3p0</artifactId>
		<version>${c3po.version}</version>
	</dependency>
	<!-- Servlet+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。因此,我们创建两个类并在其中指定所需的配置。

DemoAppConfig.java

package com.w3codebox.searchfieldexample.config;
import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
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;				
	}
	// helper 메서드 필요 
		// 환경 속성 읽기 및 int로 변환
		private int getIntProperty(String propName) {
			String propVal = env.getProperty(propName);
			// 지금 int로 변환
			int intPropVal = Integer.parseInt(propVal);
			return intPropVal;
		}
		@Bean
		public LocalSessionFactoryBean sessionFactory(){
			// session factory 생성
			LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
			// 속성 설정
			sessionFactory.setDataSource(myDataSource());
			sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
			sessionFactory.setHibernateProperties(getHibernateProperties());
			return sessionFactory;
		}
		@Bean
		@Autowired
		public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
			// session factory를 기반으로 transaction manager 설정
			HibernateTransactionManager txManager = new HibernateTransactionManager();
			txManager.setSessionFactory(sessionFactory);
			return txManager;
		}	
}

MySpringMvcDispatcherServletInitializer.java

package com.w3codebox.searchfieldexample.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TOdo Auto-generated method stub
		return null;
	}
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { DemoAppConfig.class };
	}
	@Override
	protected String[] getServletMappings() {
		return new String[] {"/"};
	}
}

创建实体类
在这里,我们将创建一个Entity/POJO(普通的旧Java对象)类。

User.java

package com.w3codebox.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 com.w3codebox.searchfieldexample.DAO.interfaces;
import java.util.List;
import com.w3codebox.searchfieldexample.entity.User;

	public int SaveUser(User user);
	public List<User> getFilteredData(User user);
}

package com.w3

import java.util.List;



import org.springframework.beans.factory.annotation.Autowired;

import com.w3codebox.searchfieldexample.DAO.interfaces.UserDAO;
import com.w3codebox.searchfieldexample.entity.User;


	@Autowired
	
	public int SaveUser(User user) {
		
		
			
			
			
		}
		catch(Exception exception)
		{
			 + 
			
		}
		finally
		{
			session.flush();
		}
	}
	public List<User> getFilteredData(User user) {
		
		
		{
			
			
			
			
			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 com.w3codebox.searchfieldexample.service.interfaces;
import java.util.List;
import com.w3codebox.searchfieldexample.entity.User;
public interface UserService {
	public int SaveUser(User user);
	public List<User> getFilteredData(User user);
}

서비스 레이어 구현 클래스 생성

UserServiceImpl.java

package com.w3codebox.searchfieldexample.service.implementation;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.w3codebox.searchfieldexample.DAO.interfaces.UserDAO;
import com.w3codebox.searchfieldexample.entity.User;
import com.w3codebox.searchfieldexample.service.interfaces.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	UserDAO userDAO;
	@Transactional
	public int SaveUser(User user) {
		return userDAO.SaveUser(user) ;
	}
	@Transactional
	public List<User> getFilteredData(User user) {
		return userDAO.getFilteredData(user);
	}
}

创建控制器类

UserController.java

package com.w3codebox.searchfieldexample.restcontroller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.w3codebox.searchfieldexample.entity.User;
import com.w3codebox.searchfieldexample.service.interfaces.UserService;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:42"00", allowedHeaders = ""*"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项目

使用以下命令创建一个Angular项目:

ng new SearchFieldExample


此处, SearchFieldExample 是项目的名称。

安装Bootstrap CSS框架

使用以下命令在项目中安装引导程序。

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);
  }
  get Name()
  {
    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>

작업이 완료되면 웹에서 URL http:을 입력하세요 //localhost: 4200/브라우저에서 다음 웹 페이지가 표시됩니다:

이제, 검색 필드에 특정 키워드를 제공하여 데이터를 검색할 수 있습니다.

이름을 통해 검색:

이메일 ID를 통해 검색: