Servlet调用Java EE类方法返回null,登录重定向功能异常求助
Hey there! Let's work through this null return issue in your AuthServlet so you can get that login redirect working. Based on what you've shared, here are the most common fixes to check step by step:
1. First, make sure you're correctly grabbing form parameters in the Servlet
The most likely culprit for null values is mismatched parameter names or accidentally consuming the request body before fetching parameters.
Double-check:
- Your form inputs have
nameattributes exactly matching what you're using inrequest.getParameter(). For example, if your input is<input type="text" name="login">, you need to callrequest.getParameter("login")(case-sensitive!). - You haven't called
request.getReader()orrequest.getInputStream()before usinggetParameter()—these methods consume the request body, making parameters unavailable afterward.
Here's a safe way to fetch your login credentials:
String username = request.getParameter("login"); String password = request.getParameter("password"); // Add a check to catch empty/missing params early if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) { response.sendRedirect("index.jsp?error=emptyFields"); return; }
2. Fix your hardcoded validation logic
If you're calling a custom method to validate the username/password and it's returning null, check for these common mistakes:
- Using
==instead ofequals()for string comparisons:==checks object references, not actual string content. Always useequals()(orObjects.equals()to avoid null pointers) for string matches.- Wrong:
if (username == "admin" && password == "123456") - Right:
if (Objects.equals(username, "admin") && Objects.equals(password, "123456"))
- Wrong:
- Typos in your hardcoded test values: Make sure the username/password you're entering in the form exactly matches what's in your validation code (capitalization, spaces, and special characters matter!).
3. Verify your Servlet mapping matches the form's action
Your form's action is http://localhost:8080/Miniproject/Authservlet—so your Servlet must be mapped to /Authservlet (case-sensitive!).
If you're using annotations, add this to your Servlet class:
@WebServlet("/Authservlet")
If you're using web.xml, ensure your mapping looks like this:
<servlet> <servlet-name>Authservlet</servlet-name> <servlet-class>com.yourpackage.Authservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Authservlet</servlet-name> <url-pattern>/Authservlet</url-pattern> </servlet-mapping>
4. Example working AuthServlet code
Here's a complete, simplified version of your Servlet that uses hardcoded credentials and handles redirects properly:
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 javax.servlet.http.HttpSession; import java.io.IOException; import java.util.Objects; @WebServlet("/Authservlet") public class Authservlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Fetch parameters String username = request.getParameter("login"); String password = request.getParameter("password"); // Validate input presence if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) { response.sendRedirect("index.jsp?error=emptyFields"); return; } // Hardcoded validation boolean isAuthenticated = Objects.equals(username, "testUser") && Objects.equals(password, "testPass123"); if (isAuthenticated) { // Store user in session and redirect to dashboard HttpSession session = request.getSession(); session.setAttribute("loggedInUser", username); response.sendRedirect("dashboard.jsp"); } else { // Redirect back with error response.sendRedirect("index.jsp?error=invalidCredentials"); } } }
5. Add error feedback to your index.jsp
To make debugging easier, add a small snippet to your login page to show error messages:
<% String error = request.getParameter("error"); if (error != null) { switch(error) { case "emptyFields": out.println("<p style='color: red;'>Please fill in both username and password!</p>"); break; case "invalidCredentials": out.println("<p style='color: red;'>Wrong username or password. Try testUser/testPass123!</p>"); break; } } %>
Go through these steps one by one, and you should be able to track down why that null value is popping up. Let me know if any part needs clarification!
内容的提问来源于stack exchange,提问作者Vaaroz

