當(dāng)有多個(gè)post方式請(qǐng)求action時(shí),可以采用過(guò)濾器的方式對(duì)多個(gè)action進(jìn)行統(tǒng)一設(shè)置編碼,設(shè)置方式有兩大步驟:1.webxml中設(shè)置filter 2.建立filter類,這里我給出自己寫的filter,通常在項(xiàng)目中使用SPRing自帶的編碼過(guò)濾器。
Web.xml的配置:
<filter>
<filter-name>filter1</filter-name>
<filter-class>com.zhangyike.Demo.CodingFiler</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
Filter-class對(duì)應(yīng)的filter類:
public class CodingFiler implementsFilter {
private String encode = "";
public void doFilter(ServletRequest req, ServletResponseresp, FilterChain chain) throws IOException, ServletException {
//轉(zhuǎn)換
HttpServletRequestrequest = (HttpServletRequest)req;
HttpServletResponseresponse = (HttpServletResponse)resp;
/*
* 判斷在web.xml文件中是否配置了編碼格式的信息
* 如果為空,則設(shè)置編碼格式為配置文件中的編碼格式
* 否則編碼格式設(shè)置為GBK
*/
if(this.encode != null&& !this.encode.equals("")){
request.setCharacterEncoding(this.encode);
response.setCharacterEncoding(this.encode);
}else{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
}
/*
* 使用doFilter方法調(diào)用鏈中的下一個(gè)過(guò)濾器或目標(biāo)資源(servlet或JSP頁(yè)面)。
* chain.doFilter處理過(guò)濾器的其余部分(如果有的話),最終處理請(qǐng)求的servlet或JSP頁(yè)面。
*/
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throwsServletException {
this.encode = fConfig.getInitParameter("encode");
}
@Override
public void destroy() {
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注