Spring MVC 基础注解之@RequestMapping、@Controller、(二)

简介: 我现在学的是spring4.2 今天主要学习了Spring MVC注解  引入注解可以减少我们的代码量,优化我们的代码。 @Controller:用于标识是处理器类; @RequestMapping:请求到处理器功能方法的映射规则; 还是以示例来解释说明   1 创建springAnnotation02项目,导入jar包。

我现在学的是spring4.2

今天主要学习了Spring MVC注解 

引入注解可以减少我们的代码量,优化我们的代码。

@Controller:用于标识是处理器类;

@RequestMapping:请求到处理器功能方法的映射规则;

还是以示例来解释说明

 

1 创建springAnnotation02项目,导入jar包。

   这里的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>springmvc01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
<!-- 前端控制器 -->
  <servlet>
    <servlet-name>springAnnotation</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 默认情况下:DispatcherServlet会寻找WEB-INF下,命名规范为[servlet-name]-servlet.xml文件。如:在上例中,它就会找/WEB-INF/spring-servlet.xml 如果需要修改,需要在web.xml中的<servlet>标记中增加 <init-param>。。。 </init-param>:--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/springAnnotation-servlet.xml</param-value> </init-param>

<!-- load-on-startup:表示启动容器时初始化该Servlet; --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springAnnotation</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- 动态设置项目的运行路径 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>spring.root</param-value> </context-param> <!-- 加载LOG4J --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.xml</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!-- spring Web MVC框架提供了org.springframework.web.filter.CharacterEncodingFilter 用于解决POST方式造成的中文乱码问题 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 启动log4j日志管理 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> </web-app>

 

由于要使用SpringMVC注解,所以springAnnotation-servlet.xml文件需要增加springmvc的标记命名空间。
未使用SpringMVC注解时:
  
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xsi:schemaLocation=
5 "http://www.springframework.org/schema/beans
6 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
7 http://www.springframework.org/schema/context
8 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

 修改过后的springAnnotation-servlet.xml。

 

<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"
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/mvc   
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 

 

使用Spring mvc注解时一个完整的springAnnotation-servlet.xml配置如下:

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4 xmlns:context="http://www.springframework.org/schema/context"
 5 xmlns:mvc="http://www.springframework.org/schema/mvc"
 6 xsi:schemaLocation=
 7   "http://www.springframework.org/schema/beans
 8    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 9    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-3.0.xsd
10    http://www.springframework.org/schema/mvc   
11    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
12 
13 <!--开启注解  -->    
14 <mvc:annotation-driven />
15 
16 <!--启用自动扫描  -->
17 <context:component-scan base-package="com.cy.springannotation.controller" />
18     
19 <!--配置视图解析器  -->
20     <!-- ViewResolver 视图解析器 用于将返回的ModelAndView对象进行分离
21     InternalResourceViewResolver:用于支持Servlet、JSP视图解析;
22        viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,classpath中必须包含jstl的相关jar包;
23        prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),
24        比如传进来的逻辑视图名为WEB-INF/jsp/hello,则该该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp”; -->
25 
26 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
27      <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
28      <property name="prefix" value="/"></property> <!-- 我这里的视图直接放在WebRoot下的 -->
29      <property name="suffix" value=".jsp"></property>
30 </bean> 
31 
32 <!-- 为何不配置HandlerMapping?因为基于注解时,会自动使用DefaultAnnotationHandlerMapping -->    
33     
34 </beans>

 

    接下来,我们完成一个最简单的通过控制实现页面间的跳转。

  一个有提交的页面

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>登录页面</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26   <form action="login.do" method="post">
27     <table>
28        <tr>
29            <td>用户名:</td>
30            <td><input type="text" name="username"/></td>
31        </tr>
32        <tr>
33            <td>班级</td>
34            <td><input type="text" name="clazz"/></td>
35        </tr>
36        <tr>
37            <td colspan="2"> <input type="submit" value="提交"/> </td>
38        </tr>
39     </table>
40   </form>
41   </body>
42 </html>

 

控制器

  

 1 package com.cy.springannotation.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 @Controller  // @Controller告知Spring容器这是一个控制器组件
 7 public class LoginController {
 8      @RequestMapping("/login.do")  // @RequestMapping告知该方法是针对/login.do请求的处理方法
 9      public String login(String username){
10          System.out.println(username);
11         return "index";           // 返回的字符串被当做ViewName
12 
13          
14      }
15 }

 

以上的代码就可以进行一个简单的页面跳转。

 

接下来进一步了解@RequestMapping的特性

 1、可以被配置在控制器类名上。
如:
 
 1 @Controller
 2 @RequestMapping("/test")
 3 public class login.doController {
 4     
 5     @RequestMapping("/login.do")
 6     public String login(){
 7         return "index";
 8     }
 9 }
10 
11 //此时代表请求该方法的路径是:/test/login.spring

 

2、三个常用属性:value,params,method
   2-1、value必填属性,代表请求的url,支持模糊配置。(value字可以省略,但是属性值必须填)

@RequestMapping(value=“/users/**”)   匹配“/users/abc/abc”;

@RequestMapping(value="/product?")   匹配“/product1”或“/producta”,但不匹配“/product”或“/productaa”;

@RequestMapping(value="/product*")   匹配“/productabc”或“/product”,但不匹配“/productabc/abc”; 

@RequestMapping(value="/product/*")   匹配“/product/abc”,但不匹配“/productabc”;

 
   2-2、params可选属性,代表对请求参数进行过滤

@RequestMapping(value="/login.do",params="flag")   代表请求中必须要有名为flag的提交项 

@RequestMapping(value="/login.do",params="!flag")  代表请求中不能有名为flag的提交项

@RequestMapping(value="/login.do",params="flag=hello") 代表请求中必须有名为flag的提交项,且值为hello

@RequestMapping(value="/login.do",params="flag!=hello") 代表请求中如果有名为flag的提交项,其值不能为hello

@RequestMapping(value="/login.do",params={"flag1","flag2=hello"})代表请求中必须有名为flag1的提交项,同时必须有名为flag2的提交项,且flag2的值必须为hello

   2-3、method可选属性,代表请求方式
 

@RequestMapping(value="/login.do",method=RequestMethod.POST)

@RequestMapping(value="/login.do",method=RequestMethod.GET)

@RequestMapping(value="/login.do", method= {RequestMethod.POST, RequestMethod.GET}"

接下来是:请求处理方法可接收参数

 

 

 

 

相关文章
|
4月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
808 128
|
4月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
570 0
|
4月前
|
Java 测试技术 API
将 Spring 的 @Embedded 和 @Embeddable 注解与 JPA 结合使用的指南
Spring的@Embedded和@Embeddable注解简化了JPA中复杂对象的管理,允许将对象直接嵌入实体,减少冗余表与连接操作,提升数据库设计效率。本文详解其用法、优势及适用场景。
356 126
|
5月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
3月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
3月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
516 2
|
4月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
625 1
使用Spring的@Retryable注解进行自动重试
|
4月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
399 12
|
4月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
256 0
探索Spring Boot的@Conditional注解的上下文配置