使用自定义视图解析器和自定义视图的 Spring MVC AJAX 和 JSON
自定义视图:
public class MyView extends AbstractView {
.... awesome stuff ...
}
控制器:
@RequestMapping(value="mylocation")
public ModelAndView dosomething() {
...
modelAndView.setView( new MyView() );
return modelAndView;
}
出于某种原因,这不起作用...我唯一的视图解析器如下:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" >
<property name="exposedContextBeanNames">
<list>
<value>spEnv</value>
</list>
</property>
</bean>
此代码不起作用,因为它试图基于...创建一些 JSP 视图...我不确定,我的表单提交路径;显然没有 JSP 视图,我期望实际上返回 JSON,但由于某种原因这不起作用,它只是试图将我转发到一些 JSP,所以我猜测我需要指定如何在我的 XML 中处理这个问题...但是我已经看到人们返回 JSON 的大约 1000 种不同方式,所有这些方式都让我感到非常困惑,我只是在寻找最简单的方法,所以我可以从那里
编辑:我添加了一个答案,这是一个好的开始,但它允许您在任何 URL 之后输入“.json”,如果作为控制器我不期望它,它会做一些非常糟糕的事情,所以我需要以某种方式使该视图解析器仅适用于受保护的 URL
custom view:
public class MyView extends AbstractView {
.... awesome stuff ...
}
controller:
@RequestMapping(value="mylocation")
public ModelAndView dosomething() {
...
modelAndView.setView( new MyView() );
return modelAndView;
}
For some reason this doesn't work... The only view resolver I have is the following:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" >
<property name="exposedContextBeanNames">
<list>
<value>spEnv</value>
</list>
</property>
</bean>
this code doesn't work because it's trying to create some JSP view based on... I'm not sure, the path of my form submission; and there obviously is no JSP view for it, I'm expecting JSON to be returned actually, but for some reason this isn't working, it's just trying to forward me to some JSP, so I'm guessing that I need to specify how to handle this in my XML... but I've seen about 1000 different ways that people return JSON, and all of them are very confusing to me, I'm just looking for the simplest way, so I can take it from there
edit: I added an answer which is a good start, but it allows you to type ".json" after any URL and it will do some really bad things if as the controller I'm not expecting it, so I need to somehow have this view resolver only apply to secured URLs
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,最后在尝试了一百万种组合之后
,
我真的不明白如何从这里返回一个对象...
但这实际上虽然简单,但非常有用,但这是不可接受的,因为然后我去了其他页面我的网站,只需在 url 后面添加一个任意的“.json”,它就会抛出一个异常,为用户提供太多有关我的应用程序的信息,所以基本上我需要找到一种方法,只在某些控制器上具有此功能是安全的...
有什么想法吗?
Ok, finally after trying a million combinations
and then this
I don't really understand how I can return an object from here...
But this actually, while simple, and very useful is not acceptable because then I went to some other page of my website, and just put an arbitrary ".json" after the url and it threw an exception that gives the users WAY too much information about my application, so basically I need to figure out a way to only have this ability on certain controllers that are secured...
Any Ideas?