标签简化Spring-MVC配置

新填入@RequestMapping标签

和@org.springframework.stereotype.Controller标签

这样做就是通过标签来简化之前,对HandlerMapping的配置。HandlerMapping的作用也就无非是,接收前端request,再找到指定controller。

package com.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@org.springframework.stereotype.Controller
@RequestMapping("/path01/path02")
public class HelloController implements Controller{

    @Override
    public ModelAndView handleRequest(HttpServletRequest arg0,
            HttpServletResponse arg1) throws Exception {
        System.out.println("处理hello.form请求");
        ModelAndView mv = new ModelAndView("hello");
        return mv;
    }
    
    @RequestMapping("/hello.form")
    public String execute() throws Exception{
        return "hello";
    }
    
}

这样配置后,路径就是 localhost/myspring(project's name)/path01/path02/hello.form

<?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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation=
       "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">

     <mvc:annotation-driven/>
    <context:component-scan base-package="com.controller"/>
    
    <!-- 定义视图解析器viewResolver -->
    <bean id = "viewResolver"
           class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name = "prefix" value = "/WEB-INF/jsp/"/>
           <property name = "suffix" value = ".jsp"/>
    </bean>
    
    <!-- 控制器bean配置 -->
    <bean id = "helloController"
          class = "com.controller.HelloController"/>
</beans>

运行:

原文地址:https://www.cnblogs.com/rixiang/p/5127287.html