很久没有过来写东西了,最近搞其他的开发去了,很少来弄Java。今天没事做就写了个Spring MVC的超级简单的例子。
参考地址为: http://static.springsource.org/spring/docs/2.0.0/reference/mvc.html
进入正题。spring采用的3.0.5版本,首先是包的使用有,web容器用的是Tomcat6.0.32。
首先是spring在web.xml里面的配置:
<servlet> <servlet-name>main</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>main</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
添加以上内容,然后说明一下,main这里还是有文章的,说的明白一点。servlet-name的值为main。那么下面在 /WEB-INF/ 下面就创建一个main-servlet.xml的文件,就是[servlet-name的值] -servlet.xml的格式保存。
我这里就是main-servlet.xml。如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="springappController" class="xl.spring.demo.SpringController" /> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="hell.do">springappController</prop> </props> </property> </bean> </beans>
然后这里的hell.do是地址栏敲入的名称,后面的 springappController就是指上面的id名称,对应的实体类就是
xl.spring.demo.SpringController
下面贴SpringController.java的代码:
package xl.spring.demo; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; /** * <code>SpringController</code> * <code>控制层与视图层的交互</code> * * @author XL * Jun 3, 201110:10:20 AM * @version 1.0 */ public class SpringController implements Controller { // protected final Log logger = LogFactory.getLog(getClass()); @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { request.setAttribute("xl", "This is first Spring MVC by XL!"); ModelAndView mv = new ModelAndView("index.jsp"); return mv; } }
然后就是index.jsp的代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML> <html> <head> <title>Spring MVC</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> ${xl} </body> </html>
然后在地址栏敲入
http://localhost:8081/springmvc/hell.do
结果:
This is first Spring MVC by XL!
搞定,收工。