添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

服务端开发中,有很多知识是相通的,例如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的拆分,一种简单的对应关系为:

PHPJAVA
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/webtest

    以上内容属个人学习总结,如有不当之处,欢迎在评论中指正

    原文链接:
    https://mp.weixin.qq.com/s?__biz=MzI1ODU0Mzk4NQ==&mid=2247483760&idx=1&sn=045fba3ddcee4a444cb8af9cd5d8ca7c&chksm=ea07d96edd705078510aec0d6501559c24eb84b94146179936db3c2b2ab48027510523f2b147&token=1663801279&lang=zh_CN#rd 说来人生际遇无常,因为从小会几手 PS,直到大学,我的人生规划都是做一个平面设计师。大四时由于毕业和女朋友的压力,最终才入了编程的坑。幸好专业是计算机,应付考试的同时,学习专业课也为编程打下了一些基础。现在看来,以我的直男审美,第一批被阿里的鲁班这样的人工智能替代的人中就有我。 学习过程中的鸡汤不再泼洒,这里必须夸赞一下 PHP 非常平缓的学习曲线。语法简单能让人快速入手,解释性语言的特性也让人更易于理解,而且做出些什么产生的成就感会让人更愿意去学习。不过 PHP 是一个易懂难精的语言,前期使用它进 php顺序员可以java吗?可以。关于专业顺序员来讲,在差别的开辟场景下采纳差别的编程言语是比较罕见的事变,所以许多顺序员在事情一段时候以后都邑控制多种差别的编程言语,比方不少Web顺序员都邑同时控制JavaPHP、C#等编程言语。关于顺序员来讲,在控制一门编程言语以后,再进修其他编程言语也相对比较轻易,完全可以一边运用一边进修。别的,大部分顺序开辟使命都有严厉的开辟周期请求,许多情况下并不许... 网络安全产业就像一个江湖,各色人等聚集。相对于欧美国家基础扎实(懂加密、会防护、能挖洞、擅工程)的众多名门正派,我国的人才更多的属于旁门左道(很多白帽子可能会不服气),因此在未来的人才培养和建设上,需要调整结构,鼓励更多的人去做“正向”的、结合“业务”与“数据”、“自动化”的“体系、建设”,才能解人才之渴,真正的为社会全面互联网化提供安全保障。 function bter_query($path, array $req = array()) {// API settings, add your Key and Secret at here$key = '';$secret = '';// generate a nonce to avoid problems with 32bits systems$mt = explode(' ', mic... 如果你想将 PHP 代码换成 Java 代码,你需要找到一个能够完成这个任务的工具。不过要注意,这种换并不是完全自动化的过程,所以你可能需要手动调整换后的 Java 代码,使其能够正常工作。还有一点要注意的是,PHPJava 是两种不同的编程语言,它们之间的差异很大,所以在换过程中可能会有一些不可避免的限制和困难。希望这些信息对你有帮助。 码云项目推荐1、项目名称: 中文拼音库 pinyin4j项目简介:Pinyin4j 是一个流行的 Java 库,支持中文字符和拼音之间的换。拼音输出格式可以定制。2、项目名称:汉字/拼音工具库 Pinyin4Net项目简介:Pinyin4Net 是一个 .net 下的汉字/拼音工具库。现支持 .net2.0, .net4.0, .netcore1.1 ( standaedlib1.6 ... 1、PHP依然是改变世界的语言,Facebook早期就是建立在PHP之上,型不意味着PHP不够强大,而是场景选择和架构选择的结果 2、为什么型?个人理解是PHP更面向前台业务,服务层和中台技术选型应该多选择支持多线程和协程的技术如Java和Golang,当 然还有很多。 3、之所以Java还是要看Java是否在团队内是大众语言,在语言统一上来看,只要成本可接受,收益还是很明显,全团队可以做到... 从PHP研发工程师型到了Java工程师,丰富研发技术栈。接下来,需要继续加深自己对项目中相关技术的深入理解,源码分析阅读,提升架构设计能力。在技术方面之外,逐步提升自己的外部沟通能力。夯实基础,长风破浪会有时,直挂云帆济沧海! function bter_query($path, array $req = array()) {// API settings, add your Key and Secret at here$key = '';$secret = '';// generate a nonce to avoid problems with 32bits systems$mt = explode(' ', mic... 将 PHP 翻译成 Java 非终结符: 开始 -> S | SFUNC S -> ECHOPRINT PRINT_EXPR ); S -> VAR_EXPR ; S -> while ( UNEQ ) { S } S -> 对于 FOR_EXPR { S } S -> INPHP SFUNC -> FUNC FTYPE FUNAME ( 参数 ) { S RETURN} FUNC -> 私有静态FTYPE -> 无效 | 类型参数 -> e | 参数参数 -> 类型 VAR | 类型变量,参数返回 -> e | 返回 NUMVAR ; S -> S_IF | S_ELSE S_IF -> if ( UNEQ ) { S } S_ELSE -> else { S } | 否则 S_IF INPHP -> e ECHOPRINT -> System.out.println( PRINT_E publicfunctionPOST($data){$this->genPostData($data);$curl=curl_init();curl_setopt($curl,CURLOPT_URL,$this->url);curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);curl_setopt($c...public function POST(... 我正在尝试使用php脚本运行Java程序。首先,php显示一个表单,用户可以在其中输入两个值:价格和销售税率。接下来,它提取值并将其传递给Java程序(预编译为.class文件)。我不确定是否在所有Java代码正常工作的情况下将输出打印在了哪里。我的最终目标是在html页面中向用户显示结果。我将文件内容上传到Web服务器,并尝试从那里运行它。更新:如何使用shell_exec或exec运行Java...