在重定向代码之前,将参数值用以下代码编码一下即可。
message = URLEncoder.encode(message, "UTF-8");
代码如下:
@WebServlet(urlPatterns = "/check")
public class CheckServler extends HttpServlet{
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String message = null;
if(username == null) {
message = "Please input username.";
}else {
message = "Hello, " + username;
}
message = URLEncoder.encode(message, "UTF-8");
response.sendRedirect("/helloapp/output?msg="+message);
}
}
@WebServlet(urlPatterns = "/output")
public class OutputServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain; charset=UTF-8");
String msgString = request.getParameter("msg");
PrintWriter outPrintWriter = response.getWriter();
outPrintWriter.println(msgString);
outPrintWriter.close();
}
}