点击页面跳转至FirstSpringMVC并跳转到另一个页面:
Spring mvc 的jar包拷贝到 WEB-INF/lib下
- 文件目录结构:
首先建立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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- 这里配置springmvc的serlvet -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置好了spring的DispatcherServlet之后按照约定,需要在WEB-INF目录下建立[name] - servlet文件夹,这里我们命名为spring,也就是建立spring-serlvet。
对应配置为:
<beans xmlns="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">
<!-- 需要扫描并注册为bean的包 -->
<context:component-scan base-package="micro.action"></context:component-scan>
<!-- 视图的解析 -->
<bean id = "viewModel" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value = "/" />
<property name="suffix" value = ".jsp" />
</bean>
</beans>
welcome.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>欢迎页面</title>
</head>
<body>
<h1>欢迎你</h1>
<a href = "spring">点此请求DispatcherServlet并跳转</a>
</body>
</html>
show.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>跳转后的页面</title>
</head>
<body>
<h1>成功进行了跳转</h1>
</body>
</html>
然后是controller的编写,FirstSpringMVC:
package micro.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
//注册为bean
@Controller
@RequestMapping
public class FirstSpringMVC {
//方法请求路径
@RequestMapping("/spring")
public ModelAndView test()
{
String str = "this is a SpringMVC instance!";
return new ModelAndView("show","str",str);
}
}