关于java:PHP转JAVA开发30分钟实战攻略

4次阅读

共计 8704 个字符,预计需要花费 22 分钟才能阅读完成。

服务端开发中,有很多常识是相通的,例如 mysql,redis,http 协定等。

基于这些根底,在编程语言上的转变并不艰难。

本文次要从上面几点登程,讲述如何疾速从 php 开发转为 java 开发:

  • 应用框架构建 web 我的项目 – 10min
  • 罕用数据结构对应和概念转变 – 5min
  • 操作 Mysql 数据库和发送 http 申请 – 15min

应用框架构建我的项目

先看下 PHP 和 JAVA 对应的我的项目工具和框架:

PHP JAVA
项目管理工具 composer maven
框架 Laravel 或 Thinkphp SpringBoot

java 中,maven 是项目管理工具,实现装置依赖,打包等性能,是一个我的项目的终点,通过 pom.xml 配置文件治理依赖。SpringBoot 实质上就是一个 maven 的依赖包。

相比 php 的框架,SpringBoot 原生提供的性能并不多,然而能够通过 maven 很不便的加载其余性能的依赖

罕用的 java 开发 IDE 是 idea,社区版是收费的,能够间接在官网下载,根本能满足开发需要。

创立我的项目

须要的筹备工作,下载 idea。在零碎中装置 maven 和 jdk,能够间接通过 idea 装置,也能够去官网下载安装。

能够应用官方网站:https://start.spring.io/,来创立 SpringBoot 我的项目,如下图,这里咱们抉择 Spring Web 依赖。

下载解压后,能够看到外面曾经有了 pom.xml 文件,并退出了 SpringBoot 的依赖,应用 idea 加载文件夹:

我的项目引入后,能够看到目录构造曾经建好,接下来实现一个 web api 解决 http 申请,如下:

package com.abc.webtest.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {@GetMapping("/test")
    public String test(){return "hello";}
}
  • 新建一个 controller 文件夹,用来寄存所有解决 http 申请的类
  • 在 php 的框架里通常会把 url 和解决办法的映射放在一个 route.php 文件里
  • 在 SpringBoot 中次要应用注解的形式指定 url 的解决办法

之后能够间接启动利用,默认的端口是:8080。启动后就可在浏览器中拜访:http://localhost:8080/test,返回hello

  • 如果要批改启动的默认端口,能够在 application.yml 中增加如下配置。
server:
  port: 9999

application.yml是 SpringBoot 中用来治理配置的文件,大部分主动配置的组件的配置能够写到这里。例如下面的服务启动端口。

罕用数据结构对应和概念转变

如果要问 php 中最罕用的数据结构是什么?置信大多数答案都是array

绝对的在 java 开发中罕用的数据结构是 ArrayListHashMap,它们能够看成是 array 的拆分,一种简略的对应关系为:

PHP JAVA
array(‘a’,’b’,’c’) ArrayList
array(a’=>1,’b’=>2,’c’=>3) HashMap

理解对应关系有助于在开发中更好的应用对应的构造。

在开发中还有一些概念上的转变:

  • 变量定义

    • php 是弱类型语言,定义变量时能够不指定类型,应用比拟灵便,但也容易出问题。
    • java 是强类型语言,每个变量都要指定类型,不能给变量赋值为别的类型。
  • 每次申请的变量遗留

    • 应用 php-fpm 形式提供服务时,每次申请完结时都会把创立的变量回收,包含动态变量。所以申请间不会有影响
    • SpringBoot 提供服务时,是始终运行的,意味着上次申请创立或批改的变量可能会影响下一次申请,造成问题,这个须要特地留神。尤其是对动态变量的应用。

操作 Mysql 数据库

日常开发中,最罕用的性能就是操作数据库和通过 http 申请调用接口了(微服务调用次要依赖服务框架,这里不波及)。

代码中操作数据库,通常包含两大部分:

  • ORM 长久层映射:负责代码和数据表的操作转换,把表映射为一个对象,通过对象来操作表

    • php 中次要是各框架提供的,例如 Laravel 中的 Eloquent Model
    • java 中较受欢迎的是mybatis-plus,也是把每个表映射为一个实体类
  • 数据库连贯层

    • php 中是 PDO + pdo_mysql 扩大
    • java 中能够应用druid + mysql-connector

上面就介绍下在 java 中应用 mybatis-plus + druid + mysql-connector 操作数据库中的一张表,次要分 5 步。

1. 通过 maven 在 pom.xml 中加载这三个依赖

在应用 SpringBoot 框架时,会常常用到主动配置,在我的项目启动时主动创立须要的对象。

这里间接应用对应的 starter 包,能够在我的项目启动时,主动创立数据库连接池等对象。

      <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!-- mybatis plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
2. 创立表的实体和 Mapper

当初库中有一张表,表名是:main_user

CREATE TABLE `main_user` (`user_id` int(11) NOT NULL AUTO_INCREMENT,
  `password` varchar(100) NOT NULL,
  `user_name` varchar(100) NOT NULL,
  `user_phone` varchar(40) NOT NULL,
  `score` int(11) DEFAULT '0',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

要操作这张表,首先须要创立一个类作为该表的映射,类名就是 MainUser,类的成员就是表中的字段,每个字段的类型须要与数据库中的绝对应,罕用的类型能够很容看进去,其余字段能够百度一下 JdbcType 类型和 Java 类型的对应关系。

public class MainUser extends Model<MainUser> {
    private static final long serialVersionUID = 1L;
    @TableId(value = "user_id", type = IdType.AUTO)
    private Integer userId;
    private String password;
    private String userName;
    private String userPhone;
    private Integer score;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

而后创立一个 Mapper 用于操作这个类,就叫做MainUserMapper

因为这里应用了mybatis-plus,Mapper 能够间接应用很多底层办法,能够只定义一个空接口。

import com.abc.webtest.db.entity.MainUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

public interface MainUserMapper extends BaseMapper<MainUser> {}
3. 在 SpringBoot 中设置 Mapper 的包名

SpringBoot 的 IOC 能够间接生成可用的接口实现对象,只有在启动时指定要扫描的 Mapper 所在的包名。

@SpringBootApplication
@MapperScan("com.abc.webtest.db.mapper") // 这个就是 mapper 包,一个库中表的 mapper 都放在这里
public class WebtestApplication {public static void main(String[] args) {SpringApplication.run(WebtestApplication.class, args);
    }
}
4. 在 application.yml 中设置 mysql 的配置

将连贯 mysql 须要的地址,用户名,明码写入 application.yml 中:

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
      username: root
      password: 123456
5. 在 controller 中操作表

这里简略展现下对表的操作。

在 SpringBoot 中,底层的 IOC 会负责类之间的援用关系,即在 A 中援用 B,不须要手动创建对象,而是应用 Resource 等注解。

上面两个申请实现了对表的插入和按 id 查问。

@RestController
public class TestController {
    // 这里会将要应用的对象加载到该类中
    @Resource
    MainUserMapper mainUserMapper;

    @GetMapping("/test")
    public String test() {return "hello";}

    // 定义 post 申请,这里框架底层会间接将 body 外面的 json 数据,按 key 名赋值给参数中的对象
    @PostMapping("user/register") 
    public Boolean userRegister(@RequestBody MainUser mainUser) {mainUserMapper.insert(mainUser);
        return true;
    }

    @GetMapping("user/info")
    public MainUser userInfo(Integer userId) {MainUser mainUser = new MainUser();
        return mainUserMapper.selectById(userId);
    }
}

发送 HTTP 申请

在开发中,零碎的内部资源除了数据库,最多的就是其余的服务了,这里介绍下 java 中拜访 http 接口的办法。

在 php 中,拜访 http 的底层根本都是用 curl 扩大的相干性能。

在 java 中,一个比拟根底的包是httpclient,首先在 pom.xml 中引入这个包。

    <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
写一个 HttpUtil 类作 Http 的对立申请

这里应用 @Componet 注解,它的作用是通知 Spring 框架将该类作为一个 bean 加载到 IOC 中,供其余类应用。

@Component
public class HttpUtil {CloseableHttpClient client = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(500) // 连贯超时工夫,单位毫秒,按理论状况调整
                    .build())
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setSoTimeout(2 * 1000) // 申请响应超时工夫,单位毫秒,这里设为 2 秒,按理论状况调整
                    .build())
            .build();

    public String get(String url) throws IOException {HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse httpResponse = client.execute(httpGet)) {HttpEntity httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity, "UTF-8");
        }
    }

    public String post(String url, Map<String, String> params) throws IOException {HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse httpResponse = null;
        try {
            // 这里应用了 Jackson 作为 json 转换工具,在 spring-web 依赖中曾经引入,能够间接应用
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(params);
            StringEntity stringEntity = new StringEntity(json, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
            httpResponse = client.execute(httpPost);
            return EntityUtils.toString(httpResponse.getEntity());
        } finally {if (httpResponse != null) {httpResponse.close();
            }
        }
    }
}
在 controller 中应用

这里创立两个简略的接口,应用 GET 和 POST 办法别离调用了两个收费的 api。

同样应用 Resource 加载 HttpUtil 类的对象到 controller 中。

@RestController
public class TestController {
    @Resource
    HttpUtil httpUtil;

    @GetMapping("inaword")
    public String inAWord() throws IOException {return httpUtil.get("http://api.lkblog.net/ws/api.php");
    }

    @GetMapping("create/random")
    public String createRandom(String name, String phone) throws IOException {Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("job", phone);
        return httpUtil.post("https://reqres.in/api/users", params);
    }
}

通过下面的介绍,心愿能帮忙大家更快的上手 java 开发。

残缺的 pom.xml 和 application.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.abc</groupId>
    <artifactId>webtest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webtest</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.1</version>
        </dependency>

        <!-- mybatis plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>

        <!-- httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
application.yml
server:
  port: 9999

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
      username: root
      password: 123456

文章中工程的源代码地址:https://gitee.com/dothetrick/…

以上内容属集体学习总结,如有不当之处,欢送在评论中斧正

正文完
 0