xml部分:
注意写在<web-app>下面,而不是<servlet>下面
<context-param>
<param-name>name</param-name>
<param-value>张三</param-value>
</context-param>
package info.dyndns.headfirst.setContentType;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ContextParamTest extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;UTF-8");
response.setCharacterEncoding("UTF-8");//处理乱码,使发送和接收都在UTF-8中进行
//因为默认是ISO
PrintWriter out = response.getWriter();
String name = this.getServletContext().getInitParameter("name");
out.println(name);
}
}
outPut:
张三
在使用中文的时候如果不修改编码,则会出现乱码,因为默认码表是iso,而iso中是不存在中文的,那么编码和解码都设置为utf-8就妥妥的了。