目录
- 前言
- 中央控制器 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♪(・ω・)ノ希望对大家有所帮助