杰瑞科技汇

java tomcat mysql

Of course! "Java Tomcat MySQL" is a classic and powerful trio for building web applications. Let's break down what each component is, how they work together, and how to get started.

java tomcat mysql-图1
(图片来源网络,侵删)

High-Level Overview

Think of it as a team with specific roles:

  • Java: The programming language. It's the core logic and the "brain" of your application. You write your business rules, data processing, and application logic in Java.
  • Tomcat: The Web Server / Application Server (Container). It's the "engine" or "host" for your Java application. Its job is to receive requests from web browsers (via HTTP), manage your Java application, and send back responses (like HTML pages, JSON data, etc.). It understands how to run Java web applications that follow certain standards (like the Servlet API).
  • MySQL: The Database. It's the "memory" or "filing cabinet" of your application. It's responsible for persistently storing your application's data (e.g., user information, product listings, blog posts).

Java

  • What it is: A general-purpose, class-based, object-oriented programming language.
  • Its Role: You write your application's code in Java. For web applications, you'll typically use frameworks built on top of Java, such as:
    • Spring Boot: (Highly recommended for modern development) Simplifies building production-ready applications by providing auto-configuration and an embedded server.
    • Jakarta EE (formerly Java EE): A set of specifications for building enterprise-grade applications. Tomcat implements several of these (like Servlets and JSPs).
  • Key Concept: The Java code you write is compiled into bytecode. This bytecode is then executed by the Java Virtual Machine (JVM), which makes Java platform-independent ("write once, run anywhere").

Apache Tomcat

  • What it is: An open-source, web server and servlet container developed by the Apache Software Foundation.
  • Its Role: Tomcat's primary job is to run Java Servlets and JavaServer Pages (JSPs).
    • Servlets: Java classes that handle incoming HTTP requests and generate dynamic responses. They form the backbone of many Java web applications.
    • JSPs: A technology that allows you to embed Java code directly into HTML pages. It's great for creating the view layer of your application.
  • How it fits in:
    1. You package your compiled Java Servlets and JSPs into a WAR (Web Application Archive) file. This is essentially a ZIP file with a specific directory structure.
    2. You deploy this WAR file to the Tomcat server.
    3. Tomcat unpacks the WAR file and makes your application available to be accessed via a URL (e.g., http://localhost:8080/YourAppName).
  • Key Feature: Tomcat is a "lightweight" or "web container" because it implements the core web-related standards (Servlets, JSPs) but doesn't include the full features of a heavy "Java EE Application Server" like WildFly or WebLogic. This makes it fast, easy to manage, and perfect for most web applications.

MySQL

  • What it is: A popular open-source relational database management system (RDBMS).
  • Its Role: To store and manage the structured data for your application.
  • How it fits in:
    1. Your Java application (running in Tomcat) needs to connect to the MySQL database to read or write data.
    2. To do this, your Java code uses a JDBC (Java Database Connectivity) driver. The JDBC driver is a library that translates your Java database calls into a protocol that MySQL understands.
    3. Your application establishes a connection to the MySQL database, executes SQL queries (e.g., SELECT * FROM users WHERE username = ?), and processes the results.

How They All Work Together: A Typical Request Flow

Here's what happens when a user visits your website:

  1. User Request: A user opens their browser and goes to http://localhost:8080/myapp/login.
  2. Tomcat Receives Request: Tomcat's HTTP listener receives the request for the /login page on the myapp application.
  3. Tomcat Invokes Java: Tomcat looks up the request in the web.xml deployment descriptor (or uses annotations in modern apps) and finds that this request should be handled by a specific Java Servlet class (e.g., LoginServlet).
  4. Java Code Executes: Tomcat creates an instance of LoginServlet and calls its service() method (which in turn calls doGet() or doPost()). The Java code inside this servlet now runs.
  5. Database Interaction (Java -> MySQL):
    • The LoginServlet needs to check the user's credentials against the database.
    • It uses the JDBC driver to open a connection to the MySQL database.
    • It creates a SQL query (e.g., SELECT password FROM users WHERE email = ?).
    • It executes the query, passing the user's email as a parameter.
    • MySQL processes the query and returns the user's password.
  6. Java Logic: The LoginServlet receives the result from MySQL. It compares the returned password with the password the user submitted in the login form.
  7. Response Generation:
    • If the credentials match, the servlet might generate a "Welcome" page.
    • If they don't match, it generates an "Invalid Login" error message.
    • This response is typically HTML.
  8. Tomcat Sends Response: The servlet sends the generated HTML response back to Tomcat.
  9. User Receives Response: Tomcat packages the HTML into an HTTP response and sends it back to the user's browser, which then displays the page.

Getting Started: A Simple "Hello, Database!" Example

Here’s a minimal setup to see them in action. We'll use Spring Boot because it dramatically simplifies the process.

Prerequisites

  1. Java Development Kit (JDK): Install JDK 8 or later.
  2. Apache Tomcat: Download and unzip Tomcat. You can run it directly from the bin directory (startup.sh on Linux/macOS, startup.bat on Windows).
  3. MySQL Server: Install MySQL and create a database and a user for your application.
    -- In the MySQL command line
    CREATE DATABASE myapp_db;
    CREATE USER 'myapp_user'@'localhost' IDENTIFIED BY 'your_password';
    GRANT ALL PRIVILEGES ON myapp_db.* TO 'myapp_user'@'localhost';
    FLUSH PRIVILEGES;
  4. IDE: An IDE like IntelliJ IDEA (Community Edition is free) or Eclipse.
  5. Build Tool: Maven or Gradle. Maven is very common.

Step 1: Create a Spring Boot Project

  1. Go to start.spring.io.
  2. Fill in the project metadata:
    • Project: Maven
    • Language: Java
    • Spring Boot: Choose a recent stable version (e.g., 3.x.x).
    • Group: com.example
    • Artifact: demo
    • Packaging: Jar
    • Java: 17 (or your installed version)
  3. Click "ADD DEPENDENCIES" and add:
    • Spring Web: For building web applications (REST controllers).
    • Spring Data JPA: For easy database access.
    • MySQL Driver: The JDBC driver to connect to MySQL.
  4. Click "GENERATE" to download a .zip file. Unzip it and open it in your IDE.

Step 2: Configure application.properties

In the src/main/resources/application.properties file, tell Spring Boot how to connect to your MySQL database.

java tomcat mysql-图2
(图片来源网络,侵删)
# Server Port (optional, default is 8080)
server.port=8080
# Datasource Configuration
spring.datasource.url=jdbc:mysql://localhost:3306/myapp_db?useSSL=false&serverTimezone=UTC
spring.datasource.username=myapp_user
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA (Java Persistence API) Configuration
spring.jpa.hibernate.ddl-auto=update # Automatically updates the schema based on your entities
spring.jpa.show-sql=true # Prints the generated SQL to the console

Step 3: Create a JPA Entity (Java class representing a table)

Create a new Java class src/main/java/com/example/demo/User.java:

package com.example.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
@Entity // Marks this class as a JPA entity (a table in the database)
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // Constructors, Getters, and Setters
    public User() {}
    public User(String name) {
        this.name = name;
    }
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

Step 4: Create a JPA Repository (Interface for database operations)

Create a new interface src/main/java/com/example/demo/UserRepository.java:

package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    // JpaRepository provides CRUD (Create, Read, Update, Delete) methods for free!
    // e.g., findAll(), findById(), save(), deleteById()
}

Step 5: Create a REST Controller

Create a new class src/main/java/com/example/demo/DemoController.java:

package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class DemoController {
    @Autowired // Injects the UserRepository bean
    private UserRepository userRepository;
    @PostMapping
    public String createUser(@RequestParam String name) {
        User user = new User(name);
        userRepository.save(user); // Saves the user to the MySQL database
        return "Created user: " + user.getName() + " with ID: " + user.getId();
    }
    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) {
        return userRepository.findById(id)
                .map(user -> "Found user: " + user.getName())
                .orElse("User not found with ID: " + id);
    }
}

Step 6: Run and Test

  1. Run the DemoApplication.java class from your IDE. Spring Boot will start up, and you'll see logs indicating it's connected to Tomcat (on port 8080) and MySQL.
  2. Test creating a user:
    • Open a tool like Postman or your browser's developer console.
    • Send a POST request to http://localhost:8080/api/users?name=Alice.
    • You should get a response like: Created user: Alice with ID: 1.
  3. Test retrieving a user:
    • Send a GET request to http://localhost:8080/api/users/1.
    • You should get a response like: Found user: Alice.

You have successfully built a Java web application that runs on an embedded Tomcat server, stores data in a MySQL database, and exposes that data via a REST API.

java tomcat mysql-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇