JSP注册表单连接MongoDB遇HTTP 500错误,求解决方案及示例
Hey there! Let's break down your problem and fix it step by step. First off: using a POST Servlet to handle registration requests is absolutely the right approach — since registration involves sensitive data like passwords, POST keeps parameters hidden from URLs, which is way more secure than GET. This is standard practice for form submissions in web development.
Core Error: ClassNotFoundException: com.mongodb.Mongo
This error means your web project is missing the MongoDB Java driver dependencies, so Tomcat can't find the required MongoDB classes. Here's how to fix it:
1. For Maven/Gradle Projects (Recommended)
If you use a build tool, add the official MongoDB Java driver dependency. Note that the com.mongodb.Mongo class you used is from the old 2.x driver; the modern 3.x+ driver uses MongoClient instead.
Maven Dependency (Latest Stable Version Example)
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> </dependency>
Gradle Dependency
implementation 'org.mongodb:mongodb-driver-sync:4.11.1'
2. For Non-Build Tool Projects
Manually download the core MongoDB driver JARs (mongodb-driver-sync, mongodb-driver-core, bson) and place them in your web project's WEB-INF/lib directory. Then redeploy your project to Tomcat.
Code Fixes & Optimizations
Your existing code has a few mismatches and outdated practices. Here's the corrected, improved implementation:
1. Revised JSP Registration Page
(Keeps your original UI structure, fixes parameter consistency and adds basic security)
<jsp:include page="../main/header.jsp"/> <% /* signup block */ %> <div class="container-fluid" style="padding-bottom: 50px"> <div class = "jumbotron" style="margin-top:50px"> <div class= "row" style="background-image:url(<%=Common.url%>smolink_sky.jpg);width:100%;height:100%;border-radius:50%;background-position:bottom left"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="padding-top:50px; padding-bottom: 50px;text-align:right"> <p style="text-indent:30px;color:silver; font-size:19px"></p> <div class="nav-link"> <a href="signup" style="background-color:orange; color:white; padding:5px"><b>NEW USER?</b></a> </div> <form method="POST" action="sendinglog"> <fieldset class="form-group"> <p style="color:white; text-indent:20px; text-shadow: 1px 1px 1px #000000 ">USERNAME:</p> <input type="text" name="yuname" size="30" style="border-radius:13%" required><br> </fieldset> <fieldset class="form-group"> <p style="color:white; text-indent:20px; text-shadow: 1px 1px 1px #000000">PASSWORD:</p> <input type="password" name="ypname" size="30" style="border-radius:13%" required><br> </fieldset> <input type="submit" class="btn btn-info" name="Signup" value="SIGNUP" style="margin-left:235px;color:white;text-shadow: 1px 1px 1px #000000"> </form> </div> </div> </div> </div> <% /* End of signup block */ %> <jsp:include page="../main/footer.jsp"/>
Optimizations: Changed password input to
type="password"to hide plaintext; addedrequiredattribute for basic frontend validation.
2. Revised POST Servlet (Using Modern MongoDB Driver)
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoCollection; import org.bson.Document; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @WebServlet(name = "sendinglog", urlPatterns = "/sendinglog") public class SendingLogServlet extends HttpServlet { // Password encryption (MD5 example; use BCrypt/Argon2 in production for better security) private String encryptPassword(String password) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(password.getBytes()); byte[] bytes = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set request encoding to avoid Chinese garbled characters request.setCharacterEncoding("UTF-8"); String username = request.getParameter("yuname"); String password = request.getParameter("ypname"); // Use try-with-resources to auto-close MongoDB resources try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) { MongoDatabase database = mongoClient.getDatabase("smol"); MongoCollection<Document> collection = database.getCollection("customers"); // Create user document with encrypted password Document userDoc = new Document("_id", username) .append("password", encryptPassword(password)); // Insert document into collection collection.insertOne(userDoc); System.out.println("User registered successfully, document inserted"); // Redirect to homepage after successful registration response.sendRedirect("index.jsp"); } catch (Exception e) { e.printStackTrace(); // Redirect back to signup page with error flag if registration fails response.sendRedirect("signup.jsp?error=1"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Redirect GET requests to signup page directly response.sendRedirect("signup.jsp"); } }
Key Fixes & Optimizations:
- Replaced deprecated
Mongoclass with modernMongoClient- Used
try-with-resourcesto automatically manage MongoDB connections (avoids resource leaks)- Added request encoding to fix Chinese username garbling
- Encrypted passwords before storing (never save plaintext passwords!)
- Fixed parameter name mismatch (matches JSP's
yuname/ypname)- Added error handling for failed registration
Additional Notes
- Make sure your local MongoDB service is running on
localhost:27017 - In production, don't hardcode MongoDB connection strings — use a configuration file instead
- Add duplicate username checks to prevent duplicate registrations
- Add more frontend validation (e.g., password length, username format) to improve user experience
内容的提问来源于stack exchange,提问作者user9800713

