Action或者Servelet中输出javascript脚本乱码问题解决方案

Struts2 方案:

	public String test()
	{
		ActionContext actionContext = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) actionContext
				.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) actionContext
				.get(ServletActionContext.HTTP_RESPONSE);
		PrintWriter writer = null;
		try
		{
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			writer = response.getWriter();
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		writer.println("<script>alert('hello 这是我的一个测试')</script>");
		writer.println("<script>window.close();</script>");
		writer.flush();
		writer.close();

		return null;

	}

 Struts1和Servelet方式一致:

public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		UserForm userForm = (UserForm) form;// TODO Auto-generated method stub

		try
		{
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			PrintWriter writer = response.getWriter();
			writer.println("<script>alert('hello 这是我的一个测试')</script>");
			writer.println("<script>window.close();</script>");
			writer.flush();
			writer.close();
			return null;

		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

 

你可能感兴趣的:(JavaScript)