java web构建
Due to its exponential growth, REST(Representational State Transfer) has rapidly become the “de-facto” Software Architecture for developing Web Services. This is no surprise considering his creator, Roy Fielding, who was involved in maybe around a dozen specs that contribute to how the web operates now. REST architectural style was developed in the 2000s. Parallel to HTTP(Hyper-Text Transfer Protocol) 1.1 which was developed from 1996–1999 based on its previous design, HTTP 1.0.
由于其指数级增长,REST( 表示状态转移 )已Swift成为用于开发Web服务的“事实”软件体系结构。 考虑到他的创建者Roy Fielding参与了大约十二种规范,这些规范对现在的网络运行做出了贡献,这不足为奇。 REST体系结构风格是在2000年代开发的。 与HTTP( 超文本传输协议 )1.1并行,HTTP 1.1是在其先前设计HTTP 1.0的基础上于1996年至1999年开发的。
In this article, we will go step-by-step on developing a Web Service based on REST architecture. Without further ado, you will be needing the following:
在本文中,我们将逐步开发基于REST体系结构的Web服务。 事不宜迟,您将需要以下各项:
A prior, mid to advanced knowledge on Java Object-Oriented Programming Language. 具有Java面向对象编程语言的中,高级知识。 A development System with an IDE of your preference. 具有您首选的IDE的开发系统。 JDK 8 or above installed. 已安装JDK 8或更高版本。A Relational DBMS with its own SQL Server (MySQL, MongoDB, PostgreSQL).
具有自己SQL Server( MySQL,MongoDB,PostgreSQL )的关系DBMS。
Postman development tool for testing APIs. (Optional)
用于测试API的Postman开发工具。 ( 可选 )
Getting Started
入门
Let’s assume a Software Entrepreneur has a brand-new, innovative, Software as a Service. He wants to keep account of his clients, store them onto a DataBase, and manage them whenever he feels like it. For this, we will make use of the Spring Framework, which will provide us with the ability to run a Spring Boot Application. This will initialize a microservice for our application. We will develop a web server with HTTP request methods, such as GET, POST, and DELETE.
假设软件企业家拥有全新的创新软件即服务。 他想记下客户的账目,将其存储到数据库中,并在需要时进行管理。 为此,我们将利用Spring Framework,它将为我们提供运行Spring Boot Application的能力。 这将为我们的应用程序初始化微服务。 我们将使用HTTP请求方法(例如GET , POST和DELETE)开发一个Web服务器。
First, we will be creating our Spring Boot project. To create a Spring Boot project you can install the Spring Framework plug-in on your IDE, copy the following URL as your service URL https://start.spring.io or you can head directly to Spring Initializr to create a local repository. If this is the case, select Maven project and specify your Java version. Remember to configure your project with your own specifications. Click Generate and it will start to download a .zip file. Unzip it and you’ll be good to go.
首先,我们将创建我们的Spring Boot项目。 要创建一个Spring Boot项目,您可以在您的IDE上安装Spring Framework插件,将以下URL复制为您的服务URL https://start.spring.io,或者您可以直接转到Spring Initializr以创建本地存储库。 在这种情况下,请选择Maven项目并指定您的Java版本。 切记使用自己的规范配置项目。 单击生成,它将开始下载.zip文件。 解压缩它,你会很好的。
Your Spring project will consist of a pom.xml file. Add the following dependencies which we will be using later. 您的Spring项目将包含一个pom.xml文件。 添加以下依赖关系,我们将在以后使用。SpringBoot Starter data JPA(Java Persistence API) dependency
SpringBoot Starter数据JPA(Java Persistence API)依赖项
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId></dependency>SpringBoot Starter Web Dependency
SpringBoot Starter Web依赖关系
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>You also need to add your JDBC(Java Database Connection) driver dependency for your corresponding DBMS. In my case, I am using MySQL so my connector dependency is shown below.
您还需要为相应的DBMS添加JDBC( Java数据库连接 )驱动程序依赖项。 就我而言,我使用的是MySQL,因此我的连接器依赖性如下所示。
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId></dependency>Note: You can search for your respective JDBC Driver here https://mvnrepository.com/
注意:您可以在这里https://mvnrepository.com/搜索您各自的JDBC驱动程序。
Finally, your pom.xml file should look like this:
最后,您的pom.xml文件应如下所示:
3. Well done, your Spring project is set with all dependencies attached to the XML file. Next, we’ll define our DTO(Data Transfer Object) class which will be used to transfer data in and out of our Database.
3.做得好,您的Spring项目已设置为所有依赖项都附加到XML文件。 接下来,我们将定义我们的DTO( Data Transfer Object )类,该类将用于在数据库中进出数据。
Note: We won’t go into detail on Databases and table creation since it is out of the scope in this article.
注意:由于本文不涉及数据库和表的创建,因此我们将不对其进行详细介绍。
Let’s review the content in the class above.
让我们回顾一下上面的类中的内容。
Our DTO class consists of a series of attributes with their corresponding getter and setter methods, these attributes are also our columns in our Database Table.
我们的DTO类由一系列属性及其对应的getter和setter方法组成,这些属性也是数据库表中的列。
We’ll emphasize on the annotations provided.
我们将重点放在提供的注释上。
Entity is a JPA annotation. It tells our API that our class corresponds to an entity and is ready for storage in a JPA-based Data Store.
实体是一个JPA批注。 它告诉我们的API,我们的类对应于一个实体,并准备存储在基于JPA的数据存储中。
JsonSerialize and JsonProperty annotations are both parts of the Jackson library. It is defined by the Jackson wiki page as the “recommended way to register a custom serializer”, JsonSerialize is meant for serializing JsonProperties — such as our attributes in this class — when we don’t have access to the ObjectMapper class used to serialize and deserialize, also referred by other developers as “Hydrate” and “Dehydrate”. For more information on serialization, click this link.
JsonSerialize和JsonProperty批注都是Jackson库的一部分。 Jackson维基页面将其定义为“ 建议的自定义序列化程序注册方法 ”,当我们无法访问用于序列化和更新的ObjectMapper类时, JsonSerialize旨在序列化JsonProperties (例如此类的属性)。反序列化,也被其他开发人员称为“水合”和“脱水”。 有关序列化的更多信息,请单击此链接。
The Table and Id annotations are also both JPA annotations, Table specifies both the Database name as well as the table name in which our Entity will be stored. The id annotation should be placed onto the attribute that acts as the primary key in our table.
Table和Id批注也是JPA批注, Table既指定数据库名称,也指定存储实体的表名。 应该将id注释放置在用作表中主键的属性上。
The Column annotation is used to avoid error proneness, we use it to specify the exact name of the column in our table in which our object will be stored. We should always have a default constructor with its corresponding getter and setter methods besides the one that initializes all field variables in our class.
Column批注用于避免容易出错,我们使用它来指定表中存储对象的列的确切名称。 除了初始化类中所有字段变量的构造函数之外,我们始终应该有一个默认构造函数及其相应的getter和setter方法。
Tip: I am aware most developers use Long-type variables for their Id, even though this can actually be done. I prefer making use of the UUID(Uniform Universal Resource Identifier) class and recommend you implement it in your code as well. This class will automatically assign an Id to each Prospect without having to worry about duplicates. UUID assigns random Id’s to your prospects in hexadecimal positional system. e.g. 0x2AF3. For more information on the UUID class check the Oracle documentation here.
提示:我知道大多数开发人员都将Long类型变量用作其ID,即使实际上可以做到这一点。 我更喜欢使用UUID(统一通用资源标识符)类,并建议您在代码中也实现它。 此类将为每个潜在客户自动分配一个ID ,而不必担心重复。 UUID在十六进制位置系统中为您的潜在客户分配随机ID。 例如0x2AF3。 有关UUID类的更多信息,请参见此处的Oracle文档。
Note: The ProspectStatus class for prospectStatusCode attribute is defined on an ENUM class which we won’t cover. Full source code available at https://github.com/igorzelaya-io/LeadManagement-Back-end.git.
注意:provisionStatusCode属性的ProspectStatus类在我们不介绍的ENUM类上定义。 完整的源代码可在https://github.com/igorzelaya-io/LeadManagement-Back-end.git上获得 。
4. Now, we’ll cover our interface.
4.现在,我们将介绍我们的界面。
We use the CRUDRepository — which is part of JPA — as our superclass.
我们使用CRUDRepository(它是JPA的一部分)作为我们的超类。
The CRUD Repository enables us to do CRUD(Create, Read, Update, and Delete) operations on a specified object. In our case, we will perform these operations on Prospect data. CRUD Repository establishes a connection “under the hood” with your database via JDBC(Java Database Connection) and JPA, so you don’t have to worry about connecting to your database using DataSource or DriverManager classes.
CRUD存储库使我们能够对指定对象执行CRUD( 创建,读取,更新和删除 )操作。 在我们的案例中,我们将对潜在客户数据执行这些操作。 CRUD存储库通过JDBC( Java数据库连接 )和JPA与数据库建立了“后台连接”,因此您不必担心使用DataSource或DriverManager类连接到数据库。
For extended documentation on CRUD Repository click here.
有关CRUD存储库的扩展文档,请单击此处 。
5. We’re now about to instantiate our ProspectRepository interface — which extends a CRUD Repository — using a dependency injection.
5.现在,我们将使用依赖项注入实例化ProspectRepository接口,该接口扩展了CRUD存储库。
Now we can make use of the CRUD Repository methods. They are shown above, but for clarity purposes I’ll list them below.
现在,我们可以使用CRUD存储库方法。 它们显示在上方,但为清楚起见,我将在下面列出。
Update and Create: 更新和创建: Prospect prspct = prospectRepo.save(prspct); Delete: 删除: Prospect prspct = prospectRepo.delete(prspct); Read: 读: Iterable<Prospect> allProspects = prospectRepo.findAll();Prospect prspct = findByProspectEmail(String prospectEmail).get();6. Next up we will configure our Controller class, for mapping HTTP request methods such as GET, POST, DELETE. I know this may be a little bit intimidating for some programmers who are just starting on web development. At least it was for me, but don’t worry, I’ll guide you on everything you should know about this RestController class.
6.接下来,我们将配置Controller类,以映射HTTP请求方法,例如GET , POST , DELETE 。 我知道这对于刚开始进行Web开发的某些程序员来说可能有点吓人。 至少这是给我的,但是请放心,我将指导您了解有关RestController类的所有知识。
Let’s review our Controller class.
让我们回顾一下Controller类。
The RestController annotation simplifies the development of RESTful web services. Before RestController was introduced, the Controller and RequestBody annotations did the work, RestController was introduced in Spring 4.0. Its main objective is to transform the response into JSON or XML format, depending on your REST configuration.
RestController注释简化了RESTful Web服务的开发。 在引入RestController之前,先执行Controller和RequestBody批注, 然后在Spring 4.0中引入RestController 。 其主要目标是根据REST配置将响应转换为JSON或XML格式。
DeleteMapping, GetMapping, and PostMapping annotations map the HTTP request onto a handler method. Logically, GetMapping maps the GET request method, PostMapping maps the POST request method, and so on. Before these annotations were introduced, RequestMapping annotation did the same thing with a different syntax. e.g.
DeleteMapping , GetMapping和PostMapping批注将HTTP请求映射到处理程序方法。 从逻辑上讲, GetMapping映射GET请求方法, PostMapping映射POST请求方法,依此类推。 在引入这些批注之前, RequestMapping批注使用不同的语法执行相同的操作。 例如
@RequestMapping(value = "/prospects", method = RequestMethod.GET);This is how it was done before. Now, GetMapping and the rest do the RequestMapping implicitly.
这是以前做过的。 现在, GetMapping和其余的隐式地执行RequestMapping 。
@GetMapping("/prospects")Both these statements shown above have the same functionality.
上面显示的这两个语句具有相同的功能。
For each Mapping annotation, a handler method gets attached to a URL. In the case of the GET request method shown on the source code above, we can notice the findByProspectMail handler method returns a List of Prospects. We can also notice the RequestParam annotation is thrown onto its String-type, prospectMail parameter, this annotation indicates the String prospectMail is required on the URL for this method to return a response. This is very common when doing GET request methods due to the fact that we need to specify the entity we wish to be returned. In this case, we specify that our String parameter(prospectMail) is required on the URL. Our service URL should look then look like this.
对于每个Mapping批注,处理程序方法都将附加到URL。 在上面的源代码中显示GET请求方法的情况下,我们可以注意到findByProspectMail处理程序方法返回了前景列表。 我们还可以注意到RequestParam批注被抛出到它的String类型的promiseMail参数上,该批注指示URL上的String futureMail是此方法返回响应所必需的。 这在执行GET请求方法时非常常见,因为我们需要指定希望返回的实体。 在这种情况下,我们指定URL上需要我们的String参数( futureMail )。 我们的服务网址应如下所示。
http://localhost:8080/prospects?prospectMail=i@z.comI’ll dive a little bit further into this URL. Localhost indicates the webserver is running on your machine. 8080 is the port number in which your web server is being listened, and as you can notice, prospectMail is now part of our URL. If the RequestParam is not placed into the URL, it would most likely return a 404 status code, meaning the page was not found.
我将进一步深入探讨该URL。 Localhost指示Web服务器正在您的计算机上运行。 8080是用来监听您的Web服务器的端口号,并且您可以注意到, protractMail现在是我们URL的一部分。 如果RequestParam未放入URL中,则很可能返回404状态代码 ,这意味着未找到该页面。
Note: If the value assigned to your mail doesn’t exist i.e. isn’t placed on your database. Your page will crash.
注意:如果分配给您的邮件的值不存在,即未放置在数据库中。 您的页面将崩溃。
In our POST handler method, we specify our method should contain a RequestBody, meaning we need a body with data to post. In this case, a Prospect with its respective data. That is the reason we throw a Prospect object as a parameter. Normally, in a web server, there is a UI(User Interface), where we enter information. Maybe on a dialog box or select information from a drop-down. This information is parsed into JSON or XML format so the back end service can process it. In this case, we will enter information directly in JSON format. There are two different ways to achieve this process. The first and simplest way of doing this is by using Postman, the second is by using the cURL in the Command Prompt. We will discuss the use of Postman and cURL commands in just a sec. For now, let us review how our JSON data should be structured. It should look like this.
在POST处理程序方法中,我们指定我们的方法应包含RequestBody ,这意味着我们需要一个带有数据的正文来进行发布。 在这种情况下,前景及其各自的数据。 这就是我们将Prospect对象作为参数的原因。 通常,在Web服务器中,有一个UI ( 用户界面 ),我们可以在其中输入信息。 可能在对话框上,或者从下拉列表中选择信息。 此信息被解析为JSON或XML格式,因此后端服务可以对其进行处理。 在这种情况下,我们将直接以JSON格式输入信息。 有两种不同的方法可以实现此过程。 第一种也是最简单的方法是使用Postman,第二种方法是使用命令提示符中的cURL。 我们将在短短几秒钟内讨论Postman和cURL命令的使用。 现在,让我们回顾一下如何构造我们的JSON数据。 它应该看起来像这样。
{ "prospectId":"0x857", "prospectName":"Igor", "prospectOrgName":"Baas", "prospectPhone":"+504 0000-0005", "prospectCountry":"HN", "prospectMail":"a@b.com", "prospectStatusCode":"2", "prospectComments":"He is good at cod"}Note: If your DTO has more attributes, you should list them in the same way.
注意:如果DTO具有更多属性,则应以相同的方式列出它们。
Finally, we’ll review our DELETE handler method deleteProspect. It is very similar to our GET handler method, the only difference is the RequestParam annotation. The parameter passed into the handler method is now prospectId, there is a reason for this. Besides from REST’s architecture norms and documentation, the fact that our prospectId is the primary key in our database allows the process of searching for a specific prospect to be carried out in much less time. This is kind of a rule of thumb, if you’re searching for an entity, make sure to look either for a primary, secondary, or foreign key.
最后,我们将回顾我们的DELETE处理程序方法deleteProspect。 它与我们的GET处理程序方法非常相似,唯一的区别是RequestParam批注。 现在,传递到处理程序方法中的参数为profideId ,这是有原因的。 除了REST的体系结构规范和文档以外,我们的futureId是数据库中的主键这一事实使搜索特定潜在客户的过程可以在更短的时间内完成。 这是一种经验法则,如果要搜索实体,请确保查找主键,辅助键或外键。
7. You are set with the controller class, open your Spring project or Local Repository, and head to src/main/resources. There, you will find an application.properties file. If not, just create it. Enter the following configuration.
7.设置好控制器类,打开Spring项目或本地存储库,然后转到src / main / resources。 在那里,您将找到一个application.properties文件。 如果没有,只需创建它。 输入以下配置。
spring.datasource.url=jdbc:mysql://localhost:PORT/LeadManagmentDBspring.datasource.username=YOUR_USERNAMEspring.datasource.password=YOUR_PASSWORDspring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialectspring.jpa.show-sql=truespring.jpa.hibernate.ddl-auto=updatespring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpllogging.level.org.hibernate.SQL=DEBUGlogging.level.org.hibernate.type=traceNote: Make sure to type in your own Database speculations.
注意:确保键入您自己的数据库推测。
Congratulations, your application is ready to be compiled. Run a maven install on it. If you did everything correctly, your console should present the following information.
恭喜,您的应用程序已准备好进行编译。 在其上运行Maven安装。 如果正确完成所有操作,则控制台应显示以下信息。
BUILD SUCCESS 建立成功Once you’ve compiled your project successfully, you can run your project as a Spring Boot Application, this will initialize a microservice hosted on your machine. If everything goes okay you should have your application up and running.
成功编译项目后,您可以将项目作为Spring Boot应用程序运行,这将初始化计算机上托管的微服务。 如果一切正常,则应该启动并运行应用程序。
Testing
测试中
Okay, if you’ve made it this far, you might as well test your application. If you have Postman installed, we’ll get right into it. Else, head to Terminal(Command Line Interface), and type in the following command.
好的,如果您已经做到了这一点,那么不妨测试一下您的应用程序。 如果您安装了Postman,我们将直接进行安装。 否则,转到Terminal( Command Line Interface ),然后输入以下命令。
Using Terminal:
使用终端 :
curl --location --request POST 'http://localhost:8080/prospects' \--header 'Content-Type: application/json' \--data-raw '{"prospectId":"435678","prospectName":"Maria","prospectOrgName":"baas","prospectPhone":"000000000","prospectCountry":"HN","prospectEmail":"b@a.com","prospectStatusCode":"3","prospectComments":"he is tall."}'This command will POST a Prospect on your Database, you can access it by going to your browser and entering this in your URL.
此命令将发布一个展望数据库,你可以去你的浏览器,并在您的网址进入该访问它。
http://localhost:8080/prospects?prospectMail=b@a.comThis will run a GET request method on whichever prospect corresponds to the email entered on the RequestParam.
这将在与RequestParam上输入的电子邮件对应的任何潜在客户上运行GET请求方法。
Using Postman:
使用邮递员:
To GET, POST, and DELETE information using Postman, it’s a lot easier.
为了GET,POST,并使用DELETE邮差的信息,这是一个容易得多。
To POST a prospect, you just need to click on the drop-down, select POST HTTP request method, and fill the body in raw JSON format, just as shown below. When you’re done, click send. Your response message should pop in the console.
发布一个前景,你只需要点击下拉菜单,选择HTTP POST请求方法,并填写身体生JSON格式,就如下图所示。 完成后,点击发送 。 您的响应消息应在控制台中弹出。
For GET and DELETE request methods, things have a twist.
对于GET和DELETE请求方法,情况有所不同。
In this case, our handler methods are composed of a RequestParam annotation, meaning we need to specify the Prospect we are searching for either by indicating its mail or by typing its ID. Click send and you’ll get your response message in no time.
在这种情况下,我们的处理程序方法由RequestParam批注组成,这意味着我们需要通过指示其邮件或键入其ID来指定要搜索的Prospect。 单击发送,您将立即收到响应消息。
Conclusion
结论
This is a back end service application, this can be further extended by adding more tables and relate them with one another, but for the purpose of this article, I kept it pretty basic so you can really grasp the idea of REST software architecture. To automate this, even more, a UI would fit in perfectly, but that has the caliber for a full different article. I hope this article was helpful, enjoy the REST of your day.
这是一个后端服务应用程序,可以通过添加更多表并将它们彼此关联来进一步扩展,但是出于本文的目的,我将其保持为非常基础,以便您可以真正掌握REST软件体系结构的思想。 要使这一过程自动化,甚至可以使UI完美配合,但是它具有完整文章的才能。 希望本文对您有所帮助,并享受您一天的休息。
翻译自: https://medium.com/@igorzelaya/building-a-restful-web-service-using-java-d60e93528327
java web构建