第一个配置SpringMVC,HelloWorld程序

来源:互联网 发布:秒装软件下载 编辑:程序博客网 时间:2024/05/15 05:37

1、引用SpringMVC包,在pom.xml文件dependencies元素内添加

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

2、配置DispatcherServlet类,在web.xml添加

所有的请求都经过DispatcherServlet转发对应Controller中匹配RequestMapping值的方法处理

<servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>/*</url-pattern>  </servlet-mapping>

url-pattern值:为/ 不会匹配到*.jsp,即:*.jsp不会进入spring的 DispatcherServlet类。为/*会匹配*.jsp,会出现返回jsp视图时进入spring的DispatcherServlet 类,导致找不到对应的RequestMapping报404错


3、在WEB-INF目录下创建springmvc-servlet.xml文件

content:component-scan 用来扫描包下注解来创建bean。DispatcherServlet 在初始化时,Spring MVC 会查找 web 应用 WEB_INF 目录下的[servlet-name]-servlet.xml 并创建在此文件定义的 bean


<?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.java.web"/></beans>

4、创建HelloController
@Controller是标记该类为Controller。没有实际作用。主要让Spring创建该类对象,不需要去beans文件中配置
@RequestMapping 配置处理URL
@ResponseBody 表示方法返回的值,会写入Response的body中
@Controllerpublic class HelloController {    @RequestMapping(value = "/hello")    @ResponseBody    public String hello(){        return "hello world";    }}

5、配置Jetty插件
a、在pom.xml文件中build元素内添加Jetty插件包
<plugins>      <plugin>        <groupId>org.eclipse.jetty</groupId>        <artifactId>jetty-maven-plugin</artifactId>        <version>9.3.14.v20161028</version>        <configuration>          <scanIntervalSeconds>1</scanIntervalSeconds>        </configuration>      </plugin>    </plugins>
b、配置Jetty



Working directory:指定项目目录路径
Command line:指定Jetty命令
c、运行程序


6、访问

0 0
原创粉丝点击