目录
自定义MVC存在的问题
基于上次我们所写的自定义MVC框架01时的基础上解决一下问题
基本工作
导入以下类,导入jar包
中央控制器:
package com.lucy.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;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.jsp.PageContext;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;import com.lucy.framework.Action;
import com.lucy.framework.ActionModel;
import com.lucy.framework.ConfigModelFactory;
import com.lucy.framework.ForwardModel;
import com.lucy.framework.ModelDriven;
import com.lucy.framework.configModel;/**
* 中央控制器:
* 主要接受浏览器,找到对应的处理人---action
* @author lucy
*
*/
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Map<String, Action> actions=new HashMap<String, Action>();
private configModel configmodel;
//处程序启动 会加载一次初始化
@Override
public void init() throws ServletException {
// actions.put("/book", new BookAction());
// actions.put("/order", new OrderAction());
// 解决这种做法的方法
try {
// getInitParameter的作用是拿到web.xml中的servlet的信息配置的参数
String configLocation =this.getInitParameter("configLocation");//配置地址
if(configLocation==null||"".equals(configLocation)) {
configmodel=ConfigModelFactory.bulid();
}
else {
configmodel=ConfigModelFactory.bulid(configLocation);
}
} catch (Exception e) {
e.printStackTrace();
}
}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getRequestURI();//http://locatio:8080/mvc/book.action?methodName=list
// 要拿到/book 就是最后一个.为止--截取地址
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// System.out.println("路径"+url),当前需要config.xml的全路径敏,然后反射实例化
Action action=actions.get(url);//路径
// 相对于上一种从map集合里获取总控制器,
ActionModel am=configmodel.pop(url);
if(am==null) {
throw new RuntimeException("action 配置有误");
}
String type=am.getType();//是action子控制器的全路径名
try {
Action action1 =(Action)Class.forName(type).newInstance();
// action1.execute(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}}
子控制器================================================================================================
package com.lucy.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/**子控制器 --对应处理人
* 对应请求的人
* @author lucy
*
*/
public interface Action {
void execute(HttpServletRequest request, HttpServletResponse response) ;
}
Demo.jsp界面代码
<h3>参数传递封装问题优化</h3>
<a href="${pageContext.request.contextPath }/*.action?methodName=add&bid=9898&bname=laoliu&price=123">增加</a>
创建一个实体类---book
package com.lucy.entity;
public class Book {
private int bid;
private String bname;
private float price;
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
public Book(int bid, String bname, float price) {
this.bid = bid;
this.bname = bname;
this.price = price;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
- package com.lucy.web;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import com.lucy.entity.Book;
- import com.lucy.framework.Action;
- import com.lucy.framework.ActionSupport;
- import com.lucy.framework.ModelDriven;
-
- /**具体action ---若实体类改变,则用此类来进行修改实体类
- * @author lucy
- *
- */
- public class BookAction extends ActionSupport implements ModelDriven<Book>{
- private Book book=new Book();
-
- private void load(HttpServletRequest request, HttpServletResponse response) {
- System.out.println("在同一个orderservlet中调用load方法");
- }
-
- private String list(HttpServletRequest request, HttpServletResponse response) {
- System.out.println("在同一个orderservlet中调用list方法");
- return "success" ;
- }
-
- private void edit(HttpServletRequest request, HttpServletResponse response) {
- System.out.println("在同一个orderservlet中调用edit方法");
-
- }
-
- private void del(HttpServletRequest request, HttpServletResponse response) {
- System.out.println("在同一个orderservlet中调用del方法");
-
- }
-
- private String add(HttpServletRequest request, HttpServletResponse response) {
- // 方法1 接收参数
- // String bid=request.getParameter("bid");
- // String bname=request.getParameter("bname");
- // String price=request.getParameter("price");
- // Book book=new Book();
- // book.setBid(Integer.valueOf(bid));
- // book.setBname(bname);
- // book.setPrice(Integer.valueOf(price));
-
- System.out.println("在同一个orderservlet中调用add方法");
- return "failed";
- }
- //正式调方法前,book中的属性 要被赋值
- @Override
- public Book getModel() {
- return book;
- }
-
- }
package com.lucy.framework;
/**方法2: 拿到参数
* 模型驱动接口:接受前台jsp传递的参数,并且封装到实体类里
* @author lucy
*
*/
public interface ModelDriven<T> {
T getModel();
}
子控制器
package com.lucy.framework;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/**子控制器 --对应处理人
* 对应请求的人
* @author lucy
*
*/
public interface Action {
String execute(HttpServletRequest request, HttpServletResponse response) ;
}
package com.lucy.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;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.jsp.PageContext;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;import com.lucy.framework.Action;
import com.lucy.framework.ActionModel;
import com.lucy.framework.ConfigModelFactory;
import com.lucy.framework.ForwardModel;
import com.lucy.framework.ModelDriven;
import com.lucy.framework.configModel;/**
* 中央控制器:
* 主要接受浏览器,找到对应的处理人---action
* @author lucy
*
*/
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// ?
private Map<String, Action> actions=new HashMap<String, Action>();
/**
* 通过建模我们知道最终configModel对象包含config.xml中的所有子控制器信息
* 目标1---同时为了解决中央控制器能够加载动态保存子控制器的信息,那么我们只需要引入configModel对象即可
* 2.参数传递封装问题优化
* 3.对于方法执行机构转发重定向优化
* 4.框架配置文件名可改变
*/
private configModel configmodel;
//处程序启动 会加载一次初始化
@Override
public void init() throws ServletException {
// actions.put("/book", new BookAction());
// actions.put("/order", new OrderAction());
// 解决这种做法的方法
try {
// getInitParameter的作用是拿到web.xml中的servlet的信息配置的参数
String configLocation =this.getInitParameter("configLocation");//配置地址
if(configLocation==null||"".equals(configLocation)) {
configmodel=ConfigModelFactory.bulid();
}
else {
configmodel=ConfigModelFactory.bulid(configLocation);
}
} catch (Exception e) {
e.printStackTrace();
}
}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getRequestURI();//http://locatio:8080/mvc/book.action?methodName=list
// 要拿到/book 就是最后一个.为止--截取地址
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// System.out.println("路径"+url),当前需要config.xml的全路径敏,然后反射实例化
Action action=actions.get(url);//路径
// 相对于上一种从map集合里获取总控制器,
ActionModel am=configmodel.pop(url);
// System.out.println("ActionModel:"+am);//?
if(am==null) {
throw new RuntimeException("action 配置有误");
}
String type=am.getType();//是action子控制器的全路径名
try {
Action action1 =(Action)Class.forName(type).newInstance();
//action 是bookAction
if(action instanceof ModelDriven) {
ModelDriven md=(ModelDriven) action;
Object model=md.getModel();
//要给model里的属性赋值,首先要接收前台jsp的参数 ,req.getpmap()
// PropertyUtils.getProperty(, name);//从某一个对象中取一个参数
// 将前台参数封装进实体类
BeanUtils.populate(model, request.getParameterMap());
System.out.println(model);
}
action1.execute(request, response);} catch (Exception e) {
e.printStackTrace();
}
}}
config.xml类=======================================================================
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.lucy.web.BookAction">
<forward name="success" path="/demo2.jsp" redirect="false" />
<forward name="failed" path="/demo3.jsp" redirect="true" />
</action>
<action path="/order" type="com.lucy.web.OrderAction">
<forward name="failedxx" path="/reg.jsp" redirect="false" />
<forward name="success" path="/login.jsp" redirect="true" />
</action>
</config>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>0624_MVC</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.lucy.web.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>Lucy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
package com.lucy.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;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.jsp.PageContext;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;import com.lucy.framework.Action;
import com.lucy.framework.ActionModel;
import com.lucy.framework.ConfigModelFactory;
import com.lucy.framework.ForwardModel;
import com.lucy.framework.ModelDriven;
import com.lucy.framework.configModel;/**
* 中央控制器:
* 主要接受浏览器,找到对应的处理人---action
* @author lucy
*
*/
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// ?
private Map<String, Action> actions=new HashMap<String, Action>();
/**
* 通过建模我们知道最终configModel对象包含config.xml中的所有子控制器信息
* 目标1---同时为了解决中央控制器能够加载动态保存子控制器的信息,那么我们只需要引入configModel对象即可
* 2.参数传递封装问题优化
* 3.对于方法执行机构转发重定向优化
* 4.框架配置文件名可改变
*/
private configModel configmodel;
//处程序启动 会加载一次初始化
@Override
public void init() throws ServletException {
// actions.put("/book", new BookAction());
// actions.put("/order", new OrderAction());
// 解决这种做法的方法
try {
// getInitParameter的作用是拿到web.xml中的servlet的信息配置的参数
String configLocation =this.getInitParameter("configLocation");//配置地址
if(configLocation==null||"".equals(configLocation)) {
configmodel=ConfigModelFactory.bulid();
}
else {
configmodel=ConfigModelFactory.bulid(configLocation);
}
} catch (Exception e) {
e.printStackTrace();
}
}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getRequestURI();//http://locatio:8080/mvc/book.action?methodName=list
// 要拿到/book 就是最后一个.为止--截取地址
url=url.substring(url.lastIndexOf("/"),url.lastIndexOf("."));
// System.out.println("路径"+url),当前需要config.xml的全路径敏,然后反射实例化
Action action=actions.get(url);//路径
// 相对于上一种从map集合里获取总控制器,
ActionModel am=configmodel.pop(url);
// System.out.println("ActionModel:"+am);//?
if(am==null) {
throw new RuntimeException("action 配置有误");
}
String type=am.getType();//是action子控制器的全路径名
try {
Action action1 =(Action)Class.forName(type).newInstance();
//action 是bookAction
if(action instanceof ModelDriven) {
ModelDriven md=(ModelDriven) action;
Object model=md.getModel();
//要给model里的属性赋值,首先要接收前台jsp的参数 ,req.getpmap()
// PropertyUtils.getProperty(, name);//从某一个对象中取一个参数
// 将前台参数封装进实体类
BeanUtils.populate(model, request.getParameterMap());
System.out.println(model);
}
// 在正式调用方法前,book的属性要被赋值
String result=action1.execute(request, response);
ForwardModel forwardmodel =ActionModel.pop(result);
if(forwardmodel==null) {
throw new RuntimeException("forward config error!");
}
String path=forwardmodel.getPath();//路径
request.getRequestDispatcher(path).forward(request, response);//转发
// 拿到是否需要转发的配置
boolean redirect=forwardmodel.isRedirect();
if(redirect) {
response.sendRedirect(request.getServletContext().getContextPath()+path);
}
else {
request.getRequestDispatcher(path).forward(request, response);
}
//
// action1.execute(request, response);//
} catch (Exception e) {
e.printStackTrace();
}
}}