美文网首页
Web项目开发系列 之二:集成spring mvc框架,添加控制

Web项目开发系列 之二:集成spring mvc框架,添加控制

作者: with_prototype | 来源:发表于2017-07-17 22:29 被阅读0次

一、 引入maven依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>

二、 添加spring配置文件


image.png

在配置文件中引入spring-beans,spring-context,spring-mvc
并添加扫描路径

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

    <!--扫描路径-->
    <context:component-scan base-package="with_prototype"></context:component-scan>

</beans>

三、 修改web.xml,随容器启动DispacherServlet

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:with_prototype/config/spring-config.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

注意修改文件头的版本,这里取2.5的

四、写一个控制器,返回Hello

image.png

注意,我这里添加的控制器是在扫描路径下的,否则请求将无法处理

package with_prototype.ctrl;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by chenzhaolei on 2017/7/17.
 */
@Controller
public class GreetingCtrl {
    @RequestMapping(value = "/sayhello")
    public @ResponseBody String sayHello(@RequestParam String user){
        return "Hello "+user;
    }
}

五、启动tomcat,测试

image.png

相关文章

网友评论

      本文标题:Web项目开发系列 之二:集成spring mvc框架,添加控制

      本文链接:https://www.haomeiwen.com/subject/gxoqkxtx.html