一、源码简介
该源码是一个java web项目工程,主要是测试Spring的web层MVC框架,主要包括src、WebRoot主目录,其中src为java源码目录,包括HelloController.java文件,WebRoot主要web工程的相关资源存放目录。项目截图如下所示,点击跳转查看GitHub源码(如需下载基于注释@RequestMapping的spring4以上版本完整MVC的项目源码,点击spring4-mvc项目)
二、项目快照(springmvc低版本)
1. mvc相关xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>@b@<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">@b@@b@<beans>@b@@b@ <bean id="viewResolver"@b@ class="org.springframework.web.servlet.view.InternalResourceViewResolver">@b@ <property name="prefix" value="/WEB-INF/jsp/" />@b@ <property name="suffix" value=".jsp" />@b@ </bean>@b@@b@ <bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">@b@ <property name="mappings">@b@ <props>@b@ <prop key="/hello.do">helloController</prop>@b@ </props>@b@ </property>@b@ </bean>@b@@b@ <bean id="helloController" class="com.ideawu.HelloController">@b@ <!--@b@ <property name="helloManager" ref="helloManager" />@b@ -->@b@ </bean>@b@@b@</beans>
2. Controller层代码
package com.ideawu;@b@@b@import org.springframework.web.servlet.mvc.Controller;@b@import org.springframework.web.servlet.ModelAndView;@b@@b@import javax.servlet.http.HttpServletRequest;@b@import javax.servlet.http.HttpServletResponse;@b@@b@ @b@public class HelloController implements Controller {@b@ /*@b@ * private HelloManager helloManager;@b@ * @b@ * public void setHelloManager(HelloManager helloManager) {@b@ * this.helloManager = helloManager; }@b@ */@b@@b@ public ModelAndView handleRequest(HttpServletRequest request,@b@ HttpServletResponse response) throws Exception {@b@@b@ request.setAttribute("hello_1", "你好啊, Spring!");@b@ request.setAttribute("hello_2", "Hello World!");@b@@b@ return new ModelAndView("hello");@b@ }@b@@b@}
3. 访问测试页,如http://127.0.0.1:9999/SpringMvc/hello.do,效果如下
下面基于spring4.1.4相关依赖包(spring-beans、spring-aop、spring-context、spring-expression、spring-mvc及spring-web等包),项目截图如下,项目本地下载,云盘下载
1.HelloWorldController
package com.xwood.springmvc;@b@ @b@import org.springframework.stereotype.Controller;@b@import org.springframework.ui.Model;@b@import org.springframework.web.bind.annotation.RequestMapping;@b@import org.springframework.web.servlet.ModelAndView; @b@ @b@@Controller@b@public class HelloWorldController {@b@ @b@ @RequestMapping("/hello")@b@ public String hello(Model model) {@b@ model.addAttribute("greeting", "Hello Spring MVC @ http://www.xwood.net/ ");@b@ return "helloworld.jsp";@b@ }@b@ @b@ @RequestMapping("/hello2")@b@ public ModelAndView hello2() {@b@ ModelAndView mv = new ModelAndView("hello2.jsp");@b@ mv.addObject("title", "小木人印象");@b@ mv.addObject("content", "欢迎访问小木人印象,网址:<a href=\"http://www.xwood.net/\">http://www.xwood.net/</a>");@b@ return mv;@b@ }@b@ @b@ @RequestMapping("/hello3")@b@ public String hello3(Model model) {@b@ model.addAttribute("title", "小木人印象");@b@ model.addAttribute("content", "欢迎访问小木人印象,网址:<a href=\"http://www.xwood.net/\">http://www.xwood.net/</a>");@b@ return "hello3";@b@ }@b@ @b@ @RequestMapping("/redirect2")@b@ public ModelAndView redirect() {@b@ ModelAndView mv = new ModelAndView("redirect:/hello2");@b@ return mv;@b@ }@b@ @b@ @RequestMapping("/forward2")@b@ public ModelAndView forward() {@b@ ModelAndView mv = new ModelAndView("forward:/hello2");@b@ return mv;@b@ }@b@ @b@ @b@}
2.spring-mvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>@b@<beans xmlns="http://www.springframework.org/schema/beans"@b@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"@b@ xmlns:p="http://www.springframework.org/schema/p"@b@ xmlns:context="http://www.springframework.org/schema/context"@b@ xmlns:mvc="http://www.springframework.org/schema/mvc"@b@ xsi:schemaLocation="http://www.springframework.org/schema/beans@b@ http://www.springframework.org/schema/beans/spring-beans-4.1.xsd @b@ http://www.springframework.org/schema/context@b@ http://www.springframework.org/schema/context/spring-context-4.1.xsd @b@ http://www.springframework.org/schema/mvc@b@ http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">@b@ @b@ <context:component-scan base-package="com.xwood.springmvc"/>@b@ @b@ <context:annotation-config/>@b@ @b@ @b@ <bean@b@ class="org.springframework.web.servlet.view.InternalResourceViewResolver">@b@ <property name="prefix">@b@ <value>/WEB-INF/pages/</value>@b@ </property>@b@ <property name="suffix">@b@ <value></value>@b@ </property> @b@ </bean>@b@ @b@ @b@ <bean id="FreeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">@b@ <property name="templateLoaderPath" value="/WEB-INF/pages/"/>@b@ <property name="defaultEncoding" value="UTF-8"/>@b@ </bean>@b@ <bean id="FreeMarkerViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">@b@ <property name="suffix" value=".ftl"/>@b@ <property name="contentType" value="text/html;charset=UTF-8"/> @b@ </bean>@b@ @b@ @b@</beans>
四、Restful完整示例
下面基于springmvc的restful示例代码如下,完整的代码下载项目,项目本地下载,云盘下载
1.controller层代码
@Controller@b@@RequestMapping("/user")@b@public class UserController {@b@ @b@ public List<User> list=null;@b@@b@ /**@b@ * user路径下默认显示用户列表@b@ * @return@b@ */@b@ @RequestMapping(method=RequestMethod.GET)@b@ public ModelAndView index(){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("list",list);@b@ @b@ return new ModelAndView("user/index",model);@b@ }@b@ @b@ /**@b@ * 跳转到添加用户页面,约定优于配置,默认匹配文件/WEB-INF/views/user/add.jsp@b@ */@b@ @RequestMapping("add")@b@ public void add(){}@b@ @b@ /**@b@ * 新增保存用户@b@ * @param user@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.POST)@b@ public ModelAndView addUser(User user){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ list.add(user);@b@ @b@ ModelMap model=new ModelMap();@b@ model.addAttribute("list",list);@b@ @b@ return new ModelAndView("user/index",model);@b@ }@b@ @b@ /**@b@ * 查看用户详细信息@b@ * @param id@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.GET,value="{id}")@b@ public ModelAndView viewUser(@PathVariable("id")String id){@b@ User user=findUserById(id);@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("user",user);@b@ @b@ return new ModelAndView("user/view",model);@b@ }@b@ @b@ /**@b@ * 删除用户@b@ * @param id@b@ */@b@ @ResponseBody@b@ @RequestMapping(method=RequestMethod.DELETE,value="{id}")@b@ public String deleteUser(@PathVariable("id")String id){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ removeUserByUserId(id);@b@ return "suc";@b@ }@b@ @b@ /**@b@ * 跳转到编辑页面@b@ * @param id@b@ * @return ModelAndView@b@ */@b@ @RequestMapping("{id}/edit")@b@ public ModelAndView toEdit(@PathVariable("id")String id){@b@ @b@ User user=findUserById(id);@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("user",user);@b@ @b@ return new ModelAndView("user/edit",model);@b@ }@b@ @b@ /**@b@ * 更新用户并跳转到用户列表页面@b@ * @param user@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.PUT)@b@ public ModelAndView edit(User user){@b@ updateUser(user);@b@ return new ModelAndView("redirect:/user/");@b@ }@b@ @b@ @b@ /**@b@ * 造10个用户@b@ * @return List<User>@b@ */@b@ private List<User> getUserList(){@b@ List<User> list=new ArrayList<User>();@b@ for(int i=0; i<10;i++){@b@ list.add(new User((i+1)+"","李四"+(i+1)));@b@ }@b@ return list;@b@ }@b@ /**@b@ * 删除用户@b@ * @param id@b@ * @return List<User>@b@ */@b@ private List<User> removeUserByUserId(String id){@b@ if(list==null)return null;@b@ for(User user:list){@b@ if(user.getUserId().equals(id)){@b@ list.remove(user);@b@ break;@b@ }@b@ }@b@ return list;@b@ }@b@ /**@b@ * 查找用户@b@ * @param id@b@ * @return User@b@ */@b@ private User findUserById(String id){@b@ User user=null;@b@ if(list==null)return null;@b@ for(User _user:list){@b@ if(_user.getUserId().equals(id)){@b@ user=_user;@b@ break;@b@ }@b@ }@b@ return user;@b@ }@b@ /**@b@ * 更新用户@b@ * @param user@b@ */@b@ private void updateUser(User user){@b@ for(User _user:list){@b@ if(_user.getUserId().equals(user.getUserId())){@b@ _user.setUserName(user.getUserName());@b@ break;@b@ }@b@ }@b@ }@b@ @b@ @b@}
2.jsp代码
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>@b@<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>@b@<%@b@ String path = request.getContextPath();@b@ String basePath = request.getScheme() + "://"@b@ + request.getServerName() + ":" + request.getServerPort()@b@ + path + "/";@b@%>@b@@b@<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">@b@<html>@b@<head>@b@<base href="<%=basePath%>">@b@@b@<title>My JSP 'index.jsp' starting page</title> @b@<script type="text/javascript"@b@ src="<%=basePath%>resources/jquery-1.11.0.min.js"></script>@b@ @b@<script type="text/javascript">@b@@b@function deleteUser(id){@b@ $.ajax({@b@ type: 'delete',@b@ url:'<%=basePath%>user/'+id,@b@ dataType:'text', @b@ success:function(data){@b@ if(data=="suc"){@b@ alert("删除成功");@b@ location.reload();@b@ }@b@ },@b@ error:function(data){@b@ }@b@ });@b@}@b@@b@</script>@b@</head>@b@@b@<body>@b@ <div style="margin:0 auto;width:500px;">@b@ <a href="<%=basePath%>user/add">新增用户</a>@b@ <table>@b@ <tr>@b@ <th>用户ID</th>@b@ <th>用户名称</th>@b@ <th>操作</th>@b@ </tr>@b@ <c:forEach var="user" items="${list }">@b@ <tr>@b@ <td>${user.userId }</td>@b@ <td>${user.userName }</td>@b@ <td>@b@ <a href="<%=basePath %>user/${user.userId}/edit">编辑用户</a>@b@ <a href="<%=basePath %>user/${user.userId}">查看用户</a>@b@ <a href="javascript:void(0);" onclick="deleteUser(${user.userId })">删除该用户</a>@b@ </td>@b@ </tr>@b@ </c:forEach>@b@ </table>@b@ </div>@b@</body>@b@</html>
add.jsp
@Controller@b@@RequestMapping("/user")@b@public class UserController {@b@ @b@ public List<User> list=null;@b@@b@ /**@b@ * user路径下默认显示用户列表@b@ * @return@b@ */@b@ @RequestMapping(method=RequestMethod.GET)@b@ public ModelAndView index(){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("list",list);@b@ @b@ return new ModelAndView("user/index",model);@b@ }@b@ @b@ /**@b@ * 跳转到添加用户页面,约定优于配置,默认匹配文件/WEB-INF/views/user/add.jsp@b@ */@b@ @RequestMapping("add")@b@ public void add(){}@b@ @b@ /**@b@ * 新增保存用户@b@ * @param user@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.POST)@b@ public ModelAndView addUser(User user){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ list.add(user);@b@ @b@ ModelMap model=new ModelMap();@b@ model.addAttribute("list",list);@b@ @b@ return new ModelAndView("user/index",model);@b@ }@b@ @b@ /**@b@ * 查看用户详细信息@b@ * @param id@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.GET,value="{id}")@b@ public ModelAndView viewUser(@PathVariable("id")String id){@b@ User user=findUserById(id);@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("user",user);@b@ @b@ return new ModelAndView("user/view",model);@b@ }@b@ @b@ /**@b@ * 删除用户@b@ * @param id@b@ */@b@ @ResponseBody@b@ @RequestMapping(method=RequestMethod.DELETE,value="{id}")@b@ public String deleteUser(@PathVariable("id")String id){@b@ if(list==null){@b@ list=getUserList();@b@ }@b@ removeUserByUserId(id);@b@ return "suc";@b@ }@b@ @b@ /**@b@ * 跳转到编辑页面@b@ * @param id@b@ * @return ModelAndView@b@ */@b@ @RequestMapping("{id}/edit")@b@ public ModelAndView toEdit(@PathVariable("id")String id){@b@ @b@ User user=findUserById(id);@b@ ModelMap model=new ModelMap();@b@ model.addAttribute("user",user);@b@ @b@ return new ModelAndView("user/edit",model);@b@ }@b@ @b@ /**@b@ * 更新用户并跳转到用户列表页面@b@ * @param user@b@ * @return ModelAndView@b@ */@b@ @RequestMapping(method=RequestMethod.PUT)@b@ public ModelAndView edit(User user){@b@ updateUser(user);@b@ return new ModelAndView("redirect:/user/");@b@ }@b@ @b@ @b@ /**@b@ * 造10个用户@b@ * @return List<User>@b@ */@b@ private List<User> getUserList(){@b@ List<User> list=new ArrayList<User>();@b@ for(int i=0; i<10;i++){@b@ list.add(new User((i+1)+"","李四"+(i+1)));@b@ }@b@ return list;@b@ }@b@ /**@b@ * 删除用户@b@ * @param id@b@ * @return List<User>@b@ */@b@ private List<User> removeUserByUserId(String id){@b@ if(list==null)return null;@b@ for(User user:list){@b@ if(user.getUserId().equals(id)){@b@ list.remove(user);@b@ break;@b@ }@b@ }@b@ return list;@b@ }@b@ /**@b@ * 查找用户@b@ * @param id@b@ * @return User@b@ */@b@ private User findUserById(String id){@b@ User user=null;@b@ if(list==null)return null;@b@ for(User _user:list){@b@ if(_user.getUserId().equals(id)){@b@ user=_user;@b@ break;@b@ }@b@ }@b@ return user;@b@ }@b@ /**@b@ * 更新用户@b@ * @param user@b@ */@b@ private void updateUser(User user){@b@ for(User _user:list){@b@ if(_user.getUserId().equals(user.getUserId())){@b@ _user.setUserName(user.getUserName());@b@ break;@b@ }@b@ }@b@ }@b@ @b@ @b@}
edit.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>@b@<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>@b@<%@b@ String path = request.getContextPath();@b@ String basePath = request.getScheme() + "://"@b@ + request.getServerName() + ":" + request.getServerPort()@b@ + path + "/";@b@%>@b@@b@<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">@b@<html>@b@<head>@b@<base href="<%=basePath%>">@b@@b@<title>新增用户页面</title> @b@@b@</head>@b@@b@<body>@b@ <div style="margin:0 auto;width:400px;">@b@ <form action="<%=basePath%>user" method="post">@b@ <input type="hidden" name="_method" value="put" />@b@ <table>@b@ <tr>@b@ <th>用户ID</th>@b@ <th>用户名称</th>@b@ </tr>@b@ <tr>@b@ <td><input type="text" name="userId" id="userId" value="${user.userId }" readonly="readonly"/>@b@ </td>@b@ <td><input type="text" name="userName" id="userName" value="${user.userName }"/>@b@ </td>@b@ </tr>@b@ <tr>@b@ <td colspan="2"><input type="submit" value="保存用户" />@b@ </td>@b@ </tr>@b@ </table>@b@ </form>@b@ </div>@b@</body>@b@</html>
view.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>@b@<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>@b@<%@b@ String path = request.getContextPath();@b@ String basePath = request.getScheme() + "://"@b@ + request.getServerName() + ":" + request.getServerPort()@b@ + path + "/";@b@%>@b@@b@<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">@b@<html>@b@<head>@b@<base href="<%=basePath%>">@b@@b@<title>用户详情页面</title>@b@ @b@</head>@b@@b@<body>@b@ <div style="margin:0 auto;width:400px;">@b@ <form action="<%=basePath%>user" method="post">@b@ <table>@b@ <tr>@b@ <th>用户ID</th>@b@ <th>用户名称</th>@b@ </tr>@b@ <tr>@b@ <td>${user.userId}</td>@b@ <td>${user.userName}</td>@b@ </tr>@b@ <tr>@b@ <td colspan="2"><input type="button" value="返回用户列表"@b@ onclick="history.go(-1)" />@b@ </td>@b@ </tr>@b@ </table>@b@ </form>@b@ </div>@b@</body>@b@</html>
��