如何在 JSP 中解析 JSON
How parse JSON in JSP
在页面上以 JSON 格式获取数据,它们如何以 table 格式存在,例如。
@RestController
@RequestMapping("/use_profile")
public class ProfileController {
@Autowired
ProfileService profileService;
@RequestMapping(value = "/my",method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Object getProfile(Principal principal){
try {
final String name = principal.getName();
Profile profile = profileService.getProfileByUserLogin(name);
return profile;
}
catch (Exception e){
return "Error get Profile: " + e.getMessage();
}
}
在JSP中:
> <script type="text/javascript">
> var service = '/use_profile';
> var RestGet = function (id) {
> $.ajax({
> type: 'GET',
> url: service + "/" + id,
> dataType: 'json',
> async: false,
> success: function (result) {
> $('#result').html(JSON.stringify(result));
>
> },
> error: function (jqXHR, textStatus, errorThrown) {
> $('#response').html(JSON.stringify(jqXHR));
> }
> });
> };
> RestGet('my'); </script>
><div class="panel-body" id="result">
结果:
{"id":4,"login":"user","name":"Ivan","surname":"Ivanov","city":"Spb","interests":"many","avatar":null,"aboutMe":null}
如何在 JSP 中解析此数据,例如以 table 形式查看?
您可以使用 JSTL 的 <c:import>
标记向您的 API 端点发送调用,然后将响应包含在变量中。下面是一个例子:
<c:import var="myData" url="/use_profile/my"/>
<c:out value="${myData}"/>
然后使用 ${myData} 构建您的 table.
尝试
$('#result').html(JSON.parse(result));
在页面上以 JSON 格式获取数据,它们如何以 table 格式存在,例如。
@RestController
@RequestMapping("/use_profile")
public class ProfileController {
@Autowired
ProfileService profileService;
@RequestMapping(value = "/my",method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Object getProfile(Principal principal){
try {
final String name = principal.getName();
Profile profile = profileService.getProfileByUserLogin(name);
return profile;
}
catch (Exception e){
return "Error get Profile: " + e.getMessage();
}
}
在JSP中:
> <script type="text/javascript">
> var service = '/use_profile';
> var RestGet = function (id) {
> $.ajax({
> type: 'GET',
> url: service + "/" + id,
> dataType: 'json',
> async: false,
> success: function (result) {
> $('#result').html(JSON.stringify(result));
>
> },
> error: function (jqXHR, textStatus, errorThrown) {
> $('#response').html(JSON.stringify(jqXHR));
> }
> });
> };
> RestGet('my'); </script>
><div class="panel-body" id="result">
结果:
{"id":4,"login":"user","name":"Ivan","surname":"Ivanov","city":"Spb","interests":"many","avatar":null,"aboutMe":null}
如何在 JSP 中解析此数据,例如以 table 形式查看?
您可以使用 JSTL 的 <c:import>
标记向您的 API 端点发送调用,然后将响应包含在变量中。下面是一个例子:
<c:import var="myData" url="/use_profile/my"/>
<c:out value="${myData}"/>
然后使用 ${myData} 构建您的 table.
尝试
$('#result').html(JSON.parse(result));