转载自网易微博 暖暖 原文
SpringMVC框架
Spring的web框架围绕DispatcherServlet设计。 DispatcherServlet的作用是将请求分发到不同的处理器。
DispatcherServlet类似Struts2的*处理器,SpringMVC框架是被用来取代Struts2的,SpringMVC里面的Controller类似Struts2中Action
这里面我用的版本是SpringMVC3
SpringMVC开发步骤:
一、导入jar包:导入Spring中的aop、asm、aspects、beans、context、context.support、core、expression、jdbc、orm、transaction、web、web.servlet的jar包,另外导入commons-logging-1.1.1.jar包
二、在web.xml中配置DispatcherServlet
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 8 <!-- 配置DispatcherServlet --> 9 <servlet> 10 <!-- 约定:此名称springmvc必须与配置文件springmvc-servlet.xml保持一致(这里都是springmvc) --> 11 <servlet-name>springmvc</servlet-name> 12 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 13 <!-- 配置:服务器启动时自动加载此Servlet --> 14 <load-on-startup>1</load-on-startup> 15 </servlet> 16 <servlet-mapping> 17 <servlet-name>springmvc</servlet-name> 18 <url-pattern>/</url-pattern> 19 </servlet-mapping> 20 21 22 <display-name></display-name> 23 <welcome-file-list> 24 <welcome-file>index.jsp</welcome-file> 25 </welcome-file-list> 26 </web-app>
三、在WEB-INF中新建springmvc-servlet.xml(其中的springmvc是上面的servlet-name节点的值)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!-- 注意下面不要忘记导入mvc、context的schema --> 3 <beans xmlns="http://www.springframework.org/schema/beans" 4 xmlns:mvc="http://www.springframework.org/schema/mvc" 5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xsi:schemaLocation=" 8 http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 12 http://www.springframework.org/schema/context 13 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 14 15 <!-- 开启自动扫描包 --> 16 <context:component-scan base-package="com.kaishengit.web"/> 17 <!-- 开启注解驱动 --> 18 <mvc:annotation-driven/> 19 <!-- 在地址栏访问 "网站根路径 + /404",所跳转到的页面404.jsp --> 20 <mvc:view-controller path="/404" view-name="404"/> 21 <mvc:view-controller path="/500" view-name="500"/> 22 <!-- 23 配置不用DispatcherServlet拦截的路径(例如:图片、CSS样式、js文件...): 24 路径可以自己设置,这里面我用static(WebRoot中的文件夹); 25 其中的"**"代表路径及其子路径 26 --> 27 <mvc:resources location="/static/" mapping="/static/**"/> 28 29 30 31 32 <!-- 配置视图解析器 --> 33 <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> 34 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> 35 <!-- 36 上面的配置是固定的,下面两个配置意思是:如果你要访问index视图, 37 它会自动 prefix(前缀) + index + suffix(后缀), 38 生成/WEB-INF/views/index.jsp 39 --> 40 <property name="prefix" value="/WEB-INF/views/"/> 41 <property name="suffix" value=".jsp"/> 42 </bean> 43 44 <!-- 配置文件上传解析器 --> 45 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 46 <!-- 上面配置是固定的,下面是配置上传文件的最大大小 --> 47 <property name="maxUploadSize" value="1000000"/> 48 </bean> 49 50 51 </beans>
四、前面配置完全,现在我们正式开始开发
1>新建一个Controller类
a.我们新建一个Controller类(类似Struts2中的Action类):AppController.java
1 package com.kaishengit.web; 2 3 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.stereotype.Controller; 6 import org.springframework.web.bind.annotation.RequestMapping; 7 import org.springframework.web.bind.annotation.RequestMethod; 8 import org.springframework.web.servlet.ModelAndView; 9 10 import com.kaishengit.service.UserService; 11 12 13 @Controller//1.标记一个Controller 14 public class AppController { 15 16 /** 17 * Service...:和以前注入方式一样 18 */ 19 private UserService userService; 20 21 //2.标记一个请求路径(URL:http://xxx/index.html),请求方式设置为GET(如果设置多种(两种)请求方式:method={RequestMethod.GET,RequestMethod.POST}) 22 @RequestMapping(value="/index.html",method=RequestMethod.GET) 23 public ModelAndView index(){ 24 //ModelAndView的用法:三种 25 //第一种用法: 26 /*ModelAndView mav = new ModelAndView(); 27 mav.setViewName("index");//要跳转到的view视图 28 mav.addObject("msg", "Hello,SpringMVC");*///要传递到视图中的值(用法跟request传值相同) 29 30 //第二种用法 31 /*ModelAndView mav = new ModelAndView("index"); 32 mav.addObject("msg", "SpringMVC"); 33 mav.addObject("Hi", "Hi,Jack");*/ 34 35 //第三种用法 36 ModelAndView mav = new ModelAndView("index", "msg","Hello,SpringMVC"); 37 38 return mav; 39 } 40 41 @Autowired 42 public void setUserService(UserService userService) { 43 this.userService = userService; 44 } 45 }
b.在WebRoot中views文件夹中新建一个index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 3 <html> 4 <head> 5 <title>My JSP ‘index.jsp‘ starting page</title> 6 </head> 7 8 <body> 9 <!-- 用于显示我们从AppController.java中传的值 --> 10 ${msg }<br/> 11 ${Hi } 12 13 <!-- 用于显示图片(static是我们在springmvc-servlet.xml配置的不用DispatcherServlet拦截的文件夹);不配置的话,图片无法正常显示 --> 14 <img src="static/img/pretty.png"/> 15 </body> 16 </html>
2>@RequestMapping配置
a.请求的URL:http://xxx/hello/yes.html(两个@RequestMapping配置值组合成一个URL)
1 package com.kaishengit.web; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.servlet.ModelAndView; 6 7 @Controller 8 @RequestMapping("/hello") 9 public class HelloController { 10 @RequestMapping("/yes.html") 11 public ModelAndView hello() { 12 return new ModelAndView("hello","message","Hello,SpringMVC"); 13 } 14 }
b.传递参数
第一种方式:
1 @RequestMapping(value="/hello{id}.html",method=RequestMethod.GET) 2 //@PathVariable指定该变量值是从url中传递过来的(该变量名id和路径中变量id({id})一样) 3 public ModelAndView hello(@PathVariable String id) { 4 System.out.println("id:" + id); 5 return new ModelAndView("hello"); 6 }
第二种方式:
1 @RequestMapping(value="/hello{id}.html",method=RequestMethod.GET) 2 //@PathVariable("id")必须指定值id(该变量名personid和路径中变量名id({id})不一样) 3 public ModelAndView hello(@PathVariable("id") String personid) { 4 System.out.println("id:" + personid); 5 return new ModelAndView("hello"); 6 }
如果传递多个参数,这里用两个举例:
1 @RequestMapping(value="/{name}/hello{id}.html",method=RequestMethod.GET) 2 public ModelAndView hello(@PathVariable String id,@PathVariable String name) { 3 System.out.println("id:" + id + "\tname:" + name); 4 return new ModelAndView("hello"); 5 }
3>Controller return types
第一种:跳转到视图
1 @RequestMapping("/index.html") 2 public String index() { 3 return "index"; //跳转到view视图(index.jsp) 4 }
第二种:ModelAndView
1 @RequestMapping("/index.html") 2 public ModelAndView toIndex() { 3 //设置视图为hello,装载信息 4 ModelAndView mav = new ModelAndView("hello","message","Hello,SpringMVC"); 5 return mav; 6 }
第三种:@ResponseBody修饰,用于显示信息
a.只显示字符串信息
1 @RequestMapping("/show.html") 2 public String showMessage() { 3 return "Hello,SpringMVC"; 4 }
b.显示对象,转换成json
首先需要导入jar包:jackson-core-lgpl-1.9.6.jar和jackson-mapper-lgpl-1.9.6.jar
1 @RequestMapping("/show.html") 2 public @ResponseBody User showMessage(){ 3 User user = new User(); 4 user.setName("meigesir"); 5 user.setAddress("address"); 6 return user; 7 }
4>接受表单值:
a.save.jsp
1 <form action="save" method="post"> 2 name:<input name="name" type="text"/><br/> 3 password:<input name="password" type="password""/><br/> 4 zipcode:<input name="zipcode" type="text"/><br/> 5 <input name="submit" type="submit"/> 6 </form>
b. @RequestMapping(value="/save.html",method=RequestMethod.POST)
1 //其中对象(user)属性会自动装载, 2 public String save(User user,String zipcode){ 3 System.out.println(user.getAddress()); 4 System.out.println("zipCode:" + zipcode); 5 return "redirect:/index.html";//重定向只需要加"redirect:" 6 }
5>使用request、response、session(只需要传进来即可)
1 @RequestMapping("/show.html") 2 public String methodA(HttpServletRequest request, HttpServletResponse response,HttpSession session){ 3 session.setAttribute("session", "Hello,Session!"); 4 return "hello"; 5 }
可以在hello.jsp页面通过${sessionScope.session }取到值
6>文件上传
首先我们导入jar包:commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar
a.配置文件上传解析器:我们已经在springmvc-servlet.xml配置了“配置文件上传解析器”
b.JSP页面
1 <form action="file" method="post" enctype="multipart/form-data"> 2 <input type="text" name="name"/> 3 <input type="file" name="file"/> 4 <input type="submit" value="upload"/> 5 </form>
c.服务器端程序
1 @RequestMapping(value="file",method=RequestMethod.POST) 2 public String file(String name,@RequestParam MultipartFile file){ 3 //上面的@RequestParam代表是从JSP页面传过来的值 4 System.out.println("文件名:" + name); 5 try { 6 file.transferTo(new File("c:/upload/" + file.getOriginalFilename())); 7 } catch (IOException e) { 8 e.printStackTrace(); 9 } 10 return "file"; 11 }
7>Model ModelAndView
1 @RequestMapping("/model.html") 2 public String testModel(Model model){ 3 model.addAttribute("message", "model"); 4 return "hello"; 5 }
ModelAndView前面已经详细介绍过
区别就是:Model的返回类型可以是String,ModelAndView返回类型是ModelAndView