Spring MVC @ResponseStatus Annotation Comment Returns the problem of garbled characters in Chinese

Source: Internet
Author: User

Preface

As mentioned in the previous article, the use of @responsestatus annotations, you can decorate an exception class, in the event of an exception to return the specified error code and message, when the returned reason contains Chinese, there will be a problem with Chinese garbled

phenomena

When reason contains Chinese, the front end is returned as garbled

/**

* Custom Exception classes

*

* @author Administrator

*

*/

@ResponseStatus (value = httpstatus.forbidden, Reason = "No permissions")

public class TestException extends RuntimeException {

Private static final long serialversionuid = 5759027883028274330L;

}

Calling code

/**

* Test throws Exception garbled

*

* @return

*/

@RequestMapping (value = "/say", produces = "text/html;charset=utf-8")

@ResponseBody

String Say2 () {

throw new TestException ();

}

Access Http://localhost:8080/say2 returned garbled

cause

By looking at spring MVC source Discovery, the class that parses this annotation is responsestatusexceptionresolver primarily parsing and invoking response in Resolveresponsestatus Senderror method to send HTML-formatted exception messages to the client because the encoding format does not match, and the Response.setcharacterencoding method is obviously not called.

public class Responsestatusexceptionresolver extends Abstracthandlerexceptionresolver implements Messagesourceaware {

Private Messagesource Messagesource;

public void Setmessagesource (Messagesource messagesource) {

This.messagesource = Messagesource;

}

Protected Modelandview doresolveexception (httpservletrequest request, httpservletresponse response, Object handler, Exception ex)

{

ResponseStatus responsestatus = (responsestatus) annotatedelementutils.findmergedannotation (Ex.getClass (), Responsestatus.class);

if (responsestatus! = null);

try {

Return Resolveresponsestatus (responsestatus, request, response, Handler, ex);

}

catch (Exception Resolveex) {

This.logger.warn ("Handling of @ResponseStatus resulted in Exception", Resolveex);

Break label81:

if (Ex.getcause () instanceof Exception) {

ex = (Exception) ex.getcause ();

return doresolveexception (Request, response, Handler, ex); }

}

Label81:return null;

}

Protected Modelandview resolveresponsestatus (responsestatus responsestatus, httpservletrequest request,

HttpServletResponse response, Object handler, Exception ex) throws Exception {

int statusCode = Responsestatus.code (). value ();

String reason = Responsestatus.reason ();

if (This.messagesource! = null) {

Reason = this.messageSource.getMessage (reason, null, reason, Localecontextholder.getlocale ());

}

if (! ( Stringutils.haslength (reason))) {

Response.senderror (StatusCode);

} else {

Response.senderror (statusCode, reason);

}

return new Modelandview ();

}

}

Spring is characterencodingfilter to set the request and response encoding format, see the code below, go to this step, you need to see SPIRNG boot is where to define the filter

@Override

protected void Dofilterinternal (

HttpServletRequest request, HttpServletResponse response, Filterchain Filterchain)

Throws Servletexception, IOException {

if (this.encoding! = null && (this.forceencoding | | request.getcharacterencoding () = = null)) {

Request.setcharacterencoding (this.encoding);

if (this.forceencoding) {

Response.setcharacterencoding (this.encoding);

}

}

Filterchain.dofilter (request, response);

}

View code, is set in Httpencodingautoconfiguration this configuration class, the code is as follows, here is a property class httpencodingproperties to see the code, called the Shouldforce method, So just one setting, you can force him to set the encoding format spring.http.encoding.force=true

public class Httpencodingautoconfiguration {

Private final httpencodingproperties properties;

Public Httpencodingautoconfiguration (Httpencodingproperties properties) {

This.properties = properties;

}

@Bean

@ConditionalOnMissingBean ({characterencodingfilter.class})

Public Characterencodingfilter Characterencodingfilter () {

Characterencodingfilter filter = new Orderedcharacterencodingfilter ();

Filter.setencoding (This.properties.getCharset (). name ());

Filter.setforcerequestencoding (This.properties.shouldForce (HttpEncodingProperties.Type.REQUEST));

Filter.setforceresponseencoding (This.properties.shouldForce (HttpEncodingProperties.Type.RESPONSE));

return filter;

}

@Bean

Public Localecharsetmappingscustomizer Localecharsetmappingscustomizer () {

return new Localecharsetmappingscustomizer (this.properties);

}

private static class Localecharsetmappingscustomizer implements Embeddedservletcontainercustomizer, Ordered {

Private final httpencodingproperties properties;

Localecharsetmappingscustomizer (Httpencodingproperties properties) {

This.properties = properties;

}

public void Customize (Configurableembeddedservletcontainer container) {

if (this.properties.getMapping () = null)

Container.setlocalecharsetmappings (This.properties.getMapping ());

}

public int GetOrder () {

return 0;

}

}

}

Boolean Shouldforce (Type type) {

Boolean force = (Type = = Type.request)? This.forceRequest:this.forceResponse;

if (force = = null) {

force = This.force;

}

if (force = = null) {

force = boolean.valueof (type = = Type.request);

}

return Force.booleanvalue ();

}

Solutions


Spring.http.encoding.force=true

Results

Access refresh again, display normal.

Spring MVC @ResponseStatus Annotation Comment Returns the problem of garbled characters in Chinese

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.