【mvc之后台优化代码】

news/2024/7/4 9:43:20

目录

  • 前言
    • 中央控制器 DispactherServlet(按照运行顺序来)
      • 子控制接口 action
        • 子控制器超类 actionSupper
          • 总方法集合 StudentAction
        • 自动调用参数的 ModelDirven
    • 方法 BeanDao
      • 方法调用 StudentDao
    • xml的配置
    • 前台调用xml
    • 调用代码
  • 总结

前言

先说好,本次因为运用的是上次【mvc的增强】的知识,所以不会去过多的去讲解,本次跟多的是案例。
若有不理解的请看【mvc的增强】

中央控制器 DispactherServlet(按照运行顺序来)

public class DispatcherServlet extends HttpServlet{
	
	
//	private Map<String, action> actionMap = new HashMap<>();//用来存储子控制器的位置
	
	private configModel config = null ;
	
	public void init() {
		try {
			
			//使得调用指定位置的xml文件
			String xmlpath  = this.getInitParameter("xmlpath");
			if(xmlpath==null||"".equals(xmlpath)) {
				config = configModelFactory.build();
			}
			else {
				config = configModelFactory.build(xmlpath);
			}
		} catch (Exception 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 {

		
		init();//使得map里有值
		String requestURI = req.getRequestURI(); //获取请求的路径
		System.out.println("截取前:"+requestURI);
		
		String url = requestURI.substring(requestURI.lastIndexOf("/"), requestURI.lastIndexOf("."));//截取
		System.out.println("截取后:"+url);
		
		
		actionModel actionModel = config.pop(url);
		if(actionModel==null) {
			throw new RuntimeException("你没有配置相关的action");
		}
		
		try {
			action action = (action)Class.forName(actionModel.getType()).newInstance();//实列化xml中type里面的内容地址
			//calAction
			
			if(action instanceof ModelDirven) {
				ModelDirven modeldirven = (ModelDirven)action;
				Object model = modeldirven.getModel();
				
//				Map<String, String[]> parameterMap = req.getParameterMap();
//				for (Entry<String, String[]> entry : parameterMap.entrySet()) {
//					
//					Field[] declaredFields = model.getClass().getDeclaredFields();
//					for (Field field : declaredFields) {
//						if(entry.getKey().equals(field.getName())) {
//							Field declaredField = model.getClass().getDeclaredField(entry.getKey());
//							declaredField.setAccessible(true);
//							declaredField.set(model, entry.getValue());
//						}
//					}
//					
//				}
//				
				BeanUtils.populate(model, req.getParameterMap());//本行代码意思可以看到上面注释
			}
						//calAction
			String code = action.execute(req, resp);//获取返回路径的名字
			forwardModel forwardModel = actionModel.pop(code);
			
			if(forwardModel==null) {
				throw new RuntimeException("你没有配置对应子控制器action的处理方式");
			}
			
			String jsppath = forwardModel.getPath();//获取返回的路径
			
			if(forwardModel.isRedirect()) {//判断是否要重定向
				resp.sendRedirect(req.getContextPath()+jsppath);
			}
			else  {//判断是否要转发
				req.getRequestDispatcher(jsppath).forward(req, resp);
			}
			
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}  catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
}

子控制接口 action

public interface action {
	
	String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;

}

子控制器超类 actionSupper

public class actionSupper implements action {


	public final String execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String code = null;
		try {
			Method Method = this.getClass().getDeclaredMethod(req.getParameter("method"), HttpServletRequest.class,HttpServletResponse.class);
			Method.setAccessible(true);
			code = (String) Method.invoke(this, req,resp);//获取在方法的返回值
			
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		return code;
	}

}
总方法集合 StudentAction
public class StudentAction extends actionSupper implements ModelDirven<student>{
	private studentDao sd = new studentDao();
	private student stu = new student ();
	
	public String getAll(HttpServletRequest req,HttpServletResponse resp) {
		
		PageBean page = new PageBean();
		page.setRequest(req);
		List<student> list = sd.getAll(stu, page);
		System.out.println("数量"+list.size());
		req.setAttribute("list", list);
		req.setAttribute("PageBean", page);
		
		return "index";
	}
	
	public String deleteStu(HttpServletRequest req,HttpServletResponse resp) {
		
		int n = sd.deleteStu(stu);
		if(n>0) {
			System.out.println("删除成功");
		}
		else {
			System.out.println("删除失败");
		}
		return "Reindex";
	}
	public String loadStu(HttpServletRequest req,HttpServletResponse resp) {
		
		List<student> list = sd.getAll(stu, null);
		System.out.println(list.size());
		req.setAttribute("stu", list.get(0));
		System.out.println(list.get(0));
		return "preupdate";
	}
	
	public String updateStu(HttpServletRequest req,HttpServletResponse resp) {
		
		int n = sd.updateStu(stu);
		if(n>0) {
			System.out.println("修改成功");
		}
		else {
			System.out.println("修改失败");
		}
		
		return "Reindex";
	}
	public String addStu(HttpServletRequest req,HttpServletResponse resp) {
		
		int n = sd.addStu(stu);
		if(n>0) {
			System.out.println("增加成功");
		}
		else {
			System.out.println("增加失败");
		}
		
		return "Reindex";
	}
	

	@Override
	public student getModel() {
		return stu;
	}

}

自动调用参数的 ModelDirven

public interface ModelDirven<T>{
	T getModel();

}

方法 BeanDao

public class BeanDao<T> {
	
	Connection con = null;
	PreparedStatement pst = null;
	ResultSet rs = null;

	
	
	public List<T> executeQuery(String sql ,Class clz ,PageBean page ){
		List<T> lt = new ArrayList<>();
		try {
			con = DBAccess.getConnection(); //连接三部曲
			
			if(page!=null&&page.isPagination()) {//要进行分页的进这里
				
				String countPage = countPage(sql);//获取这个类在数据库的总行数
				pst = con.prepareStatement(countPage);
				rs = pst.executeQuery(); 
				if(rs.next()) {
					page.setTotal(rs.getLong(1)+"");
				}
				
				String getPage = getPage(sql,page);//获取这个页面的页数
				
				pst = con.prepareStatement(getPage);
				rs = pst.executeQuery();
				
			}
			else {
				pst = con.prepareStatement(sql);//连接三部曲
				rs = pst.executeQuery(); //连接三部曲
			}
			while (rs.next()) {
				T t = (T) clz.newInstance();//将传过来的class文件实列化,类型为实现本类的T参数
				Field[] fields = clz.getDeclaredFields();//获取这个类里的所有属性
				for (Field field : fields) { //遍历
					System.out.println(field.getName()+":"+rs.getObject(field.getName()));
					field.setAccessible(true);  //打开权限
						field.set(t, rs.getObject(field.getName()));
				}
				System.out.println(t.toString());
				lt.add(t);//加入到集合内部
			} 
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DBAccess.close(con, pst, rs);
		}
		return lt;
	}
	
	
	//增 ,删,改
	public int executeUpdate(String sql ,String [] attrs ,T t ){
		int n = 0;
		try {
			
			con = DBAccess.getConnection();  //连接三部曲
			pst = con.prepareStatement(sql); //连接三部曲
			for (int i = 0; i < attrs.length; i++) {
				Field Field = t.getClass().getDeclaredField(attrs[i]);
				Field.setAccessible(true);
				pst.setObject(i+1, Field.get(t));
			}
			n= pst.executeUpdate();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}  catch (SQLException e) {
			e.printStackTrace();
		}catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		finally {
			DBAccess.close(con, pst, rs);
		}
		return n;
	}
	
	
	


private String getPage(String sql, PageBean page) {
	return sql+" limit "+page.getStartIndex()+","+page.getRows();
}


private String countPage(String sql) {
	return "select count(1) from ( "+sql+" ) t";
}
	

}

方法调用 StudentDao

public class studentDao extends BeanDao<student>{
/**
	 * 删除
	 * @param stu
	 * @return
	 */
	public int deleteStu(student stu){
		String sql = "delete from tb_student where sid = ?";
		return super.executeUpdate(sql, new String [] {"sid" }, stu);
	}
	/**
	 * 增加
	 * @param stu
	 * @return
	 */
	public int addStu(student stu){
		String sql = "insert into tb_student(sid,sname,tid,cid,shobby) values(?,?,?,?,?)";
		return super.executeUpdate(sql, new String [] {"sid","sname","tid","cid","shobby" }, stu);
	}
	/**
	 * 修改
	 * @param stu
	 * @return
	 */
	public int updateStu(student stu){
		String sql = "update tb_student set sname=?,tid=?,cid=?,shobby=? where sid = ? ";
		return super.executeUpdate(sql, new String [] {"sname","tid","cid","shobby","sid"}, stu);
	}
	
	
	public List<student> getAll(student stu, PageBean page){
		String sql = " select * from tb_student where 1=1 ";
		
		if(StringUtils.isNotBlank(stu.getSid()+"")&& stu.getSid() !=0) {
			sql += " and sid = "+stu.getSid()+"  ";
		}
		if(StringUtils.isNotBlank(stu.getTid()+"")&& stu.getTid() !=0) {
			sql += " and tid = "+stu.getTid()+"  ";
		}
		if(StringUtils.isNotBlank(stu.getCid()+"")&& stu.getCid() !=0) {
			sql += " and cid = "+stu.getCid()+"  ";
		}
		if(StringUtils.isNotBlank(stu.getShobby())) {
			sql += " and shobby like '%"+stu.getShobby()+"%' ";
		}
		
		return super.executeQuery(sql, student.class, page);
	}

}

xml的配置

<config>
	<action path="/StudentAction" type="com.web.StudentAction">
		<forward name="index" path="/index.jsp" redirect="false" />
		<forward name="Reindex" path="/StudentAction.action?method=getAll" redirect="true" />
		<forward name="preupdate" path="/update.jsp" redirect="false" />
	</action>

</config>

前台调用xml

<filter>
  	<filter-name>encoding</filter-name>
  	<filter-class>com.filer.EncodingFiter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
  	<servlet-name>dispatcherServlet</servlet-name>
  	<servlet-class>com.framework.DispatcherServlet</servlet-class>//中央处理器
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>dispatcherServlet</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>

调用代码

	href = "StudentAction.action?method=getAll";
	//method就放自己定义好的方法名就行


总结

总的来说,代码量还好,理清思路最为关键

Thanks♪(・ω・)ノ希望对大家有所帮助


http://www.niftyadmin.cn/n/3726056.html

相关文章

计算机联锁控制系统的软件应具备信号操作功能,计算机联锁技术学习包

敌对近路()的条件下&#xff0c;将道岔和敌对进路()&#xff0c;使道岔()转换、敌对进路()建立。7、硬件系统计算机控制系统的硬件主要有()、外部设备、()、输出设备和()等组成。8、支持软件支持软件包括()&#xff0c;高级语言&#xff0c;()&#xff0c;编辑程序&#xff0c;…

python中truncate的用法_Python中truncate()方法有哪些功能?

摘要:下文讲述Python中truncate()的方法的功能简介说明&#xff0c;如下所示:truncate()方法功能:用于截断文件并返回截断的字节长度truncate()方法语法fileObject.truncate([size])--------参数说明--------fileObject:文件对象size:可选当此参数存在时&#xff0c;则文件从开…

Linux中的环境变量配置文件

这篇文章是我之前整理&#xff0c;此次上传。因为刚刚接触linux&#xff0c;一直对里面的变量设置是混淆的&#xff0c;所以查资料整理了一下&#xff0c;以便日后查询。Shell 环境依赖于多个文件的设置。用户并不需要每次登录后都对各种环境变量进行手工设置&#xff0c;通过环…

抖音名字怎么改不了_抖音名字怎么改不了

抖音上很火的点名PPT怎么制作呢&#xff1f;今天的教程帮你全方位解析制作要点快来跟充哥一起学习吧Part.1 原理剖析要点1.如何实现PPT页面的快速跳闪&#xff1f;和之前介绍过的制作快闪PPT类似&#xff0c;点名效果同样可以通过设置幻灯片的切换时间来实现页与页之间快速跳闪…

【mvc之前台优化标签】

目录前言index.jsp整体z:tld自定义标签库标签助手类checkbox标签助手类pageTag标签助手类selectTag助手类效果图总结前言 这一篇是写前台如何使用自定义标签来优化代码 之前一篇是写后台优化代码的&#xff0c;【mvc之后台优化代码】 还是一样&#xff0c;纯代码。 index.j…

揭秘腾讯MTA SDK模块化发展历程

引语 SDK是一种方便常见的开发者工具形式&#xff0c;但越来越多的内嵌功能&#xff0c;可能让SDK服务越来越全&#xff0c;可能会出现功能的重复&#xff0c;造成SDK包越来越重&#xff0c;给App自身带来负担……为App减负&#xff0c;MTA踏上了探索的道路。 作者介绍 陈翔&am…

细说java_细说JAVA反射

Reflection 是 Java 程序开发语言的特征之一&#xff0c;它允许运行中的 Java 程序对自身进行检查&#xff0c;或者说“自审”&#xff0c;并能直接操作程序的内部属性。例如&#xff0c;使用它能获得 Java 类中各成员的名称并显示出来。JavaBean 是 reflection 的实际应用之一…

计算机绘画小房子教案,幼儿园中班美术教案《漂亮的小房子》绘画活动

《幼儿园中班美术教案《漂亮的小房子》绘画活动》由会员分享&#xff0c;可在线阅读&#xff0c;更多相关《幼儿园中班美术教案《漂亮的小房子》绘画活动(5页珍藏版)》请在人人文库网上搜索。1、幼儿园中班美术教案漂亮的小房子绘画活动 点击这里 活动目标&#xff1a;1、学习粘…