手动配置Spring MVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还可以是 Struts 这样的 Web 框架。下面来带领大家进入愉快的SpringMVC之旅!!

Spring MVC核心架构图:

【环境搭建】

Spring jar包下载官方文档:http://spring.io/,下载后去掉其中的-source.jar和-docs.jar文件

我的资源库中Spring4.1.1下载:http://download.csdn.net/detail/harderxin/8310511

新建web项目工程spring-mvc,为了防止后续项目会有相应的功能添加,所以将Spring核心jar包都导入进去,然后还需要一个日志jar包:commons-logging-.jar,否则项目启动会报错,因为还没有引入持久层,所以就没有hibernate或者mybatis相关jar包,这里只讲述Spring mvc相关环境搭建,项目中的jar包:

【配置web.xml】配置Spring-mvc核心类: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">
  	<welcome-file-list>
    	<welcome-file>index.jsp</welcome-file>
  	</welcome-file-list>

  	<!-- Spring MVC配置 -->
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
	    </init-param>
		-->
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- Spring配置 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:config/applicationContext.xml</param-value>
	</context-param>
</web-app>

【配置<servlet-name>-servlet.xml】:Spring默认可以加载WEB-INF目录下的<servlet-name>-servlet.xml,因为我们上面写的是spring,所以我们在web-info文件目录下新建文件spring-servlet.xml文件,配置视图解析类:InternalResourceViewResolver和注解驱动映射,使用注解方便、简洁,没有那么多的xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		 <property name="prefix" value="/"/>
		 <property name="suffix" value=".jsp"/>
	 </bean>

     <!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
     <mvc:annotation-driven />
     <!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
     <context:component-scan base-package="com.xin" />  

</beans>

【添加applicationContext.xml】在web.xml中我们配置了contextConfigLocation,配置我们的bean所在的xml文件路径,我们可以在其中添加我们所需要配置的bean,也可以添加相应的数据库连接和事务处理等等,方便后续拓展

新建source包,在其中建立config包,在包中新建applicationContext.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
      <!-- 我们可以在其中添加我们所需要配置的bean,也可以添加相应的数据库连接和事务处理等等,方便后续拓展
       -->
</beans>

【编写我们的测试文件】上面我们在spring-servlet.xml配置文件中指定了驱动扫描包为com.xin,所以我们在src目录下新建相应的包,我把编写的测试包放在了包com.xin.test目录下:WelcomeController,Spring中的Controller相当于Struts,做控制转发、页面跳转和参数传递功能,需在其上面添加@Controller注解

@Controller
public class WelcomeController{

	//访问下面方法地址:http://localhost:8080/Spring-mvc/login/wuxin
	@RequestMapping(value = "/login/{user}", method = RequestMethod.GET)
	public ModelAndView myMethod(HttpServletRequest request,HttpServletResponse response,
			@PathVariable("user") String user, ModelMap modelMap) throws Exception {
		modelMap.put("message", user);
		return new ModelAndView("/hello", modelMap);
	}

	//访问下面方法地址:http://localhost:8080/Spring-mvc/hello
	@RequestMapping(value="/hello1",method=RequestMethod.GET)
	public String test1(){
		return "index";
	}
}

【编写我们的视图页面文件】上面我们在spring-servlet.xml配置文件中指定了视图层页面的显示方式,prefix=‘/‘表示前缀无限制,默认在webRoot目录下,如果prefix=‘/jsp/‘则表示视图文件在webroot下的jsp目录下,suffix=".jsp"表示视图文件的类型为jsp文件,我们上面为prefix=‘/‘,suffix=".jsp",表示在webroot下的jsp文件,上面的测试文件中,我们返回了一个ModelAndView("/hello",
modelMap);其中带了hello字符串,或者直接返回字符串return "index";我们则需要在webroot下新建相应的显示页面:hello.jsp和index.jsp,这是spring mvc规定的,spring mvc能够自动找到相应的显示页面,跳转显示:

index.jsp页面:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>

  <body>
    This is my JSP page. <br>
  </body>
</html>

hello.jsp页面:里面用来接收参数的测试页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>

  <body>
    Hello,welcome learn Spring MVC,the message is ${message }
    <%=request.getAttribute("message") %>
    测试user对象:${user.userName }
  </body>
</html>

【测试】将项目部署到Tomcat服务器中,启动没有报错,则说明我们的项目环境搭建成功,输入测试地址:

http://localhost:8080/Spring-mvc/hello:进入index.jsp页面

http://localhost:8080/Spring-mvc/login/jack:进入hello.jsp页面,并显示了相应的传入参数的值jack

表示项目环境搭建和测试成功!!这里要小小的祝贺一下你了....

【项目目录解构】

我的Spring-mvc完整项目资源下载地址:http://download.csdn.net/detail/harderxin/8310529

Spring-mvc其实里面还有很多的知识点,比如源代码分析、国际化、上传下载等等,大家可以详细的研究下,这里把环境搭建好知识起到一个抛砖引玉的作用,希望大家能够多多深入学习,下面给大家来介绍Controller中的两个方法:

//访问下面方法地址:http://localhost:8080/Spring-mvc/hello
	@RequestMapping(value="/hello1",method=RequestMethod.GET)
	public String test1(){
		return "index";
	}

上面我们在方法中采用注解进行驱动加载,RequestMapping表示请求映射,value表示方法请求地址,method表示请求方式,我们可以有GET或者POST,方法中return "index",表示要跳转的页面,其实在里面我们会发现,和我们Controller中的方法名称没关系了,我们取名为test1、test2等等都没关系,请求地址只和RequestMapping中的value有关系

@RequestMapping(value="/hello1",method=RequestMethod.GET):请求地址为http://localhost:8080/Spring-mvc/hello1,为get请求

@RequestMapping(value="/hello1.do",method=RequestMethod.POST):请求地址为http://localhost:8080/Spring-mvc/hello1.do,为post请求

	//访问下面方法地址:http://localhost:8080/Spring-mvc/login/wuxin
	@RequestMapping(value = "/login/{user}", method = RequestMethod.GET)
	public ModelAndView myMethod(HttpServletRequest request,HttpServletResponse response,
			@PathVariable("user") String user1, ModelMap modelMap) throws Exception {
		modelMap.put("message", user1);
		return new ModelAndView("/hello", modelMap);
	}

上面方法中,我们返回了一个ModelAndView,它是Spring-mvc中的一个模型视图结合类,可以在我们要跳转的页面中加入ModelMap参数传递到页面中,上面的RequestMapping中value = "/login/{user}",user在方法中表示一个参数变量,而且是一个字符串类型的,@PathVariable("user") String user1,@PathVariable("user")中的user表示用户传入参数,要和上面value = "/login/{user}"保持一致,而user1表示方法接收的参数,用户传来String类型的参数user,将会传递给方法myMethod方法中的user1,然后程序接收处理

用户访问地址:http://localhost:8080/Spring-mvc/login/wuxin,表示传入参数user为wuxin字符串,然后被user1接收,通过ModelMap存储,传递到hello.jsp页面接收

【获取请求参数和传参】在Struts中我们经常使用HttpServeletRequest进行参数获取和传递request.setAttribute()、request.getParameter();或者使用bean自动注入,那么在Spring-mvc中怎么进行参数请求和传参到页面呢,有下面几种方式

【获取请求参数】

1、 通过@PathVariabl注解获取路径中传递参数

	//以下是获取请求参数
	/**
	 * 通过@PathVariabl注解获取路径中传递参数
	 * 通过ModelMap向页面传值
	 * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello.do/1/xin
	 * @param id
	 * @param userName
	 * @return
	 */
	@RequestMapping(value="/hello2.do/{id}/{userName}")
	public String test2(@PathVariable int id,@PathVariable String userName){
		System.out.println("id="+id+",userName="+userName);
		return "hello";
	}

2、直接用HttpServletRequest获取,在方法中直接加入HttpServletRequest参数即可

	/**
	 * 直接用HttpServletRequest获取
	 * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello3.do?id=2&userName=xin
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/hello3.do")
	public String test3(HttpServletRequest request,HttpServletResponse response){
		int id=Integer.parseInt(request.getParameter("id"));
		String userName=request.getParameter("userName");
		System.out.println("id="+id+",userName="+userName);
		return "hello";
	}

3、用注解@RequestParam绑定请求参数id,userName到变量id,userName

	/**
	 * 用注解@RequestParam绑定请求参数id,userName到变量id,userName
	 * 当请求参数userName不存在时会有异常发生,可以通过设置属性required=false解决,
	 * 例如: @RequestParam(value="userName",required=false),请求参数属性为userName
	 * 		String userName:接收参数属性为userName
	 * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello4.do?id=2&userName=xin
	 * @param id
	 * @param userName
	 * @return
	 */
	@RequestMapping(value="/hello4.do")
	public String test4(@RequestParam("id")int id,@RequestParam(value="userName",required=false)String userName){
		System.out.println("id="+id+",userName="+userName);
		return "hello";
	}

4、我们做项目中,还可能会涉及到表单提交,例如提交User信息,我们新建User实体类:

/**
 * 封装为一个user类
 * @author dell
 *
 */
public class User {

	private int id;
	private String userName;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
}

Controller类接收处理:

	/**
	 * 以下方式可使用于表单提交
	 * 自动注入Bean属性(用@ModelAttribute注解获取POST请求的FORM表单数据)
	 * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello5.do?id=2&userName=xin
	 * 经测试发现,参数中没有@ModelAttribute("user")也能够进行自动注入
	 * @param user
	 * @return
	 */
	@RequestMapping(value="/hello5.do")
	public String test5(@ModelAttribute("user")User user){
		System.out.println("id="+user.getId()+",userName="+user.getUserName());
		return "hello";
	}

提交表单:

  <form action="hello5.do" method="post">
    <input type="text" name="id"/>
	<input type="text" name="userName"/>
	<input type="submit" value="提交"/>
  </form>

还可以使用地址访问:http://localhost:8080/Spring-mvc/hello5.do?id=2&userName=xin

上面的两种方式,我们的Controller都能够接收得到!!是不是感觉Spring-mvc很强大呢

【向页面传递参数】页面显示${message}或者<%=request.getAttribute("message")%>

1、ModelAndView数据会利用HttpServletRequest的Attribute传值到hello.jsp中

	/**
	 * ModelAndView数据会利用HttpServletRequest的Attribute传值到hello.jsp中
	 * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello6.do
	 */
    @RequestMapping(value="/hello6.do")
	public ModelAndView test6(){
		Map<String,Object> data=new HashMap<String,Object>();
		data.put("message", "test6-->xin");
		return new ModelAndView("/hello", data);
	}

2、使用ModelMap作为参数对象传入

    /**
     * 使用ModelMap作为参数对象示例:
	   ModelMap数据会利用HttpServletRequest的Attribute传值到hello.jsp中
	        访问下面方法地址:http://localhost:8080/Spring-mvc/hello7.do
     * @return
     */
    @RequestMapping(value="/hello7.do")
    public String test7(ModelMap map){
    	//以下两种方式都可以
    	//map.addAttribute("message", "test7-->xin");
    	map.put("message", "test7-->xin");
    	return "hello";
    }

3、如果是对象,例如User,使用@ModelAttribute绑定对象,页面hello.jsp中获得对象属性:${user}、${user.userName }

    /**
     * 使用@ModelAttribute示例
	         在Controller方法的参数部分或Bean属性方法上使用
	   @ModelAttribute数据会利用HttpServletRequest的Attribute传值到success.jsp中
	       访问下面方法地址:http://localhost:8080/Spring-mvc/hello8.do
     * @param user
     * @return
     */
    @RequestMapping(value="/hello8.do")
    public String test8(@ModelAttribute("user")User user){
    	user.setUserName("test8-->xin");
    	return "hello";
    }

4、Session存储:可以利用HttpServletReequest的getSession()方法,将HttpServletRequest对象当参数传入,这样request对象中的所有方法我们都可以使用了

    /**
     * Session存储:可以利用HttpServletReequest的getSession()方法
     * 访问下面方法地址:http://localhost:8080/Spring-mvc/hello9.do
     * @return
     */
    @RequestMapping(value="/hello9.do")
    public String test9(HttpServletRequest request){
    	request.setAttribute("message", "test9-->xin");
    	//request.getSession().setAttribute("message", "test9-->xin");
    	return "hello";
    }

【注意:上面的获取请求参数和向页面传递参数我们可以结合起来相互使用,从客户端接收参数,然后保存进行逻辑处理,再将结果返回给用户,这才是我们的基本需求】

    @RequestMapping(value="/hello9.do")
    public String test9(HttpServletRequest request){
    	String userName=request.getParameter("userName");
    	request.setAttribute("message", userName);
    	//request.getSession().setAttribute("message", "test9-->xin");
    	return "hello";
    }

【Spring-mvc中的重定向】Spring MVC 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作:1,使用RedirectView  2,使用redirect:前缀

1、使用RedirectView

    @RequestMapping(value="/hello10.do")
	public ModelAndView test10(){
		RedirectView view=new RedirectView("hello9.do");
		return new ModelAndView(view);
	}

2、使用redirect:前缀

	//工作中常用的方法
    @RequestMapping(value="/hello11.do")
	public String test11(){
		return "redirect:hello9.do";
	}

输入测试地址:http://localhost:8080/spring-mvc/hello10.do,重定向到hello9.do方法中

Spring-mvc还有很多知识点,革命还未成功,我们还要继续深入学习其框架的强大之处......

时间: 2024-08-27 20:20:37

手动配置Spring MVC的相关文章

Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC

在前面的文档中讲解了Spring MVC的特殊beans,以及DispatcherServlet使用的默认实现.在本部分,你会学习两种额外的方式来配置Spring MVC.分别是:MVC Java config 和  MVC XML namespace. 原文: Section 22.2.1, "Special Bean Types In the WebApplicationContext" and Section 22.2.2, "Default DispatcherSer

Spring3.X 配置----Spring MVC 配置

导论: 什么是Spring MVC? Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面. Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架.通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如  JavaServer Pages(JSP)技术.Velocity.

如何在Web项目中配置Spring MVC

要使用Spring MVC需要在Web项目配置文件中web.xml中配置Spring MVC的前端控制器DispatchServlet 1 <servlet> 2 <servlet-name>SpringMVC</servlet-name> 3 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 4 <!-- 默认所对应的配置文件是

通过eclipse配置Spring MVC项目

上一篇刚建立了一个简单的Spring项目,其实Spring MVC是一个和Struts2一样的基于MVC设计模式的web框架,并且继承了MVC的优点,是基于请求驱动的轻量级的web框架,spring mvc可以认为是spring其中的一个web扩展,小巧灵活,但是功能强大,可以直接传入ServletAPI使用起来开发会比较简单顺手,并且通过配置注解的方式,很轻松的对web资源进行管理,提高了开发的速度和应用程序的可维护性 使用spring mvc可以设计出干净的web层和薄薄的web层:目前非常

Spring MVC - 配置Spring MVC

写在前面的话: 现在开始一段新的学习历程:Spring MVC.还是按照原来的三步走学习模式(what.why.how)进行讲解. 1.Spring MVC是什么(what) Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面. Spring MVC通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.Spring MVC框架围绕DispatcherServlet设计. DispatcherServl

Spring 梳理 - 开启并配置 Spring MVC 的方法

传统web.xm中配置两个上下文+两个context对应的xml+两个上下文bean分别手动配置 传统web.xm中配置两个上下文+两个context对应的xml+<mvc:annotation-driven />+ComponentScan 继承AbstractAnnotationConfigDispatcherServletInitializer  或  WebApplicationInitializer 基于javaconfig+@EnableWebMvc+WebMvcConfigure

纯java config配置Spring MVC实例

1.首先创建一个Maven工程,项目结构如下: pom.xml添加Spring和servlet依赖,配置如下 <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.

Spring MVC配置事项

在Intellij IDEA里面配置Spring MVC项目时会碰到刚一新建完毕就大面积报错的情况,主要原因还是JAR包的问题. 解决方案: (1)点击项目结构进入相应的菜单 (2)点击Problems查看所有问题的列表,一般来讲,会有一个 Tomcat7.0.37的maven配置项无效的情况,这个很正常,因为我们使用的是Tomcat8.0.25所以,直接删除它就可以了. (3)找到maven管理文件pom.xml,删除其中的 <dependency> <groupId>javax

spring mvc 配置

之前配置spring mvc 怎么都访不到对应的jsp,后来把prefix里面的jsp改为views,就能访问到了,然后再改回jsp也可以访问到 搞了两天,都崩溃了,不管怎样先把没问题的例子给记录下来 首先是web.xml <servlet> <servlet-name>HighSchoolServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServl