1 24 package org.riotfamily.common.web.filter; 25 26 import java.io.IOException ; 27 28 import javax.servlet.FilterChain ; 29 import javax.servlet.ServletException ; 30 import javax.servlet.http.HttpServletRequest ; 31 import javax.servlet.http.HttpServletResponse ; 32 import javax.servlet.http.HttpServletResponseWrapper ; 33 34 import org.springframework.web.filter.OncePerRequestFilter; 35 36 44 public class CharacterEncodingFilter extends OncePerRequestFilter { 45 46 private String encoding; 47 48 private boolean forceRequestEncoding; 49 50 private boolean forceResponseEncoding; 51 52 61 public void setEncoding(String encoding) { 62 this.encoding = encoding; 63 } 64 65 73 public void setForceRequestEncoding(boolean forceEncoding) { 74 this.forceRequestEncoding = forceEncoding; 75 } 76 77 84 public void setForceResponseEncoding(boolean forceEncoding) { 85 this.forceResponseEncoding = forceEncoding; 86 } 87 88 protected void doFilterInternal(HttpServletRequest request, 89 HttpServletResponse response, FilterChain filterChain) 90 throws ServletException , IOException { 91 92 if (this.forceRequestEncoding || request.getCharacterEncoding() == null) { 93 request.setCharacterEncoding(this.encoding); 94 } 95 filterChain.doFilter(request, new EncodingResponseWrapper(response)); 96 } 97 98 private class EncodingResponseWrapper extends 99 HttpServletResponseWrapper { 100 101 private boolean encodingSpecified; 102 103 public EncodingResponseWrapper(HttpServletResponse response) { 104 super(response); 105 } 106 107 public void setCharacterEncoding(String encoding) { 108 if (forceResponseEncoding) { 109 super.setCharacterEncoding(encoding); 110 } 111 else { 112 super.setCharacterEncoding(encoding); 113 } 114 encodingSpecified = true; 115 } 116 117 public void setContentType(String type) { 118 String mimeType = null; 119 String charset = null; 120 int i = type.indexOf(';'); 121 if (i != -1) { 122 mimeType = type.substring(0, i).trim().toLowerCase(); 123 i = type.indexOf('=', i); 124 charset = type.substring(i + 1).trim(); 125 } 126 else { 127 mimeType = type.trim().toLowerCase(); 128 } 129 130 if (mimeType.startsWith("text/") && 131 (forceResponseEncoding || (charset == null && !encodingSpecified))) { 132 133 charset = encoding; 134 } 135 136 String explicitType = mimeType; 137 if (charset != null) { 138 explicitType += "; charset=" + charset; 139 encodingSpecified = true; 140 } 141 super.setContentType(explicitType); 142 } 143 144 } 145 } 146 | Popular Tags |