从一本书上看到一个mvc的简单实现,有点像struts2,大家分享一下
1、核心一个FrontController拦截所有请求,web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>FrontController</servlet-name>
<servlet-class>am.core.FrontController</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/classes/am-config.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FrontController</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
FrontController:
package am.core;
import java.io.IOException;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import am.common.Const;
import am.util.ConfigXMLParser;
public class FrontController extends HttpServlet {
private static final Log log=LogFactory.getLog(ConfigXMLParser.class);
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
ServletContext context=this.getServletContext();
String config_file=this.getServletConfig().getInitParameter("config");
String dispatcher_name=this.getServletConfig().getInitParameter("dispatcher");
if(config_file==null||config_file.equals(""))
config_file="/WEB-INF/classes/am-config.xml";
if(dispatcher_name==null||dispatcher_name.equals(""))
dispatcher_name=Const.DEFAULT_DISPATCHER;
try{
Map<String,ActionModel> resources=ConfigXMLParser.newInstance().parse(config_file,context);
System.out.println(resources);
context.setAttribute(Const.ACTIONS_ATTR, resources);
log.info("初始化配置文件成功");
}catch(Exception e){
log.error("初始化配置文件失败");
e.printStackTrace();
}
try{
Class c=Class.forName(dispatcher_name);
Dispatcher dispatcher=(Dispatcher)c.newInstance();
context.setAttribute(Const.DISPATCHER_ATTR, dispatcher);
log.info("初始化Dispatcher成功");
}catch(Exception e){
log.error("初始化Dispatcher失败");
e.printStackTrace();
}
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.process(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.process(request, response);
}
protected void process(HttpServletRequest request,
HttpServletResponse response)throws ServletException,IOException{
ServletContext context=this.getServletContext();
String reqURL=request.getRequestURL().toString();
int i=reqURL.lastIndexOf(".");
String contextPath=request.getContextPath();
int j=reqURL.indexOf(contextPath);
String path=reqURL.substring(contextPath.length()+j,i);
request.setAttribute(Const.REQUEST_ATTR, path);
Dispatcher dispatcher=(Dispatcher)context.getAttribute(Const.DISPATCHER_ATTR);
String nextPage=dispatcher.getNextUrl(request, response, context);
RequestDispatcher forwarder=request.getRequestDispatcher("/"+nextPage);
forwarder.forward(request,response);
}
}
am-config.xml为配置文件,结构如下:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
<action path="/login" class="am.action.LoginAction">
<forward name="success" url="hello.jsp"/>
<forward name="error" url="login.jsp"/>
</action>
</actions>
FrontController拦截所有请求,根据请求URL解析出path,根据path由Dispatcher执行具体action,返回nextpage。
ActionDispatcher如下:
package am.core;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import am.common.Const;
public class ActionDispatcher implements Dispatcher {
private ServletContext context;
private static final Log log=LogFactory.getLog(ActionDispatcher.class);
public String getNextUrl(HttpServletRequest request,
HttpServletResponse response, ServletContext context) {
setServletContext(context);
Map<String,ActionModel> actions=
(Map<String,ActionModel>)context.getAttribute(Const.ACTIONS_ATTR);
String reqPath=(String)request.getAttribute(Const.REQUEST_ATTR);
ActionModel actionModel=actions.get(reqPath);
String forward_name="";
ActionForward actionForward;
try{
Class c=Class.forName(actionModel.getClassName());
Action action=(Action)c.newInstance();
if(ValuesSetter.setValues(request, action)){
forward_name=action.execute(request, response, context);
}else{
forward_name=Action.ERROR;
}
}catch(Exception e){
log.error("can not find action"+actionModel.getClassName());
}
actionForward=actionModel.getForwards().get(forward_name);
if(actionForward==null){
log.error("can not find page for forward "+forward_name);
return null;
}else{
return actionForward.getViewUrl();
}
}
public void setServletContext(ServletContext context) {
// TODO Auto-generated method stub
this.context = context;
}
}
实现原理和struts差不多,有助于我们理解struts,具体代码可见附件。
分享到:
相关推荐
mystruts简易MVC框架实现,实现mvc思想,部分代码参考struts1.x
用MVC实现登陆注册Servlet javabean
是一个初学mvc时写的小例子,对理解mvc很有帮助
C#的mvc框架,实现简单的web功能。可以应用在泛微oa等需要基础开发简单功能的网站。erp,crm等系统。
这是一个实现网上购物商城购物车系统的代码,采用JAVAEE的MVC模式,采用的最简单的实现方式,有利于初学者对MVC模式的理解。
spring mvc mybatis mysql
使用mvc编写的一个简易的购物管理系统,包括管理员编辑商品信息,更新商品的价格以及数量,还可以删除商品。该系统还能实现用户对其商品进行虚拟购买操作。
一个简单的mvc实例,实现了简单的增删改查,可做为基础更方便理解struts2,SpringMvc等框架。
基于mvc框架 实现留言板 JSP+Servlet+javabean简单的结合应用,很好的代码
这是一个见得MVC实例,将MVC的各个部分清晰的展现了出来。主要是学生信息管理方面,很简洁,有助于理解这个模式。
PHP实现简单mvc,带数据库,可进行学习,后台开发等。
C++实现简单的MVC框架
MVC java实现的简单案例 给定球半径 自动感知改变表面积 体积 包括两种视图 文本和图形界面
基于Cglib简单实现Spring体系(Ioc+Aop+Mvc)基于Cglib简单实现Spring体系(Ioc+Aop+Mvc)基于Cglib简单实现Spring体系(Ioc+Aop+Mvc)基于Cglib简单实现Spring体系(Ioc+Aop+Mvc)基于Cglib简单实现Spring体系(Ioc+Aop+Mvc)...
适合新手学习jsp参考代码,尤其是想了解mvc架构的同学,可以下载学习一下
ASP.NET MVC 4 插件化架构简单实现 ASP.NET MVC 4 插件化架构简单实现-思路篇 http://blog.csdn.net/hao_ds/article/details/42102969 ASP.NET MVC 4 插件化架构简单实现-实例篇 ...
该项目是个简单的实现 一个登录 注册系统。 不过用到的知识有: jsp:session,cookies知识。 还实现了验证码,img.jsp javascript:对注册输入信息的判断。 jdbc数据库连接; javabeans下的两个类: 1,封装了学生...
java web MVC的实现(JSP+Servlet+javaBean) 简单的MVC实现登录功能,使用初学者
里面的配置都有说明,配置可以直接拿来用在别的项目中去。初学者很适合,内附数据库
MVC实现增删改查Demo,内容详细,代码齐全、完善,你下载绝对不会吃亏,觉得好请点赞,谢谢!