1.分析:
1、注册功能
(1)前端
1.注册表单、用户名、密码、单选、复选、下拉列表控件编写
2.action属性跳转到后台;name属性传参数到后台
(2)后台
1.新建注册Servlet,用request接收参数;response返回数据到前端
(3)处理乱码
1.request的doGet请求:new String(username.getBytes("iso-8859-1"), "utf-8");
2.response的doGet/doPost请求:response.setContentType("text/html;charset=utf-8");
3.request的doPost请求:request.setCharacterEncoding("utf-8");
(4)doGet与doPost区别
1.doGet将参数从url中传到后台,不安全,性能高;只能传文本参数
2.doPost以请求体方式传到后台,安全,性能低;可以传文本及二进制
2、登录功能
(1)前端控件的编写,action属性跳到LoginServlet
(2)后台判断登录是否成功
2.实现代码
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.doGet/doPost的response的乱码:
response.setContentType("text/html;charset=utf-8");
//3.doPost的request的乱码
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
if("zs".equals(username)&&"123".equals(password)){
response.getWriter().write("登录成功");
}else{
response.getWriter().write("登录失败 ");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//注意: 往往乱码处理尽可能放到最上面
//1.doGet/doPost的response的乱码:
response.setContentType("text/html;charset=utf-8");
//3.doPost的request的乱码
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
//2.doGet的request的乱码
//username = new String(username.getBytes("iso-8859-1"),"utf-8");
String password = request.getParameter("password");
String sex = request.getParameter("sex");
String[] loves = request.getParameterValues("loves");
String province = request.getParameter("province");
System.out.println(username+"--"+password+"--"+sex);
System.out.println(Arrays.toString(loves)+"--"+province);
if("zs".equals(username)){
response.getWriter().write("已注册~!");
}else{
response.getWriter().write("3秒后自动跳转到登录页面!");
response.setHeader("refresh", "3;url='login.html'");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost....");
doGet(request, response);
}
}
3.前端
用户-登录
用户-注册
4.web.XML配置