1.在web.xml配置DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>springmvc-1</display-name>
<!-- 配置dispatcherServlet -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数 :配饰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>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.创建spring配置文件: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.hcx.springmvc.*"></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>
3.新建处理类 hello.java
java类需要标注Controller
使用RequestMapping来表示对应url,前台点击该url进入控制器
而方法的返回值将会作为寻找返回视图的依据,格式为 prefix+返回值+suffix。
该类的返回值结合springmvc.xml中的配置为 /WEB-INF/views/success.jsp
@Controller
public class HelloWorld {
/**
* 1.使用 RequestMapping 注解来映射请求的URL
*
* 2.返回值會通過視圖解析器 解析 返回实际的视图
* prefix+teturnValue+后缀 这样的方式,找到实际的视图,然后做转发操作
* @return
*/
@RequestMapping("/helloworld")
public String hello(){
System.out.println("hello world");
return "success";
}
}
4.两个页面,初始index.jsp和success.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="helloworld">Hello World</a>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Success page</h3>
</body>
</html>
至此,完成了一个简单的HelloWorld的程序。