源码如下
servlet源码:
@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String, String[]> parameterMap = request.getParameterMap();
System.out.println(parameterMap);
Set<String> keySet = parameterMap.keySet();
for (String key : keySet) {
String[] values = parameterMap.get(key);
System.out.println(key + " = " + Arrays.asList(values));
}
System.out.println("----------------------------");
String team = request.getParameter("team");//只能获取其中的一个值
System.out.println("team = " + team);
String[] seasons = request.getParameterValues("season");//获取单选框的请求参数
System.out.println("Arrays.asList(seasons)" + Arrays.asList(seasons));
// getParameterValues()方法:取多选框的请求参数
String[] teams = request.getParameterValues("team");
System.out.println("Arrays.asList(teams) = " + Arrays.asList(teams));
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write("你好,我是你爸爸");
}
}
filter源码
public class ServletFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("过滤器正在执行中,请稍等...");
// servletRequest.setCharacterEncoding("UTF-8");
String message = servletRequest.getParameter("message");
if (message.equals("index")){
filterChain.doFilter(servletRequest,servletResponse);
} else {
servletRequest.getRequestDispatcher("EmployeeServlet").forward(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
在使用过滤器是遇到一个想不通的问题:当我使用过滤器ServletFilter拦截IndexServlet时,在IndexServlet设置的request的编码方式为request.setCharacterEncoding("UTF-8");,然后正常执行项目,但是发现在控制台输出有乱码,可见并没有成功编码;然后我把编码提前在过滤器ServletFilter中,发现成功设置编码了,哪位大佬可告诉我是什么原因