SpringMVC之HelloWorld实例

1.1 Helloworld实例的操作步骤 

 1. 加入jar包

 2. 配置dispatcherServlet

 3. 加入Spring配置文件

 4. 编写请求处理器 并表示为处理器

 5. 编写视图

1.2 具体步骤

1)加入Jar包

2)配置dispatcherServlet的代码(web.xml文件)

 1 <!-- 配置dispatcherServlet -->
 2      <servlet>
 3          <servlet-name>helloworld</servlet-name>
 4          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 5          <load-on-startup>1</load-on-startup>
 6          <!-- 默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml -->
 7      </servlet>
 8      <servlet-mapping>
 9          <servlet-name>helloworld</servlet-name>
10          <url-pattern>/</url-pattern>
11      
12      </servlet-mapping>

3)加入Spring配置文件(<servlet-name>-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="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
 8         http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 9         
10     <!-- 配置自定扫描的包 -->
11     <context:component-scan base-package="com.tk.handlers"></context:component-scan>
12     <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
13     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
14         <property name="prefix" value="/WEB-INF/views/"></property>
15         <property name="suffix" value=".jsp"></property>
16     </bean>
17 </beans>

4)编写请求处理器(Java类)并标识为处理器

1 @Controller
2 public class Helloworld {
3    
4     @RequestMapping("/helloworld")
5     public String helloworld(){
6         System.out.println("helloworld @RequestMapping 只有方法映射...");
7         return "success";
8     }
9 }

5)编写视图文件

1 <a href="helloworld">helloworld1-@RequestMapping【只有方法映射】</a></br>

1.3 注意事项

1)实际上也可以不通过 contextConfigLocation 来配置 SpringMVC 的配置文件, 而使用默认的.

2)默认的配置文件为: /WEB-INF/<servlet-name>-servlet.xml

3)使用contextConfigLocation 来配置 SpringMVC 的配置文件

1 <init-param>
2             <param-name>contextConfigLocation</param-name>
3             <param-value>classpath:springmvc.xml</param-value>
4 </init-param>-->
原文地址:https://www.cnblogs.com/quinntian/p/6744987.html