本文主要是介绍SpringMVC的第一个案例 Helloword 步骤,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
第一步:web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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">
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置DispatcherServlet的一个初始化参数:配置SpringMVC 配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
第二步:springmvc.xml配置
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.haixing.springmvc.handlers"></context:component-scan>
<!-- 配置试图解析器,如何把handler 方法返回值为实际的物理视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
第三步:核心类 HelloSpringMvcWord
@Controller
public class HelloSpringMvcWord {
private static final String SUCCESS = "success"; //定义常量
/**
* 1.使用@RequestMapping 注解来映射请求的url
* 2.返回值会通过视图解析为实际的物理视图 ,对于InternalResourceViewResolver 视图解析,会做如下解析
* 通过prefix + returnVal + 后缀得到实际的物理视图,然后做转发操作
* /WEB-INF/views/success.jsp
* @return
*/
@RequestMapping("/helloword")
public String hello(){
System.out.println("Spring MVC word;you are ok...");
return SUCCESS;
}
}
这篇关于SpringMVC的第一个案例 Helloword 步骤的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!