`
阅读更多

 

web.xml 配置:

<servlet>
        <servlet-name>dispatcher</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<init-param>
		<description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description>
		<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>dispatcher</servlet-name>
	<url-pattern>*.htm</url-pattern>
</servlet-mapping>

  

 

这样,所有的.htm的请求,都会被DispatcherServlet处理;

初始化 DispatcherServlet 时,该框架在 web 应用程序WEB-INF 目录中寻找一个名为[servlet-名称]-servlet.xml的文件,并在那里定义相关的Beans,重写在全局中定义的任何Beans,像上面的web.xml中的代码,对应的是dispatcher-servlet.xml;当然也可以使用<init-param>元素,手动指定配置文件的路径;

dispatcher-servlet.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
			http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
			http://www.springframework.org/schema/context 
			http://www.springframework.org/schema/context/spring-context-3.0.xsd
			http://www.springframework.org/schema/aop 
			http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
			http://www.springframework.org/schema/tx 
			http://www.springframework.org/schema/tx/spring-tx-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">
    <!--
        使Spring支持自动检测组件,如注解的Controller
    -->
    <context:component-scan base-package="com.minx.crm.web.controller"/>
   
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

 

 

第一个Controller

 

package com.minx.crm.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

 

 

@Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径(/index.htm),return "index"标记返回视图(index.jsp);

注:如果@RequestMapping注解在类级别上,则表示一相对路径,在方法级别上,则标记访问的路径;

@RequestMapping注解标记的访问路径中获取参数:

Spring MVC 支持RESTful风格的URL参数,如:

 

@Controller
public class IndexController {

    @RequestMapping("/index/{username}")
    public String index(@PathVariable("username") String username) {
        System.out.print(username);
        return "index";
    }
}

 

 

@RequestMapping中定义访问页面的URL模版,使用{}传入页面参数,使用@PathVariable 获取传入参数,即可通过地址:http://localhost:8080/crm/index/tanqimin.htm 访问;

根据不同的Web请求方法,映射到不同的处理方法:

使用登陆页面作示例,定义两个方法分辨对使用GET请求和使用POST请求访问login.htm时的响应。可以使用处理GET请求的方法显示视图,使用POST请求的方法处理业务逻辑

 

@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        return "login";
    }
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login2(HttpServletRequest request) {
            String username = request.getParameter("username").trim();
            System.out.println(username);
        return "login2";
    }
}

 

 

在视图页面,通过地址栏访问login.htm,是通过GET请求访问页面,因此,返回登陆表单视图login.jsp;当在登陆表单中使用POST请求提交数据时,则访问login2方法,处理登陆业务逻辑;

防止重复提交数据,可以使用重定向视图:

 

return "redirect:/login2"

 

 

 

可以传入方法的参数类型:

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
	String username = request.getParameter("username");
	System.out.println(username);
	return null;
}

 

 

 

 

可以传入HttpServletRequestHttpServletResponseHttpSession,值得注意的是,如果第一次访问页面,HttpSession没被创建,可能会出错;

其中,String username = request.getParameter("username");可以转换为传入的参数:

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session,@RequestParam("username") String username) {
	String username = request.getParameter("username");
	System.out.println(username);
	return null;
}

 

 

 

使用@RequestParam 注解获取GET请求或POST请求提交的参数;

获取Cookie的值:使用@CookieValue 

获取PrintWriter

可以直接在Controller的方法中传入PrintWriter对象,就可以在方法中使用:

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, @RequestParam("username") String username) {
	out.println(username);
	return null;
}

 

 

 

 

获取表单中提交的值,并封装到POJO中,传入Controller的方法里:

POJO如下(User.java):

 

public class User{
	private long id;
	private String username;
	private String password;

	…此处省略getter,setter...
}

 

 

 

通过表单提交,直接可以把表单值封装到User对象中:

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, User user) {
	out.println(user.getUsername());
	return null;
}

 

 

 

 

可以把对象,put 入获取的Map对象中,传到对应的视图:

 

 

@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
	model.put("user",user);
	return "view";
}

 

 

 

 

在返回的view.jsp中,就可以根据key来获取user的值(通过EL表达式,${user }即可);

Controller中方法的返回值:

void:多数用于使用PrintWriter输出响应数据;

String 类型:返回该String对应的View Name

任意类型对象:

返回ModelAndView

自定义视图(JstlViewExcelView):

拦截器(Inteceptors):

 

 

public class MyInteceptor implements HandlerInterceptor {
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) 
		throws Exception {
		return false;
	}
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView mav) 
		throws Exception {
	}
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception excptn) 
		throws Exception {
	}
}

 拦截器需要实现HandleInterceptor接口,并实现其三个方法:

 

preHandle:拦截器的前端,执行控制器之前所要处理的方法,通常用于权限控制、日志,其中,Object o表示下一个拦截器;

postHandle:控制器的方法已经执行完毕,转换成视图之前的处理;

afterCompletion:视图已处理完后执行的方法,通常用于释放资源;

MVC的配置文件中,配置拦截器与需要拦截的URL

 

<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/index.htm" />
		<bean class="com.minx.crm.web.interceptor.MyInterceptor" />
	</mvc:interceptor>
</mvc:interceptors>

 

 

 

国际化:

MVC配置文件中,配置国际化属性文件:

 

<bean id="messageSource"
	class="org.springframework.context.support.ResourceBundleMessageSource"
	p:basename="message">
</bean>

 

 

 

那么,Spring就会在项目中搜索相关的国际化属性文件,如:message.propertiesmessage_zh_CN.properties

VIEW中,引入Spring标签:<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>,使用<spring:message code="key" />调用,即可;

如果一种语言,有多个语言文件,可以更改MVC配置文件为:

 

 

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	<property name="basenames">
		<list>
			<value>message01</value>
			<value>message02</value>
			<value>message03</value>
		</list>
	</property>
</bean>

 

 

 

 

ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。至于ApplicationContext.xml这个配置文件部署在哪,如何配置多个xml文件,书上都没怎么详细说明。现在的方法就是查看它的API文档。在ContextLoaderListener中关联了ContextLoader这个类,所以整个加载配置过程由ContextLoader来完成。看看它的API说明

 

第一段说明ContextLoader可以由 ContextLoaderListener和ContextLoaderServlet生成。如果查看ContextLoaderServlet的API,可以看到它也关联了ContextLoader这个类而且它实现了HttpServlet。这个接口

 

    第二段,ContextLoader创建的是 XmlWebApplicationContext这样一个类,它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->

 

BeanFactory这样一来spring中的所有bean都由这个类来创建

 

    第三段,讲如何部署applicationContext的xml文件,如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数:

 

 

view plaincopy to clipboardprint?
<context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
            /WEB-INF/classes/applicationContext-*.xml   
        </param-value>  
    </context-param>  
<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/classes/applicationContext-*.xml
        </param-value>
 </context-param>

 

 

在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并一“,”号分隔。上面的applicationContext-*.xml采用通配符,比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。

 

由此可见applicationContext.xml的文件位置就可以有两种默认实现:

 

第一种:直接将之放到/WEB-INF下,之在web.xml中声明一个listener、

 

第二种:将之放到classpath下,但是此时要在web.xml中加入<context-param>,用它来指明你的applicationContext.xml的位置以供web容器来加载。按照Struts2 整合spring的官方给出的档案,写成:

 

 

view plaincopy to clipboardprint?
<!-- Context Configuration locations for Spring XML files -->  
<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>/WEB-INF/applicationContext-*.xml,classpath*:applicationContext-*.xml</param-value>  
</context-param

 

 

 

分享到:
评论

相关推荐

    Spring MVC基于注解完整实例

    Spring MVC基于注解完整实例,学习的好东西

    Spring MVC 的注解使用实例

    在Spring MVC框架中,注解的使用极大地简化了配置,提高了开发效率。Spring MVC通过注解可以实现控制器、方法映射、模型数据绑定、视图解析等关键功能。本实例将深入探讨Spring MVC中常见的注解及其应用。 1. `@...

    使用Spring 2.5 基于注解驱动的 Spring MVC详解

    使用 Spring 2.5 基于注解驱动的 Spring MVC 详解 本文将介绍 Spring 2.5 新增的 Spring MVC 注解功能,讲述如何使用注解配置替换传统的基于 XML 的 Spring MVC 配置。 Spring MVC 注解驱动 在 Spring 2.5 中,...

    spring3 mvc基于注解的用户登录实例

    经过一段时间对spring mvc的学习,自己做了个简单的用户登录模块。仅仅是登录模块。数据库连接也是简单的使用了JDBC这繁琐的方法。新手可以参考学习。高手就绕道。这个事例只是让新手明白spring mvc 的页面如何跳转...

    基于注解Spring MVC环境搭建

    在“基于注解的Spring MVC环境搭建”中,我们将深入探讨如何利用注解来简化配置,快速建立一个运行中的Web项目。这篇博文(尽管描述为空,但提供了链接)很可能是关于创建一个基本的Spring MVC项目并使用注解来管理...

    Spring 2.5 基于注解驱动的Spring MVC

    Spring 2.5引入了一种基于注解的新方式来驱动Spring MVC框架,使得开发者能够更加简洁、直观地配置和管理控制器。这一变化显著提升了开发效率,减少了XML配置文件的复杂性,同时也使得代码更加模块化。 ### 1. 基于...

    使用 Spring 2_5 基于注解驱动的 Spring MVC

    在本主题中,我们将深入探讨Spring框架的2.5版本引入的一个重要特性——基于注解的Spring MVC配置。Spring MVC是Spring框架的一部分,专门用于构建Web应用程序,它提供了一个模型-视图-控制器(MVC)架构来组织和...

    最全的Spring MVC注解例子,异步请求,错误处理

    在这个“最全的Spring MVC注解例子”中,我们将深入探讨Spring MVC的核心注解,以及如何实现异步请求处理和错误管理。 1. **Spring MVC核心注解** - `@Controller`:标记一个类为处理HTTP请求的控制器。这是Spring...

    Spring MVC非注解测试

    非注解测试在Spring MVC中是指不依赖于Java注解如`@Test`,`@Controller`等进行的测试,而是通过XML配置文件来定义组件和它们之间的关系。这种方式虽然比注解方式繁琐,但有助于理解Spring MVC的工作原理。 首先,...

    spring mvc mybatis 注解版

    **Spring MVC注解版** 在Spring MVC中,注解简化了配置文件,使得开发者可以直接在控制器类和方法上使用注解来声明路由、参数绑定和异常处理等。主要的注解有: 1. `@Controller`:标记一个类为控制器类,处理来自...

    使用 Spring 2.5 基于注解驱动的 Spring MVC.doc

    本文将深入探讨这些注解的使用,帮助开发者理解如何利用注解配置替代传统的基于 XML 的 Spring MVC 配置。 首先,让我们关注 `@Controller` 注解。在 Java 类定义前添加 `@Controller` 注解,标记该类为 Spring MVC...

    Spring MVC 使用注解的示例讲解

    Spring MVC 是一款强大的Java Web开发框架,由Spring Software Foundation维护,它简化了构建基于模型-视图-控制器(MVC)架构的Web应用程序的过程。在本示例中,我们将深入探讨如何利用注解来增强Spring MVC的功能...

    基于注解配置的spring mvc+jpa

    如果使用spring mvc 3.2+和servelt 3+容器(比如tomcat8),那么web.xml和applicationContext.xml都不是必须的,可使用基于注解的配置: 基于配置的集成例子源代码:

    使用 Spring 2.5 基于注解驱动的 Spring MVC

    ### 使用 Spring 2.5 基于注解驱动的 Spring MVC #### 概述与背景 自从Spring 2.0版本对Spring MVC框架进行了重大升级之后,Spring 2.5再次对该框架进行了显著改进,引入了注解驱动的功能。这使得开发人员能够更加...

    Spring3.0MVC注解(附实例)

    本节将深入探讨Spring MVC注解及其在实际应用中的实现方式。 首先,Spring MVC注解允许开发者以声明式的方式配置控制器,避免了传统的XML配置文件。这极大地简化了代码,提高了可读性和维护性。例如,`@...

    spring-mvc注解详情

    Spring MVC 是一个强大的Java Web开发框架,它使用注解来简化MVC(Model-View-Controller)模式的应用程序开发。注解在Spring MVC中扮演着核心角色,它们提供了声明式编程,使得开发者能够以更简洁的方式配置和控制...

    spring mvc + spring + hibernate 全注解整合开发视频教程 12

    在本教程中,我们将深入探讨如何使用Spring MVC、Spring和Hibernate三大框架进行全注解的整合开发。这个视频教程系列的第12部分,将帮助开发者掌握如何在Java Web项目中高效地集成这三个核心框架,实现松耦合、可...

    基于jpa+hibernate+spring+spring mvc注解方式项目

    **基于JPA+Hibernate+Spring+Spring MVC注解方式项目详解** 在现代Java Web开发中,Spring框架扮演了核心角色,而Spring MVC作为其MVC(Model-View-Controller)实现,提供了强大的Web应用程序构建能力。同时,JPA...

Global site tag (gtag.js) - Google Analytics