BaseServlet抽取
减少Servlet的数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法来完成用户的请求
UserServlet
package cn.itcast.travel.web.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/user/*") public class UserServlet extends BaseServlet { public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("userServlet的add方法..."); } public void find(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("userServlet的find方法..."); } }
BaseServlet
package cn.itcast.travel.web.servlet; 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.lang.reflect.Method; /** * 全部封装到一个servlet中 父类 */ public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //完成方法分成 //1.获取请求路径 String uri = req.getRequestURI();// /travel/user/add System.out.println("请求uri:"+uri);// /travel/user / add //2.获取方法名称 String substring = uri.substring(uri.lastIndexOf('/')+ 1 );//从后面开始找最后一个斜杠截取掉 System.out.println("方法名称:"+substring); //3.获取方法对象Method //谁调用我,我代表谁 System.out.println(this);// UserServlet的对象 try { //忽略访问权限修饰符,获取方法 //Method method = this.getClass().getDeclaredMethod(substring, HttpServletRequest.class, HttpServletResponse.class);//对应方法 //对应UserServlet方法 Method method = this.getClass().getMethod(substring, HttpServletRequest.class, HttpServletResponse.class);//对应方法 //4.执行方法 //暴力反射 //method.setAccessible(true);//获取方法 method.invoke(this, req,resp); } catch (Exception e) { e.printStackTrace(); } } }
UserServlet页面路径改写
UserServlet类:
package cn.itcast.travel.web.servlet; import cn.itcast.travel.domain.ResultInfo; import cn.itcast.travel.domain.User; import cn.itcast.travel.service.UserService; import cn.itcast.travel.service.impl.UserServiceImpl; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.beanutils.BeanUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; /** * 子类 */ @WebServlet("/user/*") public class UserServlet extends BaseServlet { //声明成员变量 private UserService service = new UserServiceImpl(); /** * 注册功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //验证校验 String check = request.getParameter("check"); //从sesion中获取验证码 HttpSession session = request.getSession(); String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");// 获取验证码 程序猿生成的验证码 session.removeAttribute("CHECKCODE_SERVER");//移除验证码,为了保证验证码只能使用一次 //比较 if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){ //验证码错误 ResultInfo info = new ResultInfo(); //注册失败 info.setFlag(false); info.setErrorMsg("验证码错误"); //将info对象序列化为json ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(info); //设置编码 response.setContentType("application/json;charset=utf-8"); response.getWriter().write(json); return; } //1.获取数据 Map<String, String[]> map = request.getParameterMap(); //2.封装对象 User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //3.调用service完成注册 //UserService service = new UserServiceImpl(); boolean flag = service.regist(user); ResultInfo info = new ResultInfo(); //4.响应结果 if(flag){ //注册成功 info.setFlag(true); }else{ //注册失败 info.setFlag(false); info.setErrorMsg("注册失败!"); } //将info对象序列化为json ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(info); //将json数据写回客户端 //设置content-type response.setContentType("application/json;charset=utf-8");// json类型数据 response.getWriter().write(json); } /** * 登录功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取用户名和密码数据 Map<String, String[]> map = request.getParameterMap(); //2.封装User对象 User user = new User(); try { BeanUtils.populate(user, map); } catch (Exception e) { e.printStackTrace(); } //3.调用Servlet查询 //UserService service = new UserServiceImpl(); User u = service.login(user); ResultInfo info = new ResultInfo(); //4.判断用户对象是否为null if (u == null){ //用户名或密码错误 info.setFlag(false); info.setErrorMsg("用户名或密码错误"); } //5.判断用户是否激活 if (u != null && !"Y".equals(u.getStatus())){ //用户尚末激活 info.setFlag(false); info.setErrorMsg("您尚末激活,请激活"); } //6. 判断登录成功 if (u != null && "Y".equals(u.getStatus())){ request.getSession().setAttribute("user", u);//登录成功的标记 //登录成功 info.setFlag(true); } //响应数据 ObjectMapper mapper = new ObjectMapper(); //设置编码 response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(), info); } /** * 查找单个对象 * @param request * @param response * @throws ServletException * @throws IOException */ public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从session中获取登录用户 Object user = request.getSession().getAttribute("user"); //将user写回客户端 ObjectMapper mapper = new ObjectMapper(); //设置编码 response.setContentType("application/json;charset=utf-8"); //回写 mapper.writeValue(response.getOutputStream(),user); } /** * 退出功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.销毁session request.getSession().invalidate(); //2.跳转登录页面 response.sendRedirect(request.getContextPath()+"/login.html"); } /** * 激活功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.获取激活码 String code = request.getParameter("code"); if (code != null) { //2.调用service完成激活 //UserService service = new UserServiceImpl(); boolean flag = service.active(code); //3.判断标记 String msg = null; if (flag) { //激活成功 msg = "激活成功,请<a href='login.html'>登录</a>"; } else { //激活失败 msg = "激活失败,请联系管理员!"; } //设置编码 response.setContentType("text/html;charset=utf-8"); //写出 response.getWriter().write(msg); } } }
修改页面路径:
regist.html页面:
$(function () { //当表单提交时,调用所有的校验方法 $("#registerForm").submit(function(){ //1.发送数据到服务器 if(checkUsername() && checkPassword() && checkEmail()){ //校验通过,发送ajax请求,提交表单的数据 username=zhangsan&password=123 $.post("user/regist",$(this).serialize(),function(data){ //处理服务器响应的数据 data {flag:true,errorMsg:"注册失败"} if(data.flag){ //注册成功,跳转成功页面 location.href="register_ok.html"; }else{ //注册失败,给errorMsg添加提示信息 $("#errorMsg").html(data.errorMsg); } }); } //2.不让页面跳转 return false; //如果这个方法没有返回值,或者返回为true,则表单提交,如果返回为false,则表单不提交 }); //当某一个组件失去焦点是,调用对应的校验方法 $("#username").blur(checkUsername); $("#password").blur(checkPassword); $("#email").blur(checkEmail); });
header.html页面:
<script> $(function () { $.get("user/findOne",{},function (data) { var msg = "欢迎回来,"+data.name; $("#span_username").html(msg); }); }); </script>
login.html页面:
<script> //1、给登录按钮绑定单击事件 $(function () { $("#btn_sub").click(function () { //2、发送ajax请求,提交表单数据 $.post("user/login",$("#loginForm").serialize(),function (data) { //3、处理响应数据 if (data.flag){ //登录成功 location.href="index.html"; }else { //登录失败 $("#errorMsg").html(data.errorMsg); } }); }); }); </script>
UserServiceImpl实现类:
/** * 注册用户 * @param user * @return */ @Override public boolean regist(User user) { //根据用户名查询用户对象 User u = userDao.findByUsername(user.getUsername()); //判断u是否为null if (u!=null){ //用户名已存在,注册失败 return false; } //保存用户信息 //设置激活码。唯一字符串 user.setCode(UuidUtil.getUuid()); //设置激活状态 user.setStatus("N"); userDao.save(user); //激活邮件发送 String content = "<a href='http://localhost/travel/user/active?code="+user.getCode()+"'>点击激活【旅游网】</a>"; MailUtils.sendMail(user.getEmail(),content,"激活邮件"); return true; }
标签:BaseServlet,UserServlet,request,throws,user,import,servlet,response,页面 From: https://www.cnblogs.com/xuche/p/17141558.html