📜  Angular + Spring搜索字段示例

📅  最后修改于: 2020-12-16 10:10:34             🧑  作者: Mango

弹簧角搜索领域的应用

在本节中,我们将创建一个Search Field Web应用程序。该应用程序包括具有搜索字段的表格形式的数据。在这种集成中,我们使用Spring处理后端部分,使用Angular处理前端部分。

申请工作

  • 一旦将应用程序部署到服务器上,就会生成一个表单,其中包含表格形式的数据以及一些搜索字段。
  • 现在,我们可以从这些字段中搜索表中存在的数据。在这里,我们使用两个搜索字段-名称和电子邮件ID。
  • 要搜索数据,需要在任何搜索字段中提供完整的关键字。

使用工具

  • 使用任何IDE来开发Spring和Hibernate项目。可能是MyEclipse / Eclipse / Netbeans。在这里,我们正在使用Eclipse。
  • MySQL用于数据库。
  • 使用任何IDE来开发Angular项目。它可能是Visual Studio代码/ Sublime。在这里,我们正在使用Visual Studio Code。
  • 服务器:Apache Tomcat / JBoss / Glassfish / Weblogic / Websphere。

我们使用的技术

在这里,我们使用以下技术:

  • daa5
  • 休眠5
  • 角度6
  • MySQL数据库

创建数据库

让我们创建一个数据库searchfieldexample 。由于Hibernate自动创建了表,因此无需创建表。在这里,我们需要在表中显式提供数据,以便它们可以出现在屏幕上以执行搜索操作。但是,我们也可以从下载链接中存在的文件中导入数据。

弹簧模块

让我们看看我们需要遵循的Spring目录结构:

要开发搜索字段应用程序,请执行以下步骤:-

  • 将依赖项添加到pom.xml文件。

pom.xml


  4.0.0
  com.javatpoint
  SearchFieldExample
  war
  0.0.1-SNAPSHOT
  SearchFieldExample Maven Webapp
  http://maven.apache.org
  
  
  
        5.0.6.RELEASE
        5.2.16.Final
        5.1.45
        0.9.5.2

        1.8
        1.8
    
  
  
  
    
    
        org.springframework
        spring-webmvc
        ${springframework.version}
    

    
        org.springframework
        spring-tx
        ${springframework.version}
    
        
    
        org.springframework
        spring-orm
        ${springframework.version}
    

    
    
        com.fasterxml.jackson.core
        jackson-databind
        2.9.5
    

    
    
        org.hibernate
        hibernate-core
        ${hibernate.version}
    

    
    
        mysql
        mysql-connector-java
        ${mysql.connector.version}
    

    
    
        com.mchange
        c3p0
        ${c3po.version}
    

    
    
        javax.servlet
        javax.servlet-api
        3.1.0
    

    
        javax.servlet.jsp
        javax.servlet.jsp-api
        2.3.1
    

    
        javax.servlet
        jstl
        1.2
    

    
    
        javax.xml.bind
        jaxb-api
        2.3.0
    
     
     
    
        junit
        junit
        3.8.1
        test
    
   
  
 
  
    SearchFieldExample
  

  • 创建配置类我们执行基于注释的配置,而不是XML。因此,我们创建两个类并在其中指定所需的配置。

DemoAppConfig.java

package com.javatpoint.searchfieldexample.config;

import java.beans.PropertyVetoException;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
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.javatpoint.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() {
        
        // create connection pool
        ComboPooledDataSource myDataSource = new ComboPooledDataSource();

        // set the jdbc driver
        try {
            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.hbm2ddl.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 session factorys
            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 session factory
            HibernateTransactionManager txManager = new HibernateTransactionManager();
            txManager.setSessionFactory(sessionFactory);

            return txManager;
        }    

}

MySpringMvcDispatcherServletInitializer.java

package com.javatpoint.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.javatpoint.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() {
        return userId;
    }

    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.javatpoint.searchfieldexample.DAO.interfaces;

import java.util.List;
import com.javatpoint.searchfieldexample.entity.User;

public interface UserDAO {
    
    public int SaveUser(User user);
    
    public List getFilteredData(User user);

}
  • 创建DAO接口实现类

UserDAOImpl.java

package com.javatpoint.searchfieldexample.DAO.implementation;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

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


@Repository("userDAO")
public class UserDAOImpl implements UserDAO {

    @Autowired
    SessionFactory sessionFactory;
    
    public int SaveUser(User user) {
        
        Session session = null;
        try {
            session = sessionFactory.getCurrentSession();
            int userId = (Integer) session.save(user);
            return userId;
        }
        catch(Exception exception)
        {
            
            System.out.println("Excption while saving data into DB " + exception);
            return 0;
        }
        finally
        {
            session.flush();
        }
        
    }

    public List getFilteredData(User user) {
        
        Session session = null;
        try
        {
            session = sessionFactory.getCurrentSession();
            
            ArrayList list_field = new ArrayList();
            ArrayList list_value = new ArrayList();
            
            if(user.getName()==null || user.getName()==""){}else{list_field.add("name");list_value.add(user.getName());}
            if(user.getEmailId()==null || user.getEmailId()==""){}else{list_field.add("emailId");list_value.add(user.getEmailId());}

            switch (list_field.size()) {
            
            case 0:
                    Query 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("value1", 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.javatpoint.searchfieldexample.service.interfaces;

import java.util.List;
import com.javatpoint.searchfieldexample.entity.User;

public interface UserService {
    
    public int SaveUser(User user);
    
    public List getFilteredData(User user);

}
  • 创建服务层实现类

UserServiceImpl.java

package com.javatpoint.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.javatpoint.searchfieldexample.DAO.interfaces.UserDAO;
import com.javatpoint.searchfieldexample.entity.User;
import com.javatpoint.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 getFilteredData(User user) {
        return userDAO.getFilteredData(user);
    }

}
  • 创建控制器类

UserController.java

package com.javatpoint.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.javatpoint.searchfieldexample.entity.User;
import com.javatpoint.searchfieldexample.service.interfaces.UserService;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:4200", allowedHeaders = "*", exposedHeaders = "Authorization")
public class UserController {
    
    @Autowired 
    private UserService userService;
    
    @PostMapping("/saveUser")
    public int saveAdminDetail(@RequestBody User user) {
        
        return userService.SaveUser(user);
    }
    
    @PostMapping("/filterData")
    public List 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.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl=update
hibernate.packagesToScan=com.javatpoint.searchfieldexample.entity

角度模块

让我们看看我们需要遵循的Angular目录结构:

  • 创建一个Angular项目

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

ng新的SearchFieldExample


在这里, SearchFieldExample是项目的名称。

安装Bootstrap CSS框架

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

npm install bootstrap@3.3.7-保存

现在,在style.css文件中包含以下代码。

@import "~bootstrap/dist/css/bootstrap.css";
  • 生成组件在Visual Studio中打开项目,然后使用以下命令生成Angular组件: ng gc ShowData

我们还使用以下命令创建服务类:-

ng gs服务/用户

  • 编辑app.module.ts文件
    • Import HttpModule-在这里,我们将为服务器请求导入HttpModule ,并在imports数组中指定它。
    • 注册服务类-在这里,我们在providers数组中提到了服务类。
    • 导入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 './show-data/show-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文件

  • 创建User.ts

让我们使用以下命令创建一个类:-

ng g个班级/用户

现在,在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);
  }

}
  • 编辑show-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-show-data',
  templateUrl: './show-data.component.html',
  styleUrls: ['./show-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');
  }


}
  • 编辑show-data.component.html文件




Name Email Qualification
{{item.name}} {{item.emailId}} {{item.qualification}}

完成后,在Web浏览器中输入URL http:// localhost:4200 /。出现以下网页:

现在,我们可以通过在搜索字段中提供特定的关键字来搜索数据。

按名称搜索:

通过电子邮件ID搜索: