SpringMVC首次开发遇404无映射错误,求排查方案
Hey there! Let's walk through fixing that frustrating "No mapping found" error you're seeing when trying to access /Demo/add. I'll break down the issues and step-by-step solutions based on your project files:
1. Missing View Resolver (Critical Issue)
The biggest problem here is that your demo-servlet.xml doesn't have a view resolver configured. Spring needs this to know how to map the string you return from your controller to an actual JSP file. Right now, when you return "display.jsp", Spring doesn't know where to look for it—and returning the full .jsp filename isn't the standard SpringMVC approach anyway.
Fix:
Add this bean to your demo-servlet.xml (right after the <context:component-scan> line):
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- Adjust the prefix to match where you store your JSP files; WEB-INF is a safe, standard location --> <property name="prefix" value="/WEB-INF/views/" /> <!-- Automatically appends .jsp to your returned view name --> <property name="suffix" value=".jsp" /> </bean>
Then update your AddController to return a logical view name (remove the .jsp suffix):
package com.sudeep; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class AddController { @RequestMapping("/add") public String add() { return "display"; // View resolver will turn this into /WEB-INF/views/display.jsp } }
Finally, create a views folder inside WEB-INF and move your display.jsp into it. This keeps your JSPs secure (they can't be accessed directly via URL) and follows SpringMVC best practices.
2. Verify Component Scan is Working
You've got <context:component-scan base-package="com.sudeep"/> in your config, which is correct since your controller is in the com.sudeep package. To confirm Spring is picking up your controller:
- Check your server logs for a line like:
Mapped "{[/add]}" onto public java.lang.String com.sudeep.AddController.add() - If you don't see this line, double-check your package structure (make sure
AddControlleris actually insrc/main/java/com/sudeep) and clean/rebuild your project.
3. Clean & Rebuild Your Project
Eclipse can sometimes have compilation or deployment glitches. Try these steps to refresh everything:
- Right-click your project → Maven → Clean
- Right-click your project → Maven → Install
- Restart your Tomcat server
4. Double-Check Request URL
From your logs, your server is running on port 8081, and your project name is Demo (from pom.xml's finalName). So the correct URL should be http://localhost:8081/Demo/add—your form's action="add" uses a relative path, which is correct here.
After making these changes, your request should map to the controller, and Spring should find your display.jsp file correctly.
内容的提问来源于stack exchange,提问作者Sudeep P Tulpule

