springmvc

springmvc的helloworld

1:在web.xml中加入servlet

 1 <!-- 配置 DispatcherServlet -->
 2     <servlet>
 3         <servlet-name>dispatcherServlet</servlet-name>
 4         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 5         <!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
 6         <!-- 
 7             实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.
 8             默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml
 9         -->
10         <!--  
11         <init-param>
12             <param-name>contextConfigLocation</param-name>
13             <param-value>classpath:springmvc.xml</param-value>
14         </init-param>
15         -->
16         <load-on-startup>1</load-on-startup>
17     </servlet>
18 
19     <servlet-mapping>
20         <servlet-name>dispatcherServlet</servlet-name>
21         <url-pattern>/</url-pattern>
22     </servlet-mapping>

用默认的配置文件。用spring来管理

<!-- 设置自动扫描的包 -->
    <context:component-scan base-package="com.springmvc.helloworld"></context:component-scan>
    
    <!-- 设置视图解析器。把返回的值解析为实际的物理视图 -->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

返回值是“success”  prefix 前缀,suffix 后缀。这段代码就是跳转到哪个页面。 /WEB-INF/views/success.jsp页面

主页面:

<body>
    <a href="first/helloworld">第一个springmvc</a>
  </body>

helloworld类:

package com.springmvc.helloworld;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("first")   //@RequestMapping可以请求映射类。相当于WEB应用的根目录。
@Controller
public class HelloWorld {
    @RequestMapping("/helloworld")   //@RequestMapping请求映射方法。映射了类,就是根目录的下一级,没有映射类。这个就是根目录。
    public String helloWorld(){
        System.out.println("测试springmvc的应用");
        return "success";
    }
}

1:知识点:

使用 @RequestMapping 映射请求
Spring MVC 使用 @RequestMapping 注解为控制器指定可 •
以处理哪些 URL 请求
• 在控制器的类定义及方法定义处都可标注
@RequestMapping
类定义处:提供初步的请求映射信息。相对于 WEB 应用的根目– 录
方法处:提供进一步的细分映射信息。相对于类定义处的 URL。若 –
类定义处未标注 @RequestMapping,则方法处标记的 URL 相对于
WEB 应用的根目录
DispatcherServlet 截获请求后,就通过控制器上 •
@RequestMapping 提供的映射信息确定请求所对应的处理
方法。

2:@RequestMapping 里面可以设置value,method,params,heads  分别表示请求 URL、请求方法、请求参数及请求头的映射条件

  下面演示method  设置为POST请求。默认的是get,

1 @RequestMapping(value="/testMethod",method=RequestMethod.POST)
2     public String testMethod(){
3         System.out.println("testMethod");
4         return "success";
5     }
<form action="first/testMethod" method="POST">
      <input type="submit" value="submit">
  </form>
原文地址:https://www.cnblogs.com/bulrush/p/8029393.html