今天学习Ajax时,获取服务器数据出现乱码,找了半天才发现是将
resp.setContentType("text/plain;charset=utf-8");
中的“;”写成了“:”,特此记录,提醒自己以后不要粗心大意。
以下附上源码:index.jsp
<%--
Created by IntelliJ IDEA.
User: hadoop
Date: 2016/4/20
Time: 15:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<%
%>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>测试</title>
<script language="JavaScript">
function ok()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for Firefox, Opera, IE7, etc.
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
xmlhttp.onreadystatechange = function () {
if(4 == xmlhttp.readyState) {
if(200 == xmlhttp.status) {
var msgWelcome = xmlhttp.responseText;
var msg = document.getElementById("msg");
msg.innerHTML = msgWelcome;
}
}
}
xmlhttp.open("get","http://localhost/myHelloWorld.do",true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
</script>
</head>
<body>
<span id="msg"></span><br>
<input type="button" onclick="ok()" value="单机此按钮">
</body>
</html>
HelloWorldOld.java
package com.count.Online;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by root on 2016/9/6.
*/
public class HelloWorldOld extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("现在时间是:" + getCuttentDateAndTime() + " 欢迎您(Hello-World)");
}
public String getCuttentDateAndTime() {
String currentDate = "";
SimpleDateFormat format1 = new SimpleDateFormat("yyyy'-'MM'-'dd HH:mm:ss");
format1.setLenient(false);
currentDate = format1.format(new Date());
return currentDate;
}
}
web.xml代码片段
<servlet>
<servlet-name>Servlet</servlet-name>
<servlet-class>com.count.Online.HelloWorldOld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>