Spring MVC HelloWorld入门例子
本例子为你讲解在spring3中如何使用基于注解的mvc框架.
例子中使用到的工具:
MyEclipse 9.1
jdk 1.6
1.添加Jar包引用
由于使用了Maven管理项目,所以,第一步就是添加引用.(没有使用Maven怎么办?那你直接下载Spring3的压缩包,添加相应的Jar文件就可以了。)
Java代码
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
2.编写 Controller 和 Mapping
我们采用注解的方式配置,如果想使用XML的方式,可以查看文档,都是一样的配制方法.
Java代码
packagecom.vito.action;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/welcome")
publicclassHelloWorldController{
@RequestMapping(value="/hello",method=RequestMethod.GET)
publicStringprintWelcome(ModelMapmodel){
model.addAttribute("message","Spring3MVCHelloWorld");
return"hello";
}
}
3.JSP视图
Java代码
<html>
<body>
<h2>Message:${message}</h2>
</body>
</html>
4.Spring配置文件
Java代码
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<context:component-scanbase-package="com.vito.action"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="prefix">
<!--这个配置是配置JSP页面的位置,按照你自己的配置来配-->
<value>/WEB-INF/pages/</value>
</property>
<propertyname="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
5.web.xml
Java代码
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"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">
<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:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
6.成果
访问:×××/technology
就可以得到这样的画面了:
本站所有代码来源请查看:×××/technology
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。