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


我現在學的是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}"

接下來是:請求處理方法可接收參數

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM