
目录
config.xml文件 (放在src包下即可)
- <?xml version="1.0" encoding="UTF-8"?>
- <!-- 根目录 -->
- <config>
- <!-- 第一个action标签 -->
- <!--indexAction-->
- <action path="/indexAction" type="com.jmh.action.IndexAction">
- <forward name="failed" path="/add.jsp" redirect="false" />
- <forward name="success" path="/add.jsp" redirect="true" />
- </action>
- <!--userAction-->
- <action path="/userAction" type="com.jmh.action.UserAction">
- <forward name="failed" path="/add.jsp" redirect="false" />
- <forward name="success" path="/add.jsp" redirect="true" />
- </action>
- </config>
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
- version="4.0">
- <!--中央控制器-->
- <servlet>
- <servlet-name>ActionServlet</servlet-name>
- <servlet-class>com.jmh.framework.ActionServlet</servlet-class>
- <!--配置、配置文件-->
- <init-param>
- <param-name>config</param-name>
- <param-value>/config.xml</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>ActionServlet</servlet-name>
- <url-pattern>*.action</url-pattern>
- </servlet-mapping>
- </web-app>
- package com.jmh.entity;
-
- import java.io.Serializable;
-
- /**
- * index对象
- */
- public class Index implements Serializable {
- private float sa;
- private float sb;
-
- public Index() {
- }
-
- public Index(float sa, float sb) {
- this.sa = sa;
- this.sb = sb;
- }
-
- public float getSa() {
- return sa;
- }
-
- public float getSb() {
- return sb;
- }
-
- public void setSa(float sa) {
- this.sa = sa;
- }
-
- public void setSb(float sb) {
- this.sb = sb;
- }
-
- @Override
- public String toString() {
- return "Index{" +
- "sa=" + sa +
- ", sb=" + sb +
- '}';
- }
- }
- package com.jmh.framework;
-
- import org.apache.commons.beanutils.BeanUtils;
- import org.dom4j.DocumentException;
-
- import javax.servlet.ServletConfig;
- 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.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Set;
-
- /**
- * 中央控制器
- */
- public class ActionServlet extends HttpServlet {
- //定义configModel对象
- private ConfigModel configModel;
- //定义默认配置文件.xml
- private String path="/config.xml";
-
- @Override
- public void init(ServletConfig config) throws ServletException{
- try {
- //获取配置文件key
- String path = config.getInitParameter("config");
- //判断key如果为空就赋默认值
- if(null==path){
- //初始化方法、读取配置文件
- configModel= ConfigModelFactory.bind(this.path);
- }else{
- //key里面有值
- configModel= ConfigModelFactory.bind(path);
- }
-
-
- } catch (DocumentException e) {
- e.printStackTrace();
- }
-
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doPost(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- System.out.println("来到了中央控制器");
- //获取请求路径
- String servletPath = req.getServletPath();
- //获取路径最后一个点的下标
- int in = servletPath.lastIndexOf(".");
- //开始截取 从下标0到获取最后一个点的下标
- String path = servletPath.substring(0, in);
- try {
- //根据路径获取ActionModel对象
- ActionModel actionModel = this.createActionModel(path, configModel);
- //通过ActionModel对象获取全限定名实例化Action对象
- Action action = this.createAction(actionModel.getType());
- System.out.println("反射实例化==="+action);
- //开始调用给属性赋值的方法
- this.getModels(action,req);
- //调用方法
- String code = action.query(req, resp);
- //跳转是否转发、重定向方法
- this.reqresp(code,actionModel,req,resp);
-
- } catch (Exception e) {
- e.printStackTrace();
-
- }
- }
-
- /**
- * 根据.action路径获取ActionModel对象
- * @param path 路径
- * @param con configMOdel对象
- * @return ActionModel对象
- */
- private ActionModel createActionModel(String path,ConfigModel con){
- ActionModel action = con.pop(path);
- //非空
- if(null==action){
- throw new RuntimeException(path+"找不到");
- }
- //反之
- return action;
- }
-
- /**
- * 通过全限定名实例化Action对象
- * @param type 全限定名
- * @return
- * @throws ClassNotFoundException
- * @throws IllegalAccessException
- * @throws InstantiationException
- */
- private Action createAction(String type){
- try {
- if(null==type){
- throw new RuntimeException("传来的全限定名为空");
- }
- //获取类对象
- Class clazz = Class.forName(type);
- //通过类对象实例化对象
- Action action = (Action) clazz.newInstance();
- return action;
- }catch (Exception e){
- throw new RuntimeException(e);
- }
- }
- //获取返回值判断是转发还是重定向
- private void reqresp(String code,ActionModel a,HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
- //判断返回参数是否为空
- if(null==code||"".equals(code)){
- throw new RuntimeException("返回值为空");
- }
- //获取forward对象里面是否跳转路径
- ForwardModel forward = a.pop(code);
- //判断对象是否为空
- if(null==forward){
- throw new RuntimeException(code+"对应的对象找不到");
- }
- //判断是否跳转
- boolean redirect = forward.isRedirect();
- if(redirect){
- //为true重定向
- resp.sendRedirect(req.getContextPath()+forward.getPath());
- }else{
- //反之 转发
- req.getRequestDispatcher(forward.getPath()).forward(req,resp);
- }
-
- }
-
- /**
- * 给对象属性赋值
- */
- private void getModels(Action action,HttpServletRequest req) throws InvocationTargetException, IllegalAccessException {
- //判断对象是否实现了接口
- if(action instanceof ModelDriver){
- //实现了就强转
- ModelDriver model=(ModelDriver)action;
- //调用方法、给属性赋值
- Object model1 = model.getModel();
- //获取所有的请求参数
- Map<String, String[]> map = req.getParameterMap();
- Set<Map.Entry<String, String[]>> entries = map.entrySet();
- for(Map.Entry<String, String[]> str:entries){
- //System.out.println(str.getKey()+"《===》"+str.getValue());
- }
- BeanUtils.populate(model1,map);
- }
- }
- }
- package com.jmh.framework;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
-
- /**
- * 子控制器的父类
- */
- public abstract class Action {
- //定义一个抽象方法
- public abstract String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, Exception;
- }
- package com.jmh.framework;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.util.Map;
- import java.util.Set;
-
- /**
- * 处理相识方法的功能
- */
- public class DisPatAction extends Action{
- @Override
- public String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, Exception {
- System.out.println("来到了DisPatAction里面");
- //获取方法名
- String method = this.getMenthodName(req);
- System.out.println("请求的方法名==="+method);
- //获取类对象
- Class clszz = this.getClass();
- //调用方法
- Method method1 = clszz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
- //打开访问权限
- method1.setAccessible(true);
- //开始调用方法
- String invoke = (String)method1.invoke(this, req, resp);
- return invoke;
- }
-
- /**
- * 获取要操作的方法名
- * @param req req
- * @return 方法名
- */
- private String getMenthodName(HttpServletRequest req){
- //获取对象名
- String method = req.getParameter("methodName");
- //非空、如果方法名为空的话
- if(null==method||"".equals(method)){
- //获取map集合里面的方法名
- Map<String, String[]> parameterMap = req.getParameterMap();
- //获取值
- Set<String> strings = parameterMap.keySet();
- //遍历
- for(String key:strings){
- //判断键不为空
- if(-1!=key.indexOf("method:")){
- //开始替换
- method = key.replace("method:","");
- }
- }
- }
- return method;
- }
- }
- package com.jmh.framework;
-
- /**
- * 主要工作:给对象赋值
- */
- public interface ModelDriver<T> {
- public T getModel();
- }
- package com.jmh.action;
-
- import com.jmh.entity.Index;
- import com.jmh.framework.Action;
- import com.jmh.framework.DisPatAction;
- import com.jmh.framework.ModelDriver;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
-
- public class IndexAction extends DisPatAction implements ModelDriver<Index> {
-
- //实例化index
- private Index index=new Index();
- public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- System.out.println("来到了IndexAction里面");
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- float sum=index.getSa()+index.getSb();
- //将获取到的数据保存到作用域
- req.getSession().setAttribute("sum",sum);
-
- return "failed";
- }
- public String delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- float sum=index.getSa()-index.getSb();
- //将获取到的数据保存到作用域
- req.getSession().setAttribute("sum",sum);
-
- return "failed";
- }
- public String chu(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- float sum=index.getSa()*index.getSb();
- //将获取到的数据保存到作用域
- req.getSession().setAttribute("sum",sum);
-
- return "failed";
- }
- public String cheng(HttpServletRequest req, HttpServletResponse resp) throws Exception {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- float sum=index.getSa()/index.getSb();
- //将获取到的数据保存到作用域
- req.getSession().setAttribute("sum",sum);
-
- return "failed";
- }
- @Override
- public String toString() {
- return "IndexAction{}";
- }
-
- /**
- * 实现接口方法
- * @return
- */
- @Override
- public Index getModel() {
- return index;
- }
- }
思路整理:第一步:我们需要编写一个中央控制器ActionServlet第二步:我们需要编写一个抽象类Action里面写一个抽象方法第三步:编写DisPatAction继承Action并重写抽象方法进行获取传来的方法名并进行反射实例化对象并根据获取的方法名进行反射调用指定的方法第四步:编写ModelDriver接口主要工作来给对象属性赋值
第五步:编写IndexAction并继承DisPatAction实现ModelDriver主要来编写要操作的方法体业务逻辑代码
- package com.jmh.entity;
-
- import java.io.Serializable;
-
- public class User implements Serializable {
- private Integer id;//编号
- private String name;//姓名
- private String pwd;//密码
- private String sex;//性别
- private String age;//年龄
- private String hobby;//爱好
-
- public User(Integer id, String name, String pwd, String sex, String age, String hobby) {
- this.id = id;
- this.name = name;
- this.pwd = pwd;
- this.sex = sex;
- this.age = age;
- this.hobby = hobby;
- }
-
- public User() {
- }
-
- public String getPwd() {
- return pwd;
- }
-
- public Integer getId() {
- return id;
- }
-
- public String getName() {
- return name;
- }
-
- public String getSex() {
- return sex;
- }
-
- public String getAge() {
- return age;
- }
-
- public String getHobby() {
- return hobby;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public void setSex(String sex) {
- this.sex = sex;
- }
-
- public void setAge(String age) {
- this.age = age;
- }
-
- public void setHobby(String hobby) {
- this.hobby = hobby;
- }
-
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
-
- @Override
- public String toString() {
- return "User{" +
- "id=" + id +
- ", name='" + name + '\'' +
- ", pwd='" + pwd + '\'' +
- ", sex='" + sex + '\'' +
- ", age='" + age + '\'' +
- ", hobby='" + hobby + '\'' +
- '}';
- }
- }
- package com.jmh.framework;
-
- import org.apache.commons.beanutils.BeanUtils;
- import org.dom4j.DocumentException;
-
- import javax.servlet.ServletConfig;
- 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.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.Enumeration;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Set;
-
- /**
- * 中央控制器
- */
- public class ActionServlet extends HttpServlet {
- //定义configModel对象
- private ConfigModel configModel;
- //定义默认配置文件.xml
- private String path="/config.xml";
-
- @Override
- public void init(ServletConfig config) throws ServletException{
- try {
- //获取配置文件key
- String path = config.getInitParameter("config");
- //判断key如果为空就赋默认值
- if(null==path){
- //初始化方法、读取配置文件
- configModel= ConfigModelFactory.bind(this.path);
- }else{
- //key里面有值
- configModel= ConfigModelFactory.bind(path);
- }
-
-
- } catch (DocumentException e) {
- e.printStackTrace();
- }
-
- }
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doPost(req, resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- System.out.println("来到了中央控制器");
- //获取请求路径
- String servletPath = req.getServletPath();
- //获取路径最后一个点的下标
- int in = servletPath.lastIndexOf(".");
- //开始截取 从下标0到获取最后一个点的下标
- String path = servletPath.substring(0, in);
- try {
- //根据路径获取ActionModel对象
- ActionModel actionModel = this.createActionModel(path, configModel);
- //通过ActionModel对象获取全限定名实例化Action对象
- Action action = this.createAction(actionModel.getType());
- System.out.println("反射实例化==="+action);
- //开始调用给属性赋值的方法
- this.getModels(action,req);
- //调用方法
- String code = action.query(req, resp);
- //跳转是否转发、重定向方法
- this.reqresp(code,actionModel,req,resp);
-
- } catch (Exception e) {
- e.printStackTrace();
-
- }
- }
-
- /**
- * 根据.action路径获取ActionModel对象
- * @param path 路径
- * @param con configMOdel对象
- * @return ActionModel对象
- */
- private ActionModel createActionModel(String path,ConfigModel con){
- ActionModel action = con.pop(path);
- //非空
- if(null==action){
- throw new RuntimeException(path+"找不到");
- }
- //反之
- return action;
- }
-
- /**
- * 通过全限定名实例化Action对象
- * @param type 全限定名
- * @return
- * @throws ClassNotFoundException
- * @throws IllegalAccessException
- * @throws InstantiationException
- */
- private Action createAction(String type){
- try {
- if(null==type){
- throw new RuntimeException("传来的全限定名为空");
- }
- //获取类对象
- Class clazz = Class.forName(type);
- //通过类对象实例化对象
- Action action = (Action) clazz.newInstance();
- return action;
- }catch (Exception e){
- throw new RuntimeException(e);
- }
- }
- private void reqresp(String code,ActionModel a,HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
- //判断返回参数是否为空
- if(null==code||"".equals(code)){
- throw new RuntimeException("返回值为空");
- }
- //获取forward对象里面是否跳转路径
- ForwardModel forward = a.pop(code);
- //判断对象是否为空
- if(null==forward){
- throw new RuntimeException(code+"对应的对象找不到");
- }
- //判断是否跳转
- boolean redirect = forward.isRedirect();
- if(redirect){
- //为true重定向
- resp.sendRedirect(req.getContextPath()+forward.getPath());
- }else{
- //反之 转发
- req.getRequestDispatcher(forward.getPath()).forward(req,resp);
- }
-
- }
-
- /**
- * 给对象属性赋值
- */
- private void getModels(Action action,HttpServletRequest req) throws InvocationTargetException, IllegalAccessException {
- //判断对象是否实现了接口
- if(action instanceof ModelDriver){
- //实现了就强转
- ModelDriver model=(ModelDriver)action;
- //调用方法、给属性赋值
- Object model1 = model.getModel();
- //获取所有的请求参数
- Map<String, String[]> map = req.getParameterMap();
- Set<Map.Entry<String, String[]>> entries = map.entrySet();
- for(Map.Entry<String, String[]> str:entries){
- //System.out.println(str.getKey()+"《===》"+str.getValue());
- }
- BeanUtils.populate(model1,map);
- }
- }
- }
- package com.jmh.framework;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
-
- /**
- * 子控制器的父类
- */
- public abstract class Action {
- //定义一个抽象方法
- public abstract String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, Exception;
- }
- package com.jmh.framework;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.util.Map;
- import java.util.Set;
-
- /**
- * 处理相识方法的功能
- */
- public class DisPatAction extends Action{
- @Override
- public String query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, Exception {
- System.out.println("来到了DisPatAction里面");
- //获取方法名
- String method = this.getMenthodName(req);
- System.out.println("请求的方法名==="+method);
- //获取类对象
- Class clszz = this.getClass();
- //调用方法
- Method method1 = clszz.getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
- //打开访问权限
- method1.setAccessible(true);
- //开始调用方法
- String invoke = (String)method1.invoke(this, req, resp);
- return invoke;
- }
-
- /**
- * 获取要操作的方法名
- * @param req req
- * @return 方法名
- */
- private String getMenthodName(HttpServletRequest req){
- //获取对象名
- String method = req.getParameter("methodName");
- //非空、如果方法名为空的话
- if(null==method||"".equals(method)){
- //获取map集合里面的方法名
- Map<String, String[]> parameterMap = req.getParameterMap();
- //获取值
- Set<String> strings = parameterMap.keySet();
- //遍历
- for(String key:strings){
- //判断键不为空
- if(-1!=key.indexOf("method:")){
- //开始替换
- method = key.replace("method:","");
- }
- }
- }
- return method;
- }
- }
- package com.jmh.framework;
-
- /**
- * 主要工作:给对象赋值
- */
- public interface ModelDriver<T> {
- public T getModel();
- }
- package com.jmh.action;
-
- import com.jmh.entity.User;
- import com.jmh.framework.Action;
- import com.jmh.framework.DisPatAction;
- import com.jmh.framework.ModelDriver;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.lang.reflect.Array;
- import java.util.Arrays;
- import java.util.List;
-
- public class UserAction extends DisPatAction implements ModelDriver<User> {
- //实例化user对象
- private User user=new User();
-
- public String register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //设置编码
- req.setCharacterEncoding("utf-8");
- resp.setContentType("text/html;charset=utf-8");
- //以防万一爱好不被覆盖就手动获取值
- String[] hobbies = req.getParameterValues("hobby");
- //获取到所有还好并遍历
- List<String> strings = Arrays.asList(hobbies);
- //遍历
- String hobbys="";
- for(String str:strings){
- hobbys+=str+",";
- }
- //截取从最后一个逗号的下标开始
- int i = hobbys.lastIndexOf(",");
- String substring = hobbys.substring(0, i);
- //赋值给对象的爱好
- user.setHobby(substring);
- //将对象保存到作用域里面
- req.getSession().setAttribute("sum",user);
- System.out.println("进来了==="+user);
- return "failed";
- }
-
- @Override
- public User getModel() {
- return user;
- }
- }
这些代码如果不懂的话可以多看几遍或者自己赋值到编译器看看,或者自己手巧几遍熟练了就好,如果实在不懂或者想知道的话就可以评论,直接私我都ok