亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

Java主流技術學習:從入門到實踐的簡單教程

概述

本文全面介绍了Java主流技术学习的入门知识,包括JDK安装、环境配置、基本语法和面向对象编程等内容。文章还深入讲解了Servlet、JSP、Spring、Hibernate、MyBatis、Struts2等主流开发框架,并涵盖了Web技术、并发编程等高级话题。通过实战案例,读者可以更好地掌握Java主流技术的实际应用。

Java基础入门

安装JDK和配置环境变量

安装JDK

  1. 访问JDK官方网站下载页面,选择合适的JDK版本和操作系统下载安装包。
  2. 双击安装包,按照提示完成安装过程。

配置环境变量

  1. 打开系统环境变量设置对话框。
  2. 在系统变量中添加JAVA_HOME,设置其值为JDK的安装目录(如C:\Program Files\Java\jdk-19.0.1)。
  3. 在系统变量中添加Path,在其值中添加%JAVA_HOME%\bin
  4. 重新启动命令提示符并输入命令java -version,确认安装和配置是否成功。

第一个Java程序:Hello World

创建HelloWorld程序

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

运行HelloWorld程序

  1. 将上述代码保存为HelloWorld.java 文件。
  2. 打开命令提示符,切换到保存该文件的目录。
  3. 运行命令 javac HelloWorld.java 编译程序。
  4. 执行命令 java HelloWorld 运行程序,命令行中应输出 "Hello, World!"。

Java基本语法介绍

变量与类型

public class Variables {
    public static void main(String[] args) {
        int age = 25;
        double height = 1.75;
        String name = "张三";
        boolean isMarried = true;

        System.out.println(age);
        System.out.println(height);
        System.out.println(name);
        System.out.println(isMarried);
    }
}

注释

public class Comments {
    public static void main(String[] args) {
        // 单行注释
        int x = 5;

        /*
        多行注释
        可以跨越多行
        */

        /* 单行注释也可以这样写 */
    }
}

流程控制

public class ControlFlow {
    public static void main(String[] args) {
        int x = 10;

        if (x > 5) {
            System.out.println("x大于5");
        } else {
            System.out.println("x不大于5");
        }

        for (int i = 0; i < 5; i++) {
            System.out.println("循环次数:" + i);
        }

        int count = 0;
        while (count < 5) {
            System.out.println("while循环次数:" + count);
            count++;
        }
    }
}

常见数据类型和变量使用

Java提供了多种基本数据类型和变量,包括整型、浮点型、字符型、布尔型等。此外,还可以使用数组和集合来存储和操作数据。

数据类型

public class DataTypes {
    public static void main(String[] args) {
        byte b = 127;
        short s = 32767;
        int i = 2147483647;
        long l = 9223372036854775807L;
        float f = 3.14f;
        double d = 3.1415926;
        char c = 'A';
        boolean bl = true;

        System.out.println(b);
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);
        System.out.println(c);
        System.out.println(bl);
    }
}

数组

public class ArrayExample {
    public static void main(String[] args) {
        int[] numbers = new int[5];
        numbers[0] = 1;
        numbers[1] = 2;
        numbers[2] = 3;
        numbers[3] = 4;
        numbers[4] = 5;

        for (int i = 0; i < numbers.length; i++) {
            System.out.println(numbers[i]);
        }
    }
}

集合

import java.util.ArrayList;
import java.util.List;

public class CollectionExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("张三");
        names.add("李四");
        names.add("王五");

        for (String name : names) {
            System.out.println(name);
        }
    }
}

Java面向对象编程概念

类与对象

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void introduce() {
        System.out.println("我的名字是:" + name + ",我今年" + age + "岁。");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("张三", 25);
        person.introduce();
    }
}

继承

public class Animal {
    String name;

    public void eat() {
        System.out.println(name + "正在进食。");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println(name + "正在吠叫。");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.name = "旺财";
        dog.eat();
        dog.bark();
    }
}

多态

public class Animal {
    String name;

    public void eat() {
        System.out.println(name + "正在进食。");
    }
}

public class Dog extends Animal {
    public void bark() {
        System.out.println(name + "正在吠叫。");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.name = "旺财";
        animal.eat();
        // 以下代码会编译失败,因为Animal类中没有bark方法
        // ((Dog)animal).bark();
    }
}

接口与实现

public interface Animal {
    void eat();
}

public class Dog implements Animal {
    String name;

    @Override
    public void eat() {
        System.out.println(name + "正在吃狗粮。");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal dog = new Dog();
        dog.name = "旺财";
        dog.eat();
    }
}

Java核心概念详解

类与对象

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void introduce() {
        System.out.println("我的名字是:" + name + ",我今年" + age + "岁。");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person("张三", 25);
        person.introduce();
    }
}

继承与多态

public class Animal {
    String name;

    public void eat() {
        System.out.println(name + "正在进食。");
    }
}

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println(name + "正在吃狗粮。");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Dog();
        animal.name = "旺财";
        animal.eat();  // 输出:旺财正在吃狗粮。
    }
}

泛型和集合框架

import java.util.List;
import java.util.ArrayList;

public class GenericExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

异常处理机制

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int a = 10;
            int b = 0;
            int result = a / b;
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0!");
        } finally {
            System.out.println("程序执行完毕。");
        }
    }
}

Java主流开发框架入门

Servlet和JSP基础

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Servlet和JSP示例</title>
</head>
<body>
    <h1>欢迎来到Servlet和JSP示例页面!</h1>
    <p>这是通过JSP页面动态生成的内容。</p>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorldServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello World</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

Spring框架简介

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

@RestController
public class HelloWorldController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

Hibernate与MyBatis数据持久化

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateExample {
    public static void main(String[] args) {
        SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        User user = new User();
        user.setName("张三");
        user.setAge(25);
        session.save(user);

        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }
}
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisExample {
    public static void main(String[] args) throws IOException {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("MyBatisConfig.xml"));
        SqlSession session = sqlSessionFactory.openSession();

        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user.getName());
        session.close();
    }
}

Struts2 Web应用开发

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldAction extends ActionSupport {
    private String message;

    public String execute() {
        message = "Hello World!";
        return SUCCESS;
    }

    public String getMessage() {
        return message;
    }
}
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Hello World - Struts 2 Application</title>
</head>

<body>
    <h1>消息: ${message}</h1>
</body>
</html>

Maven项目构建与管理

<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-project</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Java Web技术入门

HTML与CSS基础

<!DOCTYPE html>
<html>
<head>
    <title>HTML与CSS示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
        }
        h1 {
            color: #333;
        }
        p {
            color: #666;
        }
    </style>
</head>
<body>
    <h1>欢迎来到HTML与CSS示例页面!</h1>
    <p>这是通过HTML和内嵌CSS生成的内容。</p>
</body>
</html>

JavaScript与DOM操作

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript与DOM示例</title>
    <script>
        function changeColor() {
            document.getElementById("myParagraph").style.color = "red";
        }
    </script>
</head>
<body>
    <h1>JavaScript与DOM示例</h1>
    <p id="myParagraph">这是一个段落。</p>
    <button onclick="changeColor()">改变颜色</button>
</body>
</html>

使用Tomcat服务器部署Java Web应用

  1. 下载并安装Tomcat服务器。
  2. 将编译好的Java Web应用放置到Tomcat服务器的webapps目录下。
  3. 启动Tomcat服务器,访问http://localhost:8080/应用名

前后端分离开发入门

  1. 使用前端框架如React或Vue.js构建前端应用。
  2. 使用后端框架如Spring Boot构建后端应用。
  3. 通过RESTful API进行前后端通信。

RESTful API设计与实现

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

@RestController
public class HelloWorldController {
    @GetMapping("/hello")
    public String hello() {
        return "Hello, RESTful API!";
    }
}

Java并发编程入门

线程与进程

  • 线程是进程中更小的执行单元。
  • 进程是操作系统进行资源分配和调度的基本单位。
public class SimpleThreadExample {
    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println("线程1执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程1结束");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("线程2执行");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("线程2结束");
        });

        t1.start();
        t2.start();
    }
}

并发控制与同步

  • 使用synchronized关键字进行同步。
public class Counter {
    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public synchronized int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("最终计数结果:" + counter.getCount());
    }
}

Java并发工具类(如ConcurrentHashMap)

import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();

        map.put("key1", "value1");
        map.put("key2", "value2");

        System.out.println(map.get("key1"));
        System.out.println(map.get("key2"));

        map.putIfAbsent("key3", "value3");
        map.putIfAbsent("key1", "new_value1");

        System.out.println(map.get("key1"));
    }
}

常见并发问题与解决方案

  • 死锁问题
public class DeadlockExample {
    public static void main(String[] args) {
        String resource1 = "resource1";
        String resource2 = "resource2";

        Runnable r1 = () -> {
            synchronized (resource1) {
                System.out.println("r1 执行 resource1");
                synchronized (resource2) {
                    System.out.println("r1 执行 resource2");
                }
            }
        };

        Runnable r2 = () -> {
            synchronized (resource2) {
                System.out.println("r2 执行 resource2");
                synchronized (resource1) {
                    System.out.println("r2 执行 resource1");
                }
            }
        };

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();
    }
}
  • 解决方案:
    • 使用Lock接口和ReentrantLock类。
    • 使用try-finally确保锁的释放。
    • 使用Thread.join()等待其他线程完成。

编程案例:多线程爬虫

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SimpleWebCrawler {
    public static void main(String[] args) throws Exception {
        String url = "https://www.example.com";
        URL urlObj = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
        connection.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    }
}

实战项目案例

个人博客系统设计与实现

  1. 数据库设计
CREATE TABLE `users` (
    `id` INT(11) PRIMARY KEY AUTO_INCREMENT,
    `username` VARCHAR(50) NOT NULL,
    `password` VARCHAR(200) NOT NULL,
    `email` VARCHAR(100) NOT NULL
);

CREATE TABLE `posts` (
    `id` INT(11) PRIMARY KEY AUTO_INCREMENT,
    `title` VARCHAR(100) NOT NULL,
    `content` TEXT NOT NULL,
    `author_id` INT(11) NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (`author_id`) REFERENCES `users`(`id`)
);
  1. 后端逻辑实现
import java.sql.*;

public class BlogApplication {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/blog";
        String username = "root";
        String password = "password";

        Connection connection = DriverManager.getConnection(url, username, password);
        Statement statement = connection.createStatement();

        String createUsers = "CREATE TABLE IF NOT EXISTS users (id INT PRIMARY KEY, username VARCHAR(50), password VARCHAR(200), email VARCHAR(100))";
        String createPosts = "CREATE TABLE IF NOT EXISTS posts (id INT PRIMARY KEY, title VARCHAR(100), content TEXT, author_id INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (author_id) REFERENCES users(id))";

        statement.execute(createUsers);
        statement.execute(createPosts);

        connection.close();
    }
}

在线购物系统开发

  1. 数据库设计
CREATE TABLE `products` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `name` VARCHAR(100) NOT NULL,
    `price` DECIMAL(10, 2) NOT NULL,
    `stock` INT NOT NULL
);

CREATE TABLE `orders` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `customer_name` VARCHAR(100) NOT NULL,
    `total_price` DECIMAL(10, 2) NOT NULL,
    `status` VARCHAR(50) NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE `order_items` (
    `id` INT PRIMARY KEY AUTO_INCREMENT,
    `order_id` INT NOT NULL,
    `product_id` INT NOT NULL,
    `quantity` INT NOT NULL,
    FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`),
    FOREIGN KEY (`product_id`) REFERENCES `products`(`id`)
);
  1. 后端逻辑实现
import java.sql.*;

public class OnlineShop {
    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/shop";
        String username = "root";
        String password = "password";

        Connection connection = DriverManager.getConnection(url, username, password);
        Statement statement = connection.createStatement();

        String createProducts = "CREATE TABLE IF NOT EXISTS products (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(100), price DECIMAL(10, 2), stock INT)";
        String createOrders = "CREATE TABLE IF NOT EXISTS orders (id INT PRIMARY KEY AUTO_INCREMENT, customer_name VARCHAR(100), total_price DECIMAL(10, 2), status VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
        String createOrderItems = "CREATE TABLE IF NOT EXISTS order_items (id INT PRIMARY KEY AUTO_INCREMENT, order_id INT, product_id INT, quantity INT, FOREIGN KEY (order_id) REFERENCES orders(id), FOREIGN KEY (product_id) REFERENCES products(id))";

        statement.execute(createProducts);
        statement.execute(createOrders);
        statement.execute(createOrderItems);

        connection.close();
    }
}

基于Spring Boot的微服务应用构建

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MicroserviceApplication {
    public static void main(String[] args) {
        SpringApplication.run(MicroserviceApplication.class, args);
    }
}

使用Docker部署Java应用

  1. 创建Dockerfile
FROM openjdk:11-jdk-alpine
COPY target/my-app.jar /app/my-app.jar
ENTRYPOINT ["java", "-jar", "/app/my-app.jar"]
  1. 构建并运行Docker镜像
docker build -t my-java-app .
docker run -p 8080:8080 my-java-app

实战技巧与经验分享

  1. 日志管理
    • 使用SLF4J或Log4j进行日志管理。
  2. 性能优化
    • 使用JVM调优参数。
    • 使用Profiler工具进行性能分析。
  3. 代码质量管理
    • 使用静态代码分析工具如Checkstyle或FindBugs。
  4. 持续集成与持续部署
    • 使用Jenkins或GitHub Actions进行CI/CD。
點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消