如何在MVC中返回JSON数据表单控制器到jsp

How to return JSON data form controller to jsp in MVC

本文关键字:表单 数据表 控制器 jsp 数据 JSON MVC 返回      更新时间:2023-09-26

我试图从数据库中检索数据,并从控制器返回JSON,以便我可以在jsp中显示该数据的highchart。最初,我试图在alert()中提醒JSON数据,以检查数据是否即将到来。json,我从控制器返回没有填充在警报。有人能帮我一下吗?

ReportModel.java

 import org.springframework.stereotype.Component;
@Component
public class ReportModel {
	int year;
	int population;
	
	public int getYear() {
		return year;
	}
	public void setYear(int year) {
		this.year = year;
	}
	public int getPopulation() {
		return population;
	}
	public void setPopulation(int population) {
		this.population = population;
	}
	@Override
	public String toString() {
		return "reportModel [year=" + year + ", population=" + population + "]";
	}
     	
   }

ReportDao

@Repository
public class ReportDao {
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@SuppressWarnings("deprecation")
	@Autowired
	private SimpleJdbcTemplate simpleJdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public void setSimpleJdbcTemplate(SimpleJdbcTemplate simpleJdbcTemplate) {
		this.simpleJdbcTemplate = simpleJdbcTemplate;
	}
	
	//method to retrieve the data from population table
	@SuppressWarnings("unchecked")
	public List<ReportModel> getReport() {
		final String reportQuery = "SELECT year, population from population";
		 List<ReportModel> report = new ArrayList<ReportModel>();
		 report = jdbcTemplate.query(
				reportQuery, new RowMapper<ReportModel>() {
					public ReportModel mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						ReportModel model = new ReportModel();
						model.setYear(Integer.parseInt(rs.getString("year")));
						model.setPopulation(Integer.parseInt(rs.getString("population")));
						
						return model;
					}
				});
		
		return  report ;
	}
}

ReportImpl

@Service
public class ReportImpl {
	
	@Autowired
	ReportDao reportDao; 
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ReportDao.class);
	 
     	public void setReportDao(ReportDao reportDao) {
		this.reportDao = reportDao;
	}
	
	public List<ReportModel> getReportModels() {
		return reportDao.getReport();
	}  
}

ReportController

@Controller
@RequestMapping("/reportController")
public class ReportController {
	
	@Autowired
	ReportImpl reportImpl;
	
	public void setReportImpl(ReportImpl reportImpl) {
		this.reportImpl = reportImpl;
	}
	public ReportController() {
		super();
		System.out.println("inside Reportconstructor"); 
		}
	@RequestMapping(value = "/getreport", method = RequestMethod.GET)
	@ResponseBody
	 public Object getReportData()
    {
		System.out.println("inside report controller : get Report");
		List<ReportModel> reportModel =  reportImpl.getReportModels();
		Object json = null;
		ObjectMapper objectMapper = new ObjectMapper();
		  try {
			  
			  //display to console
			  json = objectMapper.readValue(
					     objectMapper.writeValueAsString(reportModel), Object.class);
		  
		  }catch(JsonGenerationException e)
		  {
			  e.printStackTrace();
		  } catch (JsonMappingException e)
		  {
			   e.printStackTrace();
		  } catch (IOException e) 
		  {
			   e.printStackTrace();
		  } 
		  
		  return json;
		 
	
    }
}

report.jsp

<html>
  <head>
    <script type="text/javascript">
$(document).ready(function(){
    $("#button").click(function(){
        alert("The button is clicked.");
        
        
        <!--ajax call-->
        $.ajax({
    		type : "GET",
    		url : '/dispatcherServlet/ReportController/getReportData',
    		dataType : "json",
    	    contentType: "application/json",
    	    crossDomain:true,
    		success : function(data) {
    			//console.log(data);
    			//alert(success);
    			for(var i=0;i<data.length;i++)
    				{
    					alert(data[i].name);
    				}
    		}
    			
    			error : function(data) {
    				alert(data);
   				 }
        });
        <!--ajax call-->
        
        
    });
});
</script>
    </head>
  </html>

url不正确:'/dispatcherServlet/ReportController/getReportData',

正确url: '/dispatcherServlet/ReportController/getreport'

问题是您的请求映射