1、引入SrpingMVC所使用的Java包:
cglib-nodep-2.1_3.jar、commons-logging.jar、spring-aspects-4.1.7.RELEASE.jar、spring-beans-4.1.7.RELEASE.jar、spring-context-4.1.7.RELEASE.jar
、spring-core-4.1.7.RELEASE.jar、spring-web-4.1.7.RELEASE.jar、spring-webmvc-4.1.7.RELEASE.jar
2、新建Web项目,配置Web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>springmvc</display-name> <!-- 配置Spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置SpringMVC的编码格式 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 加载其他的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value> </context-param> <!-- 配置Spring的前置控制器DispatcherServlet --> <servlet> <servlet-name>spring</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置Spring的url后缀 --> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
3、配置spring-servlet.xml(基中的部分MVC的配置可另外再分一个bean.xml配置,这里为了方便统一放在一个里面):
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- controller方法调用规则:通过url中的method参数指定要执行的controller方法--> <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName" value="action" /> <property name="defaultMethodName" value="view" /> </bean> <!-- 配置MVC的前缀(prefix)和后缀(suffix) --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <!-- <property name="prefix" value="/WEB-INF/" /> --> <property name="suffix" value=".jsp" /> </bean> <!-- 以下是 控制器的配置 --> <bean name="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" > <property name="order" value="1" /> <property name="mappings"> <props> <prop key="user.do">userController</prop> <prop key="index.do">indexController</prop> </props> </property> </bean> <bean name="userController" class="cn.raffaello.controller.UserController"> <property name="userIService" ref="userIService"></property> </bean> <bean name="indexController" class="cn.raffaello.controller.IndexController" /> <!-- ServiceBean的配置 --> <bean name="userIService" class="cn.raffaello.service.impl.UserServiceImpl" /> </beans>
4、新建Model,User:
public class User { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
5、新建ServiceBean并实现一个模拟的数据保存添加操作:
public interface UserIService { void saveOrUpdate(User user); User getUserById(Integer id); void delete(Integer id); List<User> getUsers(); Integer getNewId(); }
public class UserServiceImpl implements UserIService { private Map<Integer,Object> map=new HashMap<Integer,Object>(); private Map<String,Integer> idCount=new HashMap<String,Integer>(); @Override public void saveOrUpdate(User user) { map.put(user.getId(), user); } @Override public User getUserById(Integer id) { if(map.containsKey(id)){ return (User)map.get(id); } return new User(); } @Override public void delete(Integer id) { map.remove(id); } @Override public List<User> getUsers() { List<User> list=new ArrayList<User>(); for(Integer key : map.keySet()){ list.add((User)map.get(key)); } return list; } @Override public Integer getNewId() { if(!idCount.containsKey("ids")){ Integer id=1; idCount.put("ids", id); return id; }else{ Integer id=idCount.get("ids"); id=id+1; idCount.put("ids", id); return id; } } }
6、新建控制器UserController:
public class UserController implements Controller{ private UserIService userIService; @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { String param=""; param=req.getParameter("param"); //新增控制器跳转 if(param.trim().equals("add")){ return new ModelAndView("/WEB-INF/userAdd"); }else if(param.trim().equals("edit")){ //编辑控制器跳转 Integer id=-1; if(!req.getParameter("userId").trim().equals("")){ id=Integer.parseInt(req.getParameter("userId").trim()); } User user=userIService.getUserById(id); req.setAttribute("user", user); return new ModelAndView("/WEB-INF/userAdd"); }else if(param.trim().equals("userList")){ //列表页面跳转 List<User> list=userIService.getUsers(); req.setAttribute("userList", list); return new ModelAndView("/WEB-INF/userList"); }else if(param.trim().equals("save")){ //新增的保存操作 User user=new User(); String name=req.getParameter("name").trim(); user.setId(userIService.getNewId()); user.setName(name); userIService.saveOrUpdate(user); List<User> list=userIService.getUsers(); req.setAttribute("userList", list); return new ModelAndView("/WEB-INF/userList"); }else if(param.trim().equals("update")){ //修改的保存操作 Integer id=-1; if(!req.getParameter("userId").trim().equals("")){ id=Integer.parseInt(req.getParameter("userId").trim()); } String name=req.getParameter("name").trim(); User user=userIService.getUserById(id); user.setName(name); userIService.saveOrUpdate(user); List<User> list=userIService.getUsers(); req.setAttribute("userList", list); return new ModelAndView("/WEB-INF/userList"); }else if(param.trim().equals("delete")){ //删除操作 Integer id=-1; if(!req.getParameter("userId").trim().equals("")){ id=Integer.parseInt(req.getParameter("userId").trim()); } userIService.delete(id); List<User> list=userIService.getUsers(); req.setAttribute("userList", list); return new ModelAndView("/WEB-INF/userList"); }else if(param.trim().equals("detail")){ //详细用户页面 Integer id=-1; if(!req.getParameter("userId").trim().equals("")){ id=Integer.parseInt(req.getParameter("userId").trim()); User user=userIService.getUserById(id); req.setAttribute("user", user); } return new ModelAndView("/WEB-INF/userDetail"); }else if(param.trim().equals("list")){ // list列表 List<User> list=userIService.getUsers(); req.setAttribute("userList", list); return new ModelAndView("/WEB-INF/userList"); } return new ModelAndView("fail"); //return forword("stu/studentList", context); //同样也可以使用forword进行页面跳转 //使用Map向前台输出数据时,获取操作同Request一样,可以在前台使用${名字}来获取如下例,可以使用${message}获取 //Map<String,String> resultMap = new HashMap<String,String>(); //resultMap.put("message", "欢迎来到首页111"); //return new ModelAndView("index",resultMap); } public UserIService getUserIService() { return userIService; } public void setUserIService(UserIService userIService) { this.userIService = userIService; } }
7、然后就是页面啦:
新增页面:
<body> <a href="user.do?param=userList">用户列表</a> <h3>新增用户</h3> <form action="user.do" method="post"> <c:if test="${user!=null }"> <input type="hidden" name="param" value="update" /> </c:if> <c:if test="${user==null }"> <input type="hidden" name="param" value="save" /> </c:if> <input type="hidden" name="userId" value="${user.id }" /> 用户名:<input type="text" name="name" value="${user.name }" /> <input type="submit" value="提交" /> </form> </body>
访问地址:http://localhost/user.do?param=add
修改页面也是此页面,访问地焉http://localhost/user.do?param=edit&userId=12
用户信息页面:
<body> <a href="user.do?param=userList">用户列表</a> <h3>用户详细信息:</h3> <ul> <li>ID:${user.id }</li> <li>用户名:${user.name }</li> </ul> </body>
用户列表页面:
<body> <a href="user.do?param=add">新增用户</a> <h3>用户列表:</h3> <table> <tr> <td>ID</td> <td>姓名</td> <td>操作</td> </tr> <c:forEach items="${userList }" var="user"> <tr> <td>${user.id }</td> <td>${user.name }</td> <td><a href="user.do?param=edit&userId=${user.id }">修改</a></td> </tr> </c:forEach> </table> </body>
下图是效果图:
其他的SpringMVC文档:
http://liudeh-009.iteye.com/blog/1267880
http://jinnianshilongnian.iteye.com/blog/1594806
http://www.importnew.com/15141.html
Spring各个版本下载: