以注解的形式来实现一个springmvc的简单范例

2018-12-02 21:35:41  卢浮宫  版权声明:本文为站长原创文章,转载请写明出处


一、创建web工程,导入jar包


二、配置springmvc的config文件    

    <?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:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 配置注解的支持 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 启用自动扫描 ,里面的base-package必须是对应你的控制类的包名-->
<context:component-scan base-package="com.lfg.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置路径 也就是你的页面的放置路径-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 配置是类型的后缀,比如你的页面是jsp页面,该出的配置就是.jsp -->
<property name="suffix" value=".jsp"></property>
</bean>

</beans>



三、配置web.xml文件


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javae e http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!-- 配置dispaly-name 其属性值必须是你的工程名 -->
<display-name>springmvctest</display-name>

<!-- 配置servlet -->
<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:com/lfg/config/springmvc-servlet.xml</param-value>
</init-param>
<!-- load-on-startup 必须在init的后面 -->
<load-on-startup>1</load-on-startup>
</servlet>

<!-- 配置servlet的映射文件 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<!-- 欢迎界面 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>



四、创建控制器类 


package com.lfg.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller //通过@controller注解,标明sayHello这个类是一个控制器
public class sayHello {
/*
* 使用@requestMapping 注解来定义页面加载的内容,该处为sayHello,请求方式为get
*/
@RequestMapping(value="/sayhello",method=RequestMethod.GET)
public String sHello(){
//定义返回值hello,该值通过视图解析器,解析为WEB-INF/pages/hello.jsp
return "hello";
}
}





更多精彩请关注guangmuhua.com


最新评论: