Spring MVC中通过Controller访问后JSP页面无法加载求助
Hey there, let's break down why your houseprice.jsp isn't loading after hitting the Controller. I've dealt with similar AJAX + Spring MVC (I’m assuming you’re using Spring given the Controller mention) setups before, so here are the key areas to troubleshoot:
First up, let’s make sure your AJAX call is set up correctly—this is where most folks trip up. AJAX is an asynchronous request, meaning it won’t automatically redirect to a new page unless you explicitly tell it to. Here’s a check list:
- Confirm the
urlmatches your Controller’s@RequestMappingpath (don’t forget your project’s context path if you have one) - Verify the request method (
GET/POST) aligns with what your Controller expects - Add error handling to catch console logs—this will tell you if you’re getting 404, 500, or other status codes
Example of a properly structured AJAX call:
$.ajax({ url: "/calculateAvgPrice", // Match your Controller's endpoint type: "POST", data: { lat: userLatitude, // Ensure these keys match your Controller's @RequestParam names lng: userLongitude }, success: function(avgPrice) { // If you want to redirect to houseprice.jsp with the data: window.location.href = "/houseprice?avgPrice=" + avgPrice; // OR if you want to load content into the current page: // $("#price-container").text("Average Price: $" + avgPrice); }, error: function(xhr, status, error) { console.log("Request failed: " + error); console.log("Status code: " + xhr.status); } });
A common mistake: Using AJAX but forgetting to handle the page redirect in the success callback—this leaves your page unchanged even if the Controller works fine.
Next, confirm your Controller is handling the request and data correctly. There are two common patterns here, depending on what you want to do:
Pattern 1: Return data to AJAX (then redirect manually)
Use @ResponseBody to send the average price back as a JSON/primitive value:
@Controller public class HousePriceController { @Autowired private HousePriceService priceService; @RequestMapping(value = "/calculateAvgPrice", method = RequestMethod.POST) @ResponseBody // Critical for returning data instead of a view public Double getAveragePrice(@RequestParam("lat") double lat, @RequestParam("lng") double lng) { try { // Your PostgreSQL spatial query logic here (e.g., using ST_DWithin) return priceService.getAvgPriceWithin1km(lat, lng); } catch (Exception e) { e.printStackTrace(); return null; // Or throw a custom exception for frontend handling } } }
Pattern 2: Directly redirect to houseprice.jsp with model data
If you don’t need AJAX, you can skip it and let the Controller return a view with data:
@RequestMapping(value = "/calculateAvgPrice", method = RequestMethod.POST) public ModelAndView showHousePricePage(@RequestParam("lat") double lat, @RequestParam("lng") double lng, Model model) { Double avgPrice = priceService.getAvgPriceWithin1km(lat, lng); model.addAttribute("avgPrice", avgPrice); // Pass data to the JSP return new ModelAndView("houseprice"); // Maps to houseprice.jsp }
Note: If you use this pattern, a standard form submission (instead of AJAX) is simpler.
houseprice.jsp Renders Data Correctly Double-check that your JSP is in the right location (e.g., WEB-INF/views/ for Spring MVC) and that it’s pulling the data correctly:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Local House Prices</title> </head> <body> <h2>Average House Price Within 1km</h2> <%-- Handle null case if no houses are found --%> <p>${avgPrice != null ? '$' + avgPrice : 'No data available for this area'}</p> </body> </html>
- Browser Dev Tools (F12): Go to the Network tab to check your AJAX request:
- 404: Your Controller’s URL path is wrong (or missing context path)
- 500: An error occurred in the Controller/database query—check server logs for details
- 200: Confirm the returned data matches what you expect, then verify your
successcallback logic
- Server Logs: Look for exceptions in your application server logs (e.g., Tomcat’s
catalina.out). Common issues here:- PostgreSQL spatial function errors (e.g., misusing
ST_DWithin, missing spatial indexes) - Database connection issues
- Null pointer exceptions if no houses are found in the 1km range
- PostgreSQL spatial function errors (e.g., misusing
- Mixing up AJAX async behavior with page redirects: AJAX doesn’t trigger page reloads by default—you have to code that
- Mismatched parameter names: Ensure the keys in your AJAX
datamatch the@RequestParamnames in the Controller - Forgetting
@ResponseBody: Without this, Spring will treat your returned Double as a view name, leading to a 404 - Ignoring null values: If no houses exist in the 1km radius, your query will return null—handle this in the Controller or JSP
内容的提问来源于stack exchange,提问作者Degsy

