标签:
Spring接触有一段时间了,但SpringMVC一直没接触过。利用周末的时间学了一点。
环境:eclipse、maven、jetty。
1、在pom.xml文件中加入SpringMVC的依赖。
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency>
2、在web.xml中配置dispatcherServlet
<!-- spring-mvc --> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- servlet-mapping --> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3、在WEB-INF目录下创建mvc-dispather-servlet.xml(这里的mvc-dispather要和在web.xml配置的servlet名字一样)
<?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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 使用注解的方式 --> <context:component-scan base-package="itc10.controller"/> <mvc:annotation-driven/> <!-- VIEW --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
这里采用注解的方式配置Controller。
4、创建Controller类
package itc10.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping(value="/namespace") public class HelloController { @RequestMapping(value="/hello", method=RequestMethod.GET) public String toHelloUI () { return "hello"; } }
5、在WEB-INF/jsp目录下创建hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello SpringMVC</title> </head> <body> Hello, itc10. </body> </html>
6、自此SpringMVC的基本框架搭建完毕。
运行jetty,在浏览器的URL中输入http://127.0.0.1:8080/namespace/hello
页面将显示hello.jsp的内容
Hello, itc10.
标签:
原文地址:http://www.cnblogs.com/itc10/p/4696681.html