Портлет Spring 2.5.x MVC с аннотацией и AJAX с jQuery + JSON Ошибка: тип содержимого не может быть установлен в json - PullRequest
3 голосов
/ 02 июля 2010

Когда я пытаюсь использовать spring 2.5.x DispatcherPortlet с LifeRay для использования Ajax, я получаю эту ошибку.Я настроил его с помощью аннотаций.

На уровне класса я использовал следующие аннотации,

Код для контроллера ...

@Controller
@RequestMapping("VIEW")
public class MyController {

@SuppressWarnings("unchecked")
 @RequestMapping(method=RequestMethod.GET) //this is default rendering...
 public String defaultRender(Model model, PortletRequest request) {
 ...
 return "/some/someview";
 }


@RequestMapping(method=RequestMethod.POST,params="action=something") // For ajax call...using jQuery
 public ModelAndView processTotalMatchCount(RenderRequest request, Model model) throws IOException {
  Map<String,String> hmapStockSearchParams = getSomeData(request);  
  Integer totalMatches = service.getTotal(hmapStockSearchParams);
  Map map = new HashMap();
  map.put("totalMatches", totalMatches); 
  return new ModelAndView("ajaxView",map);
 }

}

Из JSP я вызываю следующую функцию JSиспользуя jQuery.

function fetchTotalMatches(){ 
 var url = "<portlet:renderURL><portlet:param name='action' value='something' /></portlet:renderURL>";
  jQuery.ajax({ url: url,
    method: 'POST', 
    //dataType:'json', when i enable this it goes in error bcs response is not in JSON format...
    data: {param1:'one',param2:'two'},      
    success: function(message) {
     alert(message);
     jQuery('input:hidden[@name="total"]').val(message.totalMatches);     
     jQuery('div.secondary-nav').children('div.viewMatches').
      html(message.totalMatches);
    }, 
    error: function(xhr, ajaxOptions, thrownError) {
     alert(xhr.status + " - " + xhr.statusText);
    }
   }
  );
}

Когда я включаю dataType:'json' в вызове jquery, он переходит в функцию ошибки.В противном случае я получу оповещение об ответе всего HTML страницы, определенной в методе defaultRender (тот же самый jsp, из которого я вызываю эту функцию.)

И в консоли я получаю эту ошибку ...

, пожалуйста, помогите относительно этого.Чего мне не хватает?

Я использовал Resolver и View, связанные с Ajax, по этой ссылке ...

http://www.jtraining.com/blogs/ajax-with-spring-mvc-and-jquery.html

[2010-07-02 11:13:41,703][http-8080-4][ERROR] - org.springframework.web.portlet.FrameworkPortlet.processRequest(FrameworkPortlet.java:501) - Could not complete request
 java.lang.IllegalArgumentException
 at com.liferay.portlet.MimeResponseImpl.setContentType(MimeResponseImpl.java:162)
 at org.springframework.web.portlet.DispatcherPortlet.render(DispatcherPortlet.java:1090)
 at org.springframework.web.portlet.DispatcherPortlet.doRenderService(DispatcherPortlet.java:832)
 at org.springframework.web.portlet.FrameworkPortlet.processRequest(FrameworkPortlet.java:483)
 at org.springframework.web.portlet.FrameworkPortlet.doDispatch(FrameworkPortlet.java:453)
 at javax.portlet.GenericPortlet.render(GenericPortlet.java:233)
 at com.sun.portal.portletcontainer.appengine.filter.FilterChainImpl.doFilter(FilterChainImpl.java:126)
 at com.liferay.portal.kernel.portlet.PortletFilterUtil.doFilter(PortletFilterUtil.java:69)
 at com.liferay.portal.kernel.servlet.PortletServlet.service(PortletServlet.java:100)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:630)
 at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:535)
 at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:472)
 at com.liferay.portlet.InvokerPortletImpl.invoke(InvokerPortletImpl.java:618)
 at com.liferay.portlet.InvokerPortletImpl.invokeRender(InvokerPortletImpl.java:700)
 at com.liferay.portlet.InvokerPortletImpl.render(InvokerPortletImpl.java:419)
 at org.apache.jsp.html.portal.render_005fportlet_jsp._jspService(render_005fportlet_jsp.java:1467)
 at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
 at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
 at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:630)
 at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:535)
 at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:472)
 at com.liferay.portal.util.PortalImpl.renderPortlet(PortalImpl.java:2884)
 at com.liferay.portal.util.PortalUtil.renderPortlet(PortalUtil.java:897)
 at com.liferay.portlet.layoutconfiguration.util.RuntimePortletUtil.processPortlet(RuntimePortletUtil.java:170)
 at com.liferay.portlet.layoutconfiguration.util.RuntimePortletUtil.processPortlet(RuntimePortletUtil.java:103)
 at com.liferay.portlet.layoutconfiguration.util.velocity.PortletColumnLogic.processContent(PortletColumnLogic.java:133)
 at com.liferay.portlet.layoutconfiguration.util.velocity.TemplateProcessor.processColumn(TemplateProcessor.java:68)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.doInvoke(UberspectImpl.java:389)
 at org.apache.velocity.util.introspection.UberspectImpl$VelMethodImpl.invoke(UberspectImpl.java:378)
 at org.apache.velocity.runtime.parser.node.ASTMethod.execute(ASTMethod.java:270)
 at org.apache.velocity.runtime.parser.node.ASTReference.execute(ASTReference.java:252)
 at org.apache.velocity.runtime.parser.node.ASTReference.render(ASTReference.java:332)
 at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:336)
 at org.apache.velocity.Template.merge(Template.java:328)
 at org.apache.velocity.Template.merge(Template.java:235)
 at org.apache.velocity.app.VelocityEngine.mergeTemplate(VelocityEngine.java:381)
 at com.liferay.portal.velocity.VelocityEngineImpl.mergeTemplate(VelocityEngineImpl.java:179)
 at com.liferay.portal.kernel.velocity.VelocityEngineUtil.mergeTemplate(VelocityEngineUtil.java:84)
 at com.liferay.portlet.layoutconfiguration.util.RuntimePortletUtil.processTemplate(RuntimePortletUtil.java:237)
 at com.liferay.portlet.layoutconfiguration.util.RuntimePortletUtil.processTemplate(RuntimePortletUtil.java:190)
 at org.apache.jsp.html.portal.layout.view.portlet_jsp._jspService(portlet_jsp.java:831)
 at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
 at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
 at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:630)
 at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:535)
 at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:472)
 at com.liferay.portal.action.LayoutAction.includeLayoutContent(LayoutAction.java:294)
 at com.liferay.portal.action.LayoutAction.processLayout(LayoutAction.java:471)
 at com.liferay.portal.action.LayoutAction.execute(LayoutAction.java:195)
 at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
 at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
 at com.liferay.portal.struts.PortalRequestProcessor.process(PortalRequestProcessor.java:157)
 at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
 at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
 at com.liferay.portal.servlet.MainServlet.callParentService(MainServlet.java:608)
 at com.liferay.portal.servlet.MainServlet.service(MainServlet.java:846)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:630)
 at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
 at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
 at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
 at com.liferay.portal.servlet.FriendlyURLServlet.service(FriendlyURLServlet.java:143)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.strip.StripFilter.processFilter(StripFilter.java:142)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:94)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.gzip.GZipFilter.processFilter(GZipFilter.java:140)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.secure.SecureFilter.processFilter(SecureFilter.java:282)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:94)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.cache.CacheFilter.processFilter(CacheFilter.java:425)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.autologin.AutoLoginFilter.processFilter(AutoLoginFilter.java:257)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.sso.opensso.OpenSSOFilter.processFilter(OpenSSOFilter.java:73)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.sharepoint.SharepointFilter.processFilter(SharepointFilter.java:193)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter.doFilter(VirtualHostFilter.java:191)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.servlet.filters.threadlocalcache.ThreadLocalCacheFilter.processFilter(ThreadLocalCacheFilter.java:55)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:91)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at com.liferay.portal.kernel.servlet.BaseFilter.processFilter(BaseFilter.java:154)
 at com.liferay.portal.kernel.servlet.BaseFilter.doFilter(BaseFilter.java:94)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:738)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:433)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286)
 at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845)
 at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
 at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
 at java.lang.Thread.run(Thread.java:619)

По сути, его нельзя установитьтип контента до application\json согласно приведенному ниже классу

public class AjaxView extends AbstractView {
 private static final Log log = LogFactory.getLog(AjaxView.class);
   private static final String REQUEST_CONTEXT_ATTRIBUTE = RequestContext.class.toString();

 public AjaxView() {
//  super();  
  setRequestContextAttribute(REQUEST_CONTEXT_ATTRIBUTE);
     setContentType("application/json;charset=UTF-8");     
 }
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response) 
    throws Exception {
        log.info("Resolving ajax request view - "+map);        
        JSONObject jsonObj = new JSONObject(map);
        log.info("content Type = " + getContentType());     
//        response.reset();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonObj.toString());
        response.getWriter().flush();
    }
}

Пожалуйста, помогите как можно скорее.Мне нужно, чтобы Ajax-вызов возвращал JSON-строку весной 2.5.x MVC Portlet ...

заранее спасибо.

Ответы [ 3 ]

2 голосов
/ 06 июля 2010

Я не нашел решение с пружиной 2.5.

Итак, я обновился до 3.0.3 и попытался использовать ContentNegotiatingViewResolver с JSON.Но это не удалось.

проверьте вопрос ОШИБКА: 'ContentNegotiatingViewResolver' из Spring 3.0.3 MVC Portlet + JSON для подробного объяснения Spring 3.0.3 моей проблемы.

Наконец, я обнаружил, что Spring 3 не поддерживает портлет JSON.Поэтому я перешел на сервлет и не использовал Spring MVC для JSON.Только для JSP ... я использую его.

1 голос
/ 14 октября 2012

Если вы хотите использовать функции JSON в весеннем портлете MVC, вы должны использовать сопоставление ресурсов, а не сопоставление запросов!

Я не уверен насчет встроенной поддержки Spring MVC для JSON, в Spring я никогда не пробовал (я имею в виду @ResponseBody)

Что я делаю для генерации JSON в SpringВ портлете MVC я создаю JSP-страницу для целей JSON внутри этого JSP

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page contentType="application/json; charset=UTF-8" pageEncoding="UTF-8" %>
<c:out escapeXml="false" value="${outObject}"/>

и в контроллере

     @ResourceMapping("the id for calling from client side")
     public ModelAndView countryRequest(ResourceRequest request, ResourceRequest response) {

.... omit 

    Map<String, String> model = new HashMap<String, String>();
    model.put("outObject", json);
    return new ModelAndView("ajaxResponse", model);
}

. Вы получите результат в случае успешного метода, например:

function <portlet:namespace/>changeSicGroup(){
var sicGroupId = jQuery('#<portlet:namespace/>addBranchsicGroup').val();
jQuery.ajax({
    url: '<portlet:resourceURL id="showSicSector" />',
    global: false,
    type: "POST",
    dataType:'json',
    data: {sicGroupId : sicGroupId}
    ,async:false
    ,success: function(result){
        var targetCom = jQuery('#<portlet:namespace/>addBranchSicSector');
        if(result != null){
            //                    jQuery("#"+targetComId).show();
            targetCom.find('option').remove();
            targetCom.append('<option value=""><spring:message code="pleaseSelectSicSector"/></option >');
            for(var i=0;i< result.length;i++){
                targetCom.append("<option value="+result[i].sectorCode+">"+result[i].desc+"</option>");
            }
            //                    targetCom.attr('disabled',false);
        }else{
            targetCom.find('option').remove();
            targetCom.append('<option value=""><spring:message code="pleaseSelectSicSector"/></option >');
            //                    jQuery("#"+targetComId).hide();
        }
    }
});

}
1 голос
/ 02 июля 2010

Мне кажется, вы должны использовать следующие

  • использовать dataType:'json'
  • использование contentType: "application/json; charset=utf-8"
  • используйте JSON.stringify для преобразования ваших данных (каждое свойство отдельно), которые вы предоставляете для параметров данных.

вы можете увидеть под Как мне построить объект JSON для отправки на AJAX WebService? пример того, как сделать JSON-кодировку. Другая ссылка Могу ли я вернуть JSON из веб-службы .asmx, если ContentType не является JSON? может быть также полезным.

...