返回介绍

01-04、基于注解的 URL 映射

发布于 2025-03-09 23:21:24 字数 11327 浏览 0 评论 0 收藏 0

项目结构

创建项目 Pcrojet_0104 ,最终结构如下:

源码

applicationContext.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:p="http://www.springframework.org/schema/p"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

</beans>

该配置文件什么都没做。

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:p="http://www.springframework.org/schema/p"
     xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

  <context:component-scan base-package="me.letiantian.controller" />
  <mvc:annotation-driven/>

  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

  <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
      <props>
        <prop key="index">indexController</prop>
      </props>
    </property>
  </bean>

  <bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

  <bean name="indexController"
      class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />

</beans>

<beans> 中增加了属性 xmlns:contextxmlns:mvc ,对应的在 xsi:schemaLocation 增加了:

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

关于 <mvc:annotation-driven/> 的意义,可参考 What's the difference between and in servlet?

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>
      30
    </session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>redirect.jsp</welcome-file>
  </welcome-file-list>
</web-app>

模板文件

index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome to Spring Web MVC project</title>
  </head>

  <body>
    <p>Hello! This is the default welcome page for a Spring Web MVC project.</p>
    <p><i>To display a different welcome page for this project, modify</i>
      <tt>index.jsp</tt> <i>, or create your own welcome page then change
        the redirection in</i> <tt>redirect.jsp</tt> <i>to point to the new
        welcome page and also update the welcome-file setting in</i>
      <tt>web.xml</tt>.</p>
  </body>
</html>

hello/method01.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
  </head>
  <body>
    <h1>Hello Method01</h1>
  </body>
</html>

hello/method04.jsp:

<%@page contentType="text/plain" pageEncoding="UTF-8"%>

name: ${name}

HelloController.java

package me.letiantian.controller;

import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController{

  @RequestMapping(value = "")
  public String index() {
    return "index";
  }

  @RequestMapping(value = "/method01")
  public String method01() {
    return "hello/method01";
  }

  // 仅支持 HTTP POST 方法
  @RequestMapping(value = "/method02", method = {RequestMethod.POST})
  public String method02() {
    return "hello/method01";
  }

  @RequestMapping(value = "/method03")
  public void method03(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/plain;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
      out.println("contextPath: " + request.getContextPath());
      out.println("name: " + request.getParameter("name"));
    } catch (Exception ex) {
      System.out.println(""+ex.getMessage());
    }
  }

  @RequestMapping(value = "/method04/{name}")
  public String method04(@PathVariable String name, Model model) {
    model.addAttribute("name", name);
    return "hello/method04";
  }

  @RequestMapping(value = "/method05/{id}")
  public String method05(@PathVariable int id, Model model) {
    model.addAttribute("name", id);
    return "hello/method04";
  }
}

测试








其他

如何让一个方法映射多个 URL?
很简单,例如 @RequestMapping(value = {"/hello", "/hi"}) 。可参考 Spring MVC: Mapping Multiple URLs to Same Controller

如何自定义错误页面?
Spring MVC : How To Return Custom 404 Error Pages
Spring MVC Exception Handling Example
Exception Handling in Spring MVC

@PathVariable 是绑定数据的其中一种方法,还有绑定 Cookie 中数据,将表单数据绑定到对象中等方法:
Spring MVC Cookie example
Injecting and Binding Objects to Spring MVC Controllers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文