SpringMVC3框架开发


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

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<!-- 配置DispatcherServlet -->
	<servlet>
		<!-- 约定:此名称springmvc必须与配置文件springmvc-servlet.xml保持一致(这里都是springmvc) -->
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置:服务器启动时自动加载此Servlet -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 三、在WEB-INF中新建springmvc-servlet.xml(其中的springmvc是上面的servlet-name节点的值)

<?xml version="1.0" encoding="UTF-8"?>
<!-- 注意下面不要忘记导入mvc、context的schema -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<!-- 开启自动扫描包 -->
	<context:component-scan base-package="com.kaishengit.web"/>
	<!-- 开启注解驱动 -->
	<mvc:annotation-driven/>
	<!-- 在地址栏访问 "网站根路径 + /404",所跳转到的页面404.jsp -->
	<mvc:view-controller path="/404" view-name="404"/>
	<mvc:view-controller path="/500" view-name="500"/>
	<!--
		 配置不用DispatcherServlet拦截的路径(例如:图片、CSS样式、js文件...):
		路径可以自己设置,这里面我用static(WebRoot中的文件夹);
		其中的"**"代表路径及其子路径	
	 -->
	<mvc:resources location="/static/" mapping="/static/**"/>
	
	
	
	
	<!-- 配置视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<!-- 
			上面的配置是固定的,下面两个配置意思是:如果你要访问index视图,
			它会自动 prefix(前缀) + index + suffix(后缀),
			生成/WEB-INF/views/index.jsp 
		-->
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<!-- 配置文件上传解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 上面配置是固定的,下面是配置上传文件的最大大小 -->
		<property name="maxUploadSize" value="1000000"/>
	</bean>
	
	
</beans>

 四、前面配置完全,现在我们正式开始开发

1>新建一个Controller类

a.我们新建一个Controller类(类似Struts2中的Action类):AppController.java

package com.kaishengit.web;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.kaishengit.service.UserService;


@Controller//1.标记一个Controller
public class AppController {
	
	/**
	 * Service...:和以前注入方式一样
	 */
	private UserService userService;
	
	//2.标记一个请求路径(URL:http://xxx/index.html),请求方式设置为GET(如果设置多种(两种)请求方式:method={RequestMethod.GET,RequestMethod.POST})
	@RequestMapping(value="/index.html",method=RequestMethod.GET)
	public ModelAndView index(){
		//ModelAndView的用法:三种
		//第一种用法:
		/*ModelAndView mav = new ModelAndView();
		mav.setViewName("index");//要跳转到的view视图
		mav.addObject("msg", "Hello,SpringMVC");*///要传递到视图中的值(用法跟request传值相同)
		
		//第二种用法
		/*ModelAndView mav = new ModelAndView("index");
		mav.addObject("msg", "SpringMVC");
		mav.addObject("Hi", "Hi,Jack");*/
		
		//第三种用法
		ModelAndView mav = new ModelAndView("index", "msg","Hello,SpringMVC");
		
		return mav;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
 

b.在WebRoot中views文件夹中新建一个index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
  	<!-- 用于显示我们从AppController.java中传的值 -->
  	${msg }<br/>
  	${Hi }
  	
  	<!-- 用于显示图片(static是我们在springmvc-servlet.xml配置的不用DispatcherServlet拦截的文件夹);不配置的话,图片无法正常显示 -->
  	<img src="static/img/pretty.png"/>
  </body>
</html>
 

2>@RequestMapping配置

a.请求的URL:http://xxx/hello/yes.html(两个@RequestMapping配置值组合成一个URL)

package com.kaishengit.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/hello")
public class HelloController {
	@RequestMapping("/yes.html")
	public ModelAndView hello() {
		return new ModelAndView("hello","message","Hello,SpringMVC");
	}
}

b.传递参数

第一种方式:

@RequestMapping(value="/hello{id}.html",method=RequestMethod.GET)
	//@PathVariable指定该变量值是从url中传递过来的(该变量名id和路径中变量id({id})一样)
	public ModelAndView hello(@PathVariable String id) {
		System.out.println("id:" + id);
		return new ModelAndView("hello");
	}

 第二种方式:

@RequestMapping(value="/hello{id}.html",method=RequestMethod.GET)
	//@PathVariable("id")必须指定值id(该变量名personid和路径中变量名id({id})不一样)
	public ModelAndView hello(@PathVariable("id") String personid) {
		System.out.println("id:" + personid);
		return new ModelAndView("hello");
	}

 如果传递多个参数,这里用两个举例:

	@RequestMapping(value="/{name}/hello{id}.html",method=RequestMethod.GET)
	public ModelAndView hello(@PathVariable String id,@PathVariable String name) {
		System.out.println("id:" + id + "\tname:" + name);
		return new ModelAndView("hello");
	}
 

 3>Controller return types

第一种:跳转到视图

	@RequestMapping("/index.html") 
	public String index() { 
		return "index"; //跳转到view视图(index.jsp)
	}

 第二种:ModelAndView

@RequestMapping("/index.html")
	public ModelAndView toIndex() {
		//设置视图为hello,装载信息
		ModelAndView mav = new ModelAndView("hello","message","Hello,SpringMVC"); 
		return mav;
	}

 第三种:@ResponseBody修饰,用于显示信息

a.只显示字符串信息

@RequestMapping("/show.html") 
	public String showMessage() { 
		return "Hello,SpringMVC"; 
	}

 b.显示对象,转换成json

首先需要导入jar包:jackson-core-lgpl-1.9.6.jar和jackson-mapper-lgpl-1.9.6.jar

@RequestMapping("/show.html")
	public @ResponseBody User showMessage(){
		User user = new User();
		user.setName("meigesir");
		user.setAddress("address");
		return user;
	}

4>接受表单值:

a.save.jsp

<form action="save" method="post">
    	name:<input name="name" type="text"/><br/>
    	password:<input name="password" type="password""/><br/>
    	zipcode:<input name="zipcode" type="text"/><br/>
    	<input name="submit" type="submit"/>
    </form>

  b. @RequestMapping(value="/save.html",method=RequestMethod.POST)

	//其中对象(user)属性会自动装载,
	public String save(User user,String zipcode){
		System.out.println(user.getAddress());
		System.out.println("zipCode:" + zipcode);
		return "redirect:/index.html";//重定向只需要加"redirect:"
	}

 5>使用request、response、session(只需要传进来即可)

	@RequestMapping("/show.html") 
	public String methodA(HttpServletRequest request, HttpServletResponse response,HttpSession session){
		session.setAttribute("session", "Hello,Session!");
		return "hello"; 
	}

 可以在hello.jsp页面通过${sessionScope.session }取到值

6>文件上传

首先我们导入jar包:commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar

a.配置文件上传解析器:我们已经在springmvc-servlet.xml配置了“配置文件上传解析器”

b.JSP页面

<form action="file" method="post" enctype="multipart/form-data">
    	<input type="text" name="name"/>
		<input type="file" name="file"/>
		<input type="submit" value="upload"/>
    </form>

 c.服务器端程序

	@RequestMapping(value="file",method=RequestMethod.POST)
	public String file(String name,@RequestParam MultipartFile file){
		//上面的@RequestParam代表是从JSP页面传过来的值
		System.out.println("文件名:" + name);
		try {
			file.transferTo(new File("c:/upload/" + file.getOriginalFilename()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "file";
	}

 7>Model ModelAndView

	@RequestMapping("/model.html") 
	public String testModel(Model model){ 
		model.addAttribute("message", "model"); 
		return "hello"; 
	}

ModelAndView前面已经详细介绍过

区别就是:Model的返回类型可以是String,ModelAndView返回类型是ModelAndView 

猜你喜欢

转载自meigesir.iteye.com/blog/1515034
今日推荐