You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache本地环境下JSP导入java.sql包失败,访客计数器报错求助

Fixing Your JSP Visitor Counter Syntax Error & Step-by-Step Implementation

Hey there! Let's break down what's going wrong and build that visitor counter properly.

The Root Cause of Your Syntax Error

The error Uncaught SyntaxError: Unexpected token < happens because you used the wrong JSP directive syntax, and Chrome is interpreting your server-side import code as frontend JavaScript. Here's what you did wrong:

  • You wrote <% page import = "java.sql*." %> — this has two critical issues:
    1. JSP page directives start with <%@, not just <% (the latter is for scriptlets, not directives)
    2. The package name is malformed: it should be java.sql.*, not java.sql*.

The correct import line is:

<%@ page import="java.sql.*" %>

This line must go at the very top of your JSP file, before any HTML or frontend code, so the server processes it first.

Step-by-Step Guide to Build Your Visitor Counter

First, a quick note: Apache HTTPD alone can't run JSP files — you need a Servlet container like Apache Tomcat (you can run Tomcat directly, or integrate it with Apache HTTPD if needed, but Tomcat is easier for beginners).

1. Set Up Your Database (e.g., MySQL)

First, create a database and table to store the count:

-- Create database
CREATE DATABASE visitor_counter;

-- Use the database
USE visitor_counter;

-- Create counts table (we'll use a single row to track total visits)
CREATE TABLE visit_tracker (
    id INT PRIMARY KEY AUTO_INCREMENT,
    total_visits INT DEFAULT 0
);

-- Insert initial count (start at 0)
INSERT INTO visit_tracker (total_visits) VALUES (0);

2. Prepare Your JSP File

Create a file named visitorCounter.jsp with the following code. I'll add comments to explain each part for you:

<%@ page import="java.sql.*" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>Visitor Counter</title>
</head>
<body>
    <%
        // Database connection details (update these to match your setup)
        String dbUrl = "jdbc:mysql://localhost:3306/visitor_counter";
        String dbUser = "your_db_username";
        String dbPassword = "your_db_password";
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        int visitCount = 0;

        try {
            // Load MySQL JDBC driver (make sure you have the driver JAR in Tomcat's lib folder!)
            Class.forName("com.mysql.cj.jdbc.Driver");
            
            // Connect to database
            conn = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
            
            // 1. Update the visit count (increment by 1)
            stmt = conn.createStatement();
            stmt.executeUpdate("UPDATE visit_tracker SET total_visits = total_visits + 1 WHERE id = 1");
            
            // 2. Retrieve the updated count
            rs = stmt.executeQuery("SELECT total_visits FROM visit_tracker WHERE id = 1");
            if (rs.next()) {
                visitCount = rs.getInt("total_visits");
            }
        } catch (Exception e) {
            // Handle errors (for beginners, just print the error)
            e.printStackTrace();
        } finally {
            // Close database resources (important to prevent leaks)
            try { if (rs != null) rs.close(); } catch (Exception e) {}
            try { if (stmt != null) stmt.close(); } catch (Exception e) {}
            try { if (conn != null) conn.close(); } catch (Exception e) {}
        }
    %>

    <h1>Welcome! You're visitor #<%= visitCount %></h1>
</body>
</html>

3. Critical Setup Steps

  • Add the JDBC Driver: Download the MySQL JDBC driver (e.g., mysql-connector-java-8.0.30.jar) and place it in the lib folder of your Tomcat installation. Without this, your JSP can't connect to MySQL.
  • Update Database Credentials: Replace your_db_username and your_db_password with your actual MySQL username/password.
  • Run Tomcat: Deploy your JSP file to Tomcat's webapps/ROOT folder (or create a custom web app), start Tomcat, and visit http://localhost:8080/visitorCounter.jsp in your browser.

Common Mistakes to Avoid

  • Don't wrap JSP server-side code (<% ... %>) inside <script> tags — those are for frontend JavaScript, not server-side Java code.
  • Always close database connections/statements/result sets in a finally block to prevent resource leaks.
  • Make sure your Tomcat is running and your JSP is deployed correctly (Tomcat's default port is 8080).

内容的提问来源于stack exchange,提问作者John Hao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:33:59