1:register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>register.jsp
2:UserServlet.java
package servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; public class UserServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //处理响应中文乱码 response.setContentType("text/html;charset=UTF-8"); Integer f = Integer.parseInt(request.getParameter("f")); switch (f) { case 1: this.checkUsername(request, response); break; case 2: this.register(request, response); break; } } //检测用户名是否重复 protected void checkUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); //获取从前台页面传来的username String username = request.getParameter("username"); //简化处理逻辑(本应该去数据库查询) if("zhangsan".equals(username)){ out.print("用户名"+username+"已经有人注册,请选择一个新的用户名"); }else{ out.print("恭喜您"+username+"可以使用"); } out.close(); } //用户注册 protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out =response.getWriter(); String username = request.getParameter("username"); //简化处理逻辑(本应该去数据库添加) if("zhangsan".equals(username)){ out.print("用户名"+username+"已经有人注册,请选择一个新的用户名"); }else{ //数据库添加... out.print("恭喜您"+username+"注册成功"); } out.close(); }}
3:web.xml
UserServlet servlet.UserServlet UserServlet /UserServlet
--------------------------------------------------------------------------------------------------------------------------------