快速搭建springmvc工程

版权声明:本站所提供的文章资讯、软件资源、素材源码等内容均为本作者提供、网友推荐、互联网整理而来(部分报媒/平媒内容转载自网络合作媒体),仅供学习参考,如有侵犯您的版权,请联系我,本作者将在三个工作日内改正。 https://blog.csdn.net/weixin_42323802/article/details/84035610

声明,使用 JDK8,maven3.54 , idea2018.2

步骤

1、pom.xml中配置mvc依赖;
2、配置mvc的入口,即dispatcherServlet;
3、创建Controller ,启动tomcat,进行测试;

配置 pom依赖:

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

web.xml中配置 DispatcherServlet

<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
</servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

配置主配置文件 springmvc.xml ,配置 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"
       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.xsd">
    <context:component-scan base-package="com.baidu"/>
    <!-- 配置视图解析器 ,拦截器InternalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<!--前缀-->
        <property name="prefix" value="/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

目标资源路径: 前缀prefix+controller的返回值+后缀suffix
譬如:下面定义的DemoController的返回值 “index” ,那么目标资源路径就是:/index.jsp
->
部分配置前缀写法:/WEB-INF/jsp/ ,那么jsp的资源是放在webapp/WEB-INF/jsp/目录之下;
定义Controller如下:

controller层:

/**
 * @auther SyntacticSugar
 * @data 2018/11/13 0013下午 7:22
 */
@Controller
public class DemoController {
   @RequestMapping("/index")
    public  String  hello(){
       System.out.println("执行业务逻辑的代码");
       return "index";
    }
}

使用外部tomcat,访问 http://localhost:8080/index
使用maven的tomcat,是以项目名打包的,http://localhost:8080/springmvc_day01/index
控制台打印:执行业务逻辑的代码
页面显示: hello world

尼玛

猜你喜欢

转载自blog.csdn.net/weixin_42323802/article/details/84035610