springMVC的环境搭建其实和Struts2差不多,也就是配置一些东西,非常的方便。具体的就分为几部分:
1)引用相关jar包
2)配置配置文件
3)编写controller
4)返回视图页面
具体的实施过程还是要来看下面的。
1、引入相关jar包
2、配置配置文件
1) 配置web.xml文件
1) 配置web.xml文件
<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*:config/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>
1
</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
2)、配置spring-servlet.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<
bean name="/test1/helloworld" class="com.tgb.web.controller.HelloWorldController"
>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3、编写controller
public class HelloWorldController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println("hello tgb!");
String dataResult="hello world!";
Map<String ,Object> map=new HashMap<String,Object>();
map.put("k1", "V1");
map.put("k2", "V2");
map.put("k3", "V3");
return new ModelAndView("/welcome","map",map);
}
}
4、返回视图
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
hello tgb!<br>
<c:forEach items="${map }" var="m">
${m.key }-->${m.value }<br>
</c:forEach>
</body>
</html>