spring mvc配置(xml配置详解)

本文详细介绍SpringMVC框架的基本配置方法及核心组件作用,并通过示例代码展示如何实现请求处理与视图返回。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Framework(J2EE框架),Spring(Spring框架)下载

1、Spring Framework(J2EE框架) 3.2.4

2、Spring(Spring框架) 4.0.0.M2


首先配置web.xml

	<pre style="margin-top: 0px; margin-bottom: 0px; padding: 0px; white-space: pre-wrap; word-wrap: break-word; line-height: 18px; font-family: 'Courier New' !important;"><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 0); line-height: 1.5 !important;">       <!--</span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 0); line-height: 1.5 !important;"> Spring配置 </span><span style="margin: 0px; padding: 0px; color: rgb(0, 128, 0); line-height: 1.5 !important;">--></span>
    <span style="white-space:pre">	</span><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:beans.xml</param-value>
     </context-param>

 
<span style="white-space:pre">	</span><servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param><pre name="code" class="html"><span style="white-space:pre">			</span><!-- <description>加载/WEB-INF/spring-mvc/目录下的所有XML作为Spring MVC的配置文件</description> -->
<param-name>contextConfigLocation</param-name><param-value>classpath:SpringMVC.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springMVC</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>
 
这样所有的.do请求都会被DispatcherServlet处理; 

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

springMVC-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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-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/context 
       	http://www.springframework.org/schema/context/spring-context-3.0.xsd
       	http://www.springframework.org/schema/mvc
    	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<span style="white-space:pre">	</span><pre name="code" class="html"><span style="white-space:pre">	</span><span style="color:#009900;"><!-- 启用SpringMVC注解--></span>
<context:annotation-config />

     <!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="com.mobile.*.controller"></context:component-scan>
       <!-- 完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
       <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/"/></beans>
 DispatcherServlet会利用一些特殊的bean来处理request请求和生成相应的视图返回。 

关于视图的返回,Controller只负责传回来一个值,然后到底返回的是什么视图,由视图解析器控制的,在jsp中常用的视图解析器是InternalResourceViewResolver,它会要求一个前缀和一个后缀

在上面代码中的视图解析器中如果返回的是login.html,那么通过视频解释器解析之后变为/WEB-INF/view/login.html。会在相应路径下找到login.html 页面

接下来是控制器Controller

一个类使用了@Controller进行标记的都是Controller

<pre class="reply-text mb10" style="color: rgb(57, 57, 57); font-size: 14px; line-height: 25.2000007629395px; background-color: rgb(255, 255, 255);">@controller 控制器(注入服务)
package controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import entity.User;


@Controller  
//类似Struts的Action
<span style="color:#999999;"><span style="background-color: rgb(255, 255, 255);"></span></span><pre name="code" class="html" style="line-height: 21px;"><span style="color:#393939;background-color: rgb(250, 247, 239);">@RequestMapping("/")</span>

 
public class TestController {    @RequestMapping("test/login.do")  
// 请求url地址映射,类似Struts的action-mapping    public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {        // @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)        // @RequestParam可简写为:@RequestParam("username")        if (!"admin".equals(username) || !"admin".equals(password)) {            return "loginError"; // 跳转页面路径(默认为转发),该路径不需要包含spring-servlet配置文件中配置的前缀和后缀        }        return "loginSuccess";    }    @RequestMapping("/test/login2.do")    public ModelAndView testLogin2(String username, String password, int age){        // request和response不必非要出现在方法中,如果用不上的话可以去掉        // 参数的名称是与页面控件的name相匹配,参数类型会自动被转换                if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {            return new ModelAndView("loginError"); // 手动实例化ModelAndView完成跳转页面(转发),效果等同于上面的方法返回字符串        }        return new ModelAndView(new RedirectView("../index.jsp"));  // 采用重定向方式跳转页面        // 重定向还有一种简单写法        // return new ModelAndView("redirect:../index.jsp");    }    @RequestMapping("/test/login3.do")    public ModelAndView testLogin3(User user) {        // 同样支持参数为表单对象,类似于Struts的ActionForm,User不需要任何配置,直接写即可        String username = user.getUsername();        String password = user.getPassword();        int age = user.getAge();                if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {            return new ModelAndView("loginError");        }        return new ModelAndView("loginSuccess");    }    @Resource(name = "loginService")  // 获取applicationContext.xml中bean的id为loginService的,并注入    private LoginService loginService;  //等价于spring传统注入方式写get和set方法,这样的好处是简洁工整,省去了不必要得代码    @RequestMapping("/test/login4.do")    public String testLogin4(User user) {        if (loginService.login(user) == false) {            return "loginError";        }        return "loginSuccess";    }} 
 

@Controller注解标识一个控制器,@RequestMapping注解标记一个访问的路径,return"index.html"标记返回View视图页面。

注:如果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/admin.do访问


参考链接:1、SpringMVC配置

      2、SpringMVC 配置 详解

              3、spring @component的作用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值