6、集成baseServlet用法
为了解决重复写多个servlet使用集成baseServlet,其中的原理是对于servlet的继承类调用。
1)从前端传输数据给后台参考 5(这里使用Ajax)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax登陆页面</title> </head> <body> <span>账号</span><input type="text" name="username"> <button>登陆</button> <script src="js/jquery-3.6.0.min.js"></script> <script> $("button").click(function(){ var username = $("input[name='username']").val(); $.ajax({ url:"user?method=login", //请求地址 type:"get", //请求方式 data:{ //前端给后台发送的参数 key:username }, dataType:"json", //后台给前端返回参数的格式 success:function(result){ //result后台给前端响应的参数 if(result.status == true){ location.href = "index.jsp"; }else{ alert(result.message); } } }); }); </script> </body> </html>
2)使用url:"user?method=login",先访问servlet中的user,但是对于user没有doget()方法所以转移到父类BaseServlet 中。
package com.cqkj.controller; 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; import com.alibaba.fastjson.JSON; import com.cqkj.utils.ResultMap; @WebServlet("/user") public class UserServlet extends BaseServlet{ //servlet是什么? 哪个类继承了HttpServlet,那么这个类就不再是类而是servlet ResultMap resultMap = new ResultMap(); public String login(HttpServletRequest req, HttpServletResponse resp) { String username = req.getParameter("key"); if(username.equals("gjj")) { resultMap.setStatus(true); }else { resultMap.setStatus(false); resultMap.setMessage("用户名输入有误!"); } String jsonStr = JSON.toJSONString(resultMap); return jsonStr; } public String selectAllUser(HttpServletRequest req, HttpServletResponse resp) { return ""; } }
3)在baseservlet中调用doget()中使用反射机制调用user中的login/或其他方法,在通过BaseServlet 返回给前端中。
import com.alibaba.fastjson.JSON; import com.cqkj.utils.ResultMap; public class BaseServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String methodStr = request.getParameter("method");//selectAllUser //获取类 Class clazz = this.getClass();//this代表UserServlet
//通过前端传入功能名的获取类中的方法 Method method = clazz.getMethod(methodStr,HttpServletRequest.class,HttpServletResponse.class); //调用方法 String res = (String) method.invoke(this, request,response); //返回给前端 response.getWriter().print(res); } catch (Exception e) { e.printStackTrace(); } } //前端发送请求: /*请求名称: user * 请求参数: method:login key:username * * UserServlet接到 /user 的请求,由于UserServlet中没有dopost或doget方法去处理请求,所以将请求转移给父类BaseServlet * * BaseServlet接到请求后,利用反射机制调用UserServlet中的login方法 * */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }