Spring MVC accesses fetch data with. html as the suffix, 406 not acceptable error.

Source: Internet
Author: User
Tags response code

Title, the recent use of spring MVC as a background framework, when the front end asynchronously fetches data (. html is the way to access the suffix name), 406 not acceptable error. Originally did not know what reason, the front and back station all did not have the error to return the data, therefore looked up the next HTTP 406 response code: 406 (sc_not_acceptable) indicates that the MIME type of the requested resource is inconsistent with the type specified in the Accept header information in the client. Here's a look at the operating procedure and code for the error:

1. First configure the Spring MVC core servlet (Dispatcherservlet) to Web. XML, where the configuration can be a request with the. html and. Do suffix names. (note: Only important code is displayed, as well as below)

    <servlet>        <Servlet-name>Dispatcherservlet</Servlet-name>        <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>        <Init-param>            <Param-name>Contextconfiglocation</Param-name>            <Param-value>Classpath:dispatcher-servlet.xml</Param-value>        </Init-param>    </servlet>    <servlet-mapping>        <Servlet-name>Dispatcherservlet</Servlet-name>        <Url-pattern>*.html</Url-pattern>    </servlet-mapping>    <servlet-mapping>        <Servlet-name>Dispatcherservlet</Servlet-name>        <Url-pattern>*.do</Url-pattern>    </servlet-mapping>

2, the controller part of the code is as follows:

@RequestMapping (value= "Chat/startclient") @ResponseBody  Publicajaxresult startclient (userentity user,httpservletrequest request) {Ajaxresult result=NewAjaxresult (1); if(User.getuserid () = =NULL) {User.setuserid (System.currenttimemillis ());        Sessionutil.setattr (Request, Sessionutil.session_user, USER); } Else{userentity Sessionuser=Sessionutil.getuser (Request); if(Sessionuser.getuserid (). Equals (User.getuserid ())) {User=Sessionuser; }        }        if(client.startclient (user)) {result.setdata (user); }        returnresult; }

3. The JSP asynchronous request code is as follows:

  $.ajax ({URL:   "${ pagecontext.request.contextpath}/chat/startclient.html  '  ' JSON '  "Input[name=userid]"). Val (), username:$ ("#userName" Span style= "color: #000000"). Val ()}, Success:  function   var  State = ResU          Lt.error;  if  (state = = 1 '. Modal-header. C        Lose '  "input[name=username]"). Val ($ ("#userName"  

To configure the above code startup project to access the Async method in the JSP above, the browser's developer tool (Google) to view the results of the request is as follows, in response to the head to see Content-type is really different, the return is text/html, and the request is application/ JSON, so the browser cannot parse or accept such a type, error 406 errors.

In view of the above situation in the online toss for a while, finally found the method of cracking, the main reason for the problem: Spring MVC is a bit different, if you do not configure what kind of request to respond to what way, it will be based on the URL suffix name corresponding to the format of the response header, As follows:

 Public classMediaTypeextendsMimeTypeImplementsserializable{Private Static Final LongSerialversionuid = 2069937152339670231L;  Public Static FinalMediaType all = ValueOf ("*/*");  Public Static FinalString all_value = "*/*";  Public Static FinalMediaType Application_atom_xml = valueOf ("Application/atom+xml");  Public Static FinalString application_atom_xml_value = "Application/atom+xml";  Public Static FinalMediaType application_form_urlencoded = valueOf ("application/x-www-form-urlencoded");  Public Static FinalString application_form_urlencoded_value = "application/x-www-form-urlencoded";  Public Static FinalMediaType Application_json = valueOf ("Application/json");  Public Static FinalString application_json_value = "Application/json";  Public Static FinalMediaType Application_octet_stream = valueOf ("Application/octet-stream");  Public Static FinalString application_octet_stream_value = "Application/octet-stream";  Public Static FinalMediaType Application_xhtml_xml = valueOf ("Application/xhtml+xml");  Public Static FinalString application_xhtml_xml_value = "Application/xhtml+xml";  Public Static FinalMediaType Application_xml = valueOf ("Application/xml");  Public Static FinalString application_xml_value = "Application/xml";  Public Static FinalMediaType image_gif = valueOf ("Image/gif");  Public Static FinalString image_gif_value = "Image/gif";  Public Static FinalMediaType image_jpeg = valueOf ("Image/jpeg");  Public Static FinalString image_jpeg_value = "Image/jpeg";  Public Static FinalMediaType image_png = valueOf ("Image/png");  Public Static FinalString image_png_value = "Image/png";  Public Static FinalMediaType Multipart_form_data = valueOf ("Multipart/form-data");  Public Static FinalString multipart_form_data_value = "Multipart/form-data"; Public static Final mediatype text_html = valueOf ("text/html");  public static final String text_html_value = "text/html";  Public Static FinalMediaType Text_plain = valueOf ("Text/plain");  Public Static FinalString text_plain_value = "Text/plain";  Public Static FinalMediaType Text_xml = valueOf ("Text/xml");  Public Static FinalString text_xml_value = "Text/xml"; Private Static FinalString param_quality_factor = "Q";}

Workaround: So we are going to configure this situation to change the type of HTML that corresponds to the return. (Note: 1, first declare I use the spring version: 4.1.9,2, if you want to use @responsebody return JSON format, you need to load these three packages: Jackson-core, Jackson-databind and jackson-annotations, please go to mvn repository) generally we are configured in the MVC configuration file need to configure <mvc:annotation-driven/ So we just have to modify it here, and modify the configuration code as follows:

    <Mvc:annotation-drivenContent-negotiation-manager= "Contentnegotiationmanager" />    <!--with. html as the suffix, the default return data type is text/html, so to modify the returned data type -    <BeanID= "Contentnegotiationmanager"class= "Org.springframework.web.accept.ContentNegotiationManagerFactoryBean">         < Propertyname= "MediaTypes">              <Map>                  <entryKey= "html"value= "Application/json;charset=utf-8"/>             </Map>          </ Property>     </Bean>

Contentnegotiationmanagerfactorybean is a content negotiation management factory Bean object that is used primarily to configure multi-view request formats.

One of them asked me, "why use. html as the suffix name to access, if not use it, there will be no such errors appear, more convenient." In fact, I think I'm using. html as a suffix to access, so that the URL forms a pseudo-path, relatively enhanced security.

Spring MVC accesses fetch data with. html as the suffix, 406 not acceptable error.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.