gpt4 book ai didi

java - spring mvc 使用 json 而不是 ${variable}

转载 作者:行者123 更新时间:2023-12-02 07:51:35 26 4
gpt4 key购买 nike

基本上,我目前正在开发一个 MVC 项目,我可以使用以下类将值从服务器传递到客户端...

package org.assessme.com;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserManagementController {

private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/userManagement", method = RequestMethod.GET)
public Object home(Locale locale, Model model) {
logger.info("User management view controller loaded...");

Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

String formattedDate = dateFormat.format(date);

model.addAttribute("serverTime", formattedDate );
return "userManagement";
}
}

然后可以使用符号访问...

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>

<P> The time on the server is ${serverTime}. </P>
</body>
</html>

我的问题是,我如何更改这个项目,以便我可以使用 JSON 作为 Ajax 请求,比如用户单击一个具有...的按钮

function userManage(){
$('div.mainBody').load('userManagement');
}

我希望 userManagement 返回 View userManagement (就像现在一样),但也返回用户的 json 响应。

有人可以给我任何建议吗?

谢谢

最佳答案

this post ,作者解释了如何使用 Spring 实现这一目标。

在你的 Controller 中,你应该有类似下面的内容来返回 JSON。

@RequestMapping(value="/availability", method=RequestMethod.GET)
public @ResponseBody AvailabilityStatus getAvailability(@RequestParam String name) {
for (Account a : accounts.values()) {
if (a.getName().equals(name)) {
return AvailabilityStatus.notAvailable(name);
}
}
return AvailabilityStatus.available();
}

在您看来,您应该使用 JQuery 编写请求。

$(document).ready(function() {
// check name availability on focus lost
$('#name').blur(function() {
checkAvailability();
});
});

function checkAvailability() {
$.getJSON("account/availability", { name: $('#name').val() }, function(availability) {
if (availability.available) {
fieldValidated("name", { valid : true });
} else {
fieldValidated("name", { valid : false,
message : $('#name').val() + " is not available, try " + availability.suggestions });
}
});
}

编辑:您还应该检查 this answear 。如果您将 Jackson jar 添加到您的库中,Spring 将开始将您的 POJOS 解析为 JSON。

关于java - spring mvc 使用 json 而不是 ${variable},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164736/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com