SpringMVC项目
一、说明
该项目是为了演示SpringMVC框架中涉及到的一些知识点,相对独立,掌握这些,基本上就能够解决工作中遇到的一些问题。
整个项目的构建规划如下:
1、创建一个标准的Maven Web项目;
2、使它成为一个SpringMVC项目;
3、增删改查操作(为了演示项目独立性,暂不引入Hibernate、Mybatis框架);
4、服务端验证Validation;
5、SpringMVC中JSON 数据返回;
6、SpringMVC中实现文件的上传;
二、SpringMVC创建项目过程;
1、创建一个标准的Maven Web项目;
2、在pom.xml中添加SpringMVC 依赖;
3、在 web.xml中配置 ContextLoaderListener(上下文配置) 和 DispatcherServlet;
4、根据web.xml中配置,在WEB-INF下添加spring-mvc.xml, 在 src/main/resources/spring 下添加 applicationContext.xml;
5、在src/main/java/com/istudy/springmvc/controller 下添加IndexController.java 文件,配置默认跳转方法;
6、根据IndexController.java 中配置默认跳转页面;
7、在WEB-INF 下添加views文件夹和默认页面Index.jsp
三、运行
1、 导入
Eclipse->File->Import->Maven->Existing Maven Projects
2、 右键pom.xml,Run AS Maven build ... 输入jetty:run 运行
3、 访问地址 http://localhost:5678/springmvc
四、相关代码
1、pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.istudy</groupId> <artifactId>springmvc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springmvc Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- SPRING MVC START --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <!-- SPRING MVC END --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- Validation Begin --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <!-- Validation End --> <!--File UPLOAD Begin --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.1</version> </dependency> <!--File UPLOAD End --> <!--JSON Begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <!-- Jackson is a high-performance JSON processor (parser, generator) --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>${jackson.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <!-- Data Mapper package is a high-performance data binding package built on Jackson JSON processor --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>${jackson.version}</version> <type>jar</type> <scope>compile</scope> </dependency> <!--JSON END --> </dependencies> <properties> <jdk.version>1.7</jdk.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.1.RELEASE</spring.version> <jackson.version>1.9.3</jackson.version> <jetty.version>7.6.7.v20120910</jetty.version> </properties> <build> <finalName>springmvc</finalName> <plugins> <!-- compiler插件, 设定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>${jdk.version}</source> <target>${jdk.version}</target> <encoding>UTF-8</encoding> <skip>true</skip> <showWarnings>true</showWarnings> </configuration> </plugin> <!-- jetty --> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <configuration> <webAppConfig> <contextPath>/${project.artifactId}</contextPath> </webAppConfig> <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector"> <port>5678</port> </connector> </connectors> </configuration> </plugin> </plugins> </build> </project>
2、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_2_5.xsd" version="2.5"> <display-name>A SpringMVC Project</display-name> <!--Spring 应用上下文 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring/applicationContext.xml</param-value> </context-param> <servlet> <servlet-name>springServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 使用Annotation自动注册Bean,解决事物失效问题:在主容器中不扫描@Controller注解,在SpringMvc中只扫描@Controller注解。 --> <!-- 将@Service Bean放在主容器中加载,和事务配置在一个容器中 --> <!-- base-package 如果多个,用“,”分隔 --> <context:component-scan base-package="com.istudy.springmvc"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 根本原因:由子容器扫描装配了@Service 注解的实例。spring的context是父子容器,由ServletContextListener 加载spring配置文件产生的是父容器, springMVC加载配置文件产生的是子容器,子容器对Controller进行扫描装配时装配了@Service注解的实例 (@Controller 实例依赖@Service实例), 而该实例理应由父容器进行初始化以保证事务的增强处理,所以此时得到的将是原样的Service(没有经过事务加强处理,故而没有事务处理能力。) --> </beans>
4、IndexController.java
package com.istudy.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
*
* @desc: springmvc 入口
* @author: wyc
* @createTime: 2016年12月2日 下午5:00:49
* @history:
* @version: v1.0
*/
@Controller
public class IndexController {
/**
*
* 项目默认跳转页面
* @author: wyc
* @createTime: 2016年12月2日 下午5:01:07
* @history:
* @return String
*/
@RequestMapping({ "/", "/login", "/welcome", "/index" })
public String index() {
return "index";
}
}
5、UserController.java
package com.istudy.springmvc.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.istudy.springmvc.model.User; /** * * * @desc: 用户信息 控制层 * @author: wyc * @createTime: 2016年12月2日 下午5:19:17 * @history: * @version: v1.0 */ @Controller @RequestMapping("/user") public class UserController { Map<Long,User> usermap=new HashMap<Long,User>(); public UserController(){ User u1=new User(1L,"zhangsan","1@23456",new Date(),"zhangsan@163.com"); User u2=new User(2L,"lisi","123@456",new Date(),"lisi@163.com"); User u3=new User(3L,"sunliu","123456@7",new Date(),"sunliu@163.com"); usermap.put(u1.getId(), u1); usermap.put(u2.getId(), u2); usermap.put(u3.getId(),u3); } /** * * 获取用户列表数据,跳转到用户列表页面 * @author: wyc * @createTime: 2016年12月5日 上午9:16:17 * @history: * @param user * @return ModelAndView */ @RequestMapping(value = "/list") public ModelAndView list(User user){ ModelAndView mv=new ModelAndView("user/list"); List<User> list=new ArrayList<User>(); for (Map.Entry<Long,User> entry: usermap.entrySet()) { list.add(entry.getValue()); } mv.addObject("userlist", list); return mv; } /** * * 保存用户 * @author: wyc * @createTime: 2016年12月2日 下午5:19:35 * @history: * @param user * @return Object */ @RequestMapping(value = "/save") public String save(@Valid User user,BindingResult bindingResult){ //服务端验证示例 if(bindingResult.hasErrors()){ return "/user/add"; }else{ //编辑操作 if(user.getId()!=null){ //模拟编辑,先移除,后添加 usermap.remove(user.getId()); usermap.put(user.getId(), user); }else{ //保存操作 double random=Math.round(Math.random()*10000); //模拟主键生成 long id = new Double(random).longValue(); user.setId(id); usermap.put(user.getId(), user); } return "redirect:/user/list"; } } /** * * 删除用户 * @author: wyc * @createTime: 2016年12月2日 下午5:19:45 * @history: * @param id * @return Object */ @RequestMapping(value = "/delete/{id}") public String delete(@PathVariable("id") Long id,HttpServletRequest request){ //移除用户 usermap.remove(id); //重定向到列表action return "redirect:/user/list"; } /** * * 跳转到用户编辑页面 * @author: wyc * @createTime: 2016年12月5日 下午2:15:26 * @history: * @param id * @param request * @return ModelAndView */ @RequestMapping(value = "/add") public ModelAndView edit(HttpServletRequest request){ User user=new User(); ModelAndView mv=new ModelAndView("user/edit"); mv.addObject("user", user); return mv; } /** * * 跳转到用户编辑页面 * @author: wyc * @createTime: 2016年12月5日 下午2:15:26 * @history: * @param id * @param request * @return ModelAndView */ @RequestMapping(value = "/edit/{id}") public ModelAndView edit(@PathVariable("id") Long id,HttpServletRequest request){ User user=usermap.get(id); ModelAndView mv=new ModelAndView("user/edit"); mv.addObject("user", user); return mv; } /** * * 将时间字符串绑定为时间类型 * @author: wyc * @createTime: 2016年12月6日 上午8:38:30 * @history: * @param binder void */ @InitBinder public void initBinder(ServletRequestDataBinder binder) { binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); } }