首先对页面之间的请求响应写过滤器:
package com.train.Filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class EncodingFilter implements Filter {
protected FilterConfig filterConfig;
private String targetEncoding= "UTF-8";
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request2 = (HttpServletRequest) request;
request2.setCharacterEncoding(targetEncoding);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.targetEncoding = filterConfig.getInitParameter("encoding");
}
}
在数据库里面的字符编码集设为UTF-8
Connection conn = null;
PreparedStatement pStmt = null;
int rows = 0;
String sql = "insert into stu_info (Stu_ID,Stu_name,Stu_sex,Stu_national,Stu_pinyin,Stu_birthplace,Stu_edu,Stu_birthday,Stu_address,Stu_tel,Stu_workplace,Stu_img,Stu_img_f,Stu_img_b)"
+ "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
try {
conn = DBUtil.getConnection();
if(isExist(Stu_ID)){
return false;
}
pStmt = DBUtil.getPStmt(conn, sql);
pStmt.setString(1, Stu_ID);
// pStmt.setString(2, Stu_name);
pStmt.setBytes(2, Stu_name.getBytes("UTF-8"));//解决了java与mysql连接时编码问题
pStmt.setString(3, Stu_sex);
pStmt.setString(4, Stu_national);
pStmt.setString(5, Stu_pinyin);
// pStmt.setString(6, Stu_birthplace);
pStmt.setBytes(6, Stu_birthplace.getBytes("UTF-8"));
pStmt.setString(7, Stu_edu);
pStmt.setDate(8, Stu_birthday);
pStmt.setString(9, Stu_address);
pStmt.setString(10, Stu_tel);
pStmt.setBytes(11, Stu_workplace.getBytes("UTF-8"));
// pStmt.setString(11, Stu_workplace);
pStmt.setString(12, Stu_img);
pStmt.setString(13, Stu_img_f);
pStmt.setString(14, Stu_img_b);
rows = pStmt.executeUpdate();
} catch (SQLException e) {
System.out.print("保存失败");
e.printStackTrace();
return false;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.closePStmt(pStmt);
DBUtil.closeConnection(conn);
}
连接时编码:
url = "jdbc:mysql://localhost:3306/train?useUnicode=true&characterEncoding=UTF-8";
servlet页面重定向时:
response.sendRedirect("EntryCert.jsp"+"?"+"stu_ID="+stu_ID+"&stu_name="+URLEncoder.encode(stu_name, "UTF-8"));
重定向后jsp页面代码:
<%=new String(request.getParameter("stu_name").getBytes(
"ISO8859_1"), "UTF-8")%>