【问题标题】:Spring MVC : How url mapping was done before use of @RequestMapping() in spring framework?Spring MVC:在 Spring 框架中使用 @RequestMapping() 之前如何完成 url 映射?
【发布时间】:2020-04-21 05:10:42
【问题描述】:

我现在正在为新项目学习 Spring MVC。在那里我遇到了@RequestMapping 注释,说明如何将请求与 URL 映射。

我想了解一下,以前如何在不使用此注解的情况下映射请求和 URL? 在 XML 文件中是如何配置的?

控制器代码:

@Controller
public class HelloController {

    @RequestMapping(value = "/greeting")
    public String sayHello(Model model){
        model.addAttribute("greeting","Helloworld");
        return "hello";
    }
}

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

        <bean name="/greeting.html" class="com.pj.controller.HelloController"/>

        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
</beans>

web.xml

<servlet>
  <servlet-name>fitTrackerServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/servlet-config.xml</param-value>
  </init-param>
</servlet>

<servlet-mapping>
  <servlet-name>fitTrackerServlet</servlet-name>
  <url-pattern>*.html</url-pattern>
</servlet-mapping>

【问题讨论】:

  • 你为什么要研究这种东西?不使用通过 XML 声明映射,而且似乎也已从 Spring 的参考手册中删除,但无论如何,如果我们想看看,你可以在这里查看:stackoverflow.com/questions/4481373/requestmapping-in-xml
  • 如果您有兴趣,网上有很多资源告诉您如何使用 xml 映射弹簧控制器:baeldung.com/spring-xml-vs-java-config。但是,是的,注释定义的控制器是要走的路。
  • @Aris_Kortex 在我正在使用的项目中,他们没有使用注释。项目非常古老,他们使用的是旧技术,所以我必须了解它。我知道现在使用注释是一种很好的做法。
  • @SM,这是什么项目?它有多古老?我建议你们投资于更新所有内容。

标签: java spring spring-mvc request-mapping


【解决方案1】:

看看这个:Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

现在,

  1. RequestMapping 用于映射控制器的端点。
  2. 对于 http 动词,有特定的映射注释,如
    • @Getmapping,
    • @PostMapping,
    • @PutMapping...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多