springMVC的helloword

springMVC就是一个MVC框架,不在说概念。这个百度一大推。

准备:

1  springMVC所需要的jar。可以在仓库重下载。或者官网。

 2 创建一个动态的web工程。 将准备好的jar放到lib中.

 3  配置springMVC的 DispatcherServlet。 让DispatcherServlet拦截所有的url请求。然后DispatcherServlet解析url找到相应的Controller对于的RequestMapping。执行相应的服务方法

  
  <!-- 配置springMVC的拦截器 DispatcherServlet -->
    <servlet>
      <servlet-name>dispatcherServlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      
     
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
     <servlet-name>dispatcherServlet</servlet-name>
     <url-pattern>/</url-pattern>
    </servlet-mapping>

所有的url请求好比客户端访问服务器中的一个服务。然后把地址交给DispatcherServlet进行处理和转发到相应的服务方法中,并进行相应给客户端。

4  服务器端的发布的服务代码

@Controller
public class Hello {

	@RequestMapping("/sayHello")
	public String say() {
		System.out.println("url:http://localhost:8080/springMVC/sayHello");
		return "show";
	}

	@RequestMapping("/printHello")
	public String print() {
		System.out.println("url:http://localhost:8080/springMVC/printHello");
		return "show";
	}
	
	
	
}

5   在WEB-INF下创建springMVC配置文件:命名规则是 :web.xml中注册的springMVC的servlet的name<servlet-name>dispatcherServlet</servlet-name>  就是dispatcherServlet-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: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.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=""></context:component-scan>

    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>
  

 然后就可以通过tomcat发布我们编写好的 Controller。   启动tomcat之后 。通过浏览器访问 http://localhost:8080/springMVC/sayHello。 就可以看到控制台中的打印信息了

原文地址:https://www.cnblogs.com/sunjiqiang/p/5592314.html