JSP源码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Servlet源码:
package register;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/register")
public class register extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String username = request.getParameter("username");
if (username.equalsIgnoreCase("wjj")) {
response.getWriter().print("1");
}else {
response.getWriter().print("0");
}
}
}
常见问题:
1、编码问题:在访问jsp中可能出现中文乱码问题
应该在Servlet文件中设置如下属性:
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
2、在鼠标离开账号输入框后并没有出现想象的结果----提示用户名是否已被注册
>var user = uname.value;
xmlhttp.open("POST","register?username="+user,true); //打开连接 因为用户名是动态变量,所有要把获取都是用户名放在双引号外面
>xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded") //使用post提交表单的方式要加上这段请求头
xmlhttp.send(null); //若不填入null 有