今天学习了SpringMVC框架的配置和测试,所以记录以便查找。
开发工具:Eclipse,Tomcat
1.创建一个web项目,然后导入jar包
所需要的jar包(除了第一个,其它的都是spring框架的jar包):
- commons-logging-1.1.3.jar(Struts2框架中的jar包)
- spring-aop-4.3.7.RELEASE.jar
- spring-beans-4.3.7.RELEASE.jar
- spring-context-4.3.7.RELEASE.jar
- spring-core-4.3.7.RELEASE.jar
- spring-expression-4.3.7.RELEASE.jar
- spring-web-4.3.7.RELEASE.jar
- spring-webmvc-4.3.7.RELEASE.jar
- jstl-1.2.jar (加入该jar包是为了后面遍历集合更方便,如果不需要可以不加或删掉)
2.配置web.xml文件
进行web.xml配置,可参考spring官方网文档的 22.2 The 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>SpringMVCProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置核心 servlet-->
<servlet>
<servlet-name>springMVC</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>
<!-- 在项目启动时就加载springMVC的配置 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置servlet的访问路径 -->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.创建Controller
3.1 实现Controller接口
3.1.1 在src目录下新建一个包,包下新建一个类,该类实现Controller接口
package com.springmvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class ContorllerTest implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("username", "zhangsan");
//执行完后,要返回一个页面
mav.setViewName("/index.jsp");
return mav;
}
}
3.1.2 创建index.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>Insert title here</title>
</head>
<body>
<h1>我的第一个SpringMVC项目</h1>
<h2>${username }</h2>
<h2>${age }</h2>
</body>
</html>
3.1.3 配置SpringMVC配置文件,新建一个SpringMVC.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven/>
</beans>
我们当然不能直接用官方的,需要改一下("/ContorllerTest " 实现Controller接口 配置Controller的访问路径,为了兼容低版本,这里最好使用name):
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 打开注解 -->
<context:annotation-config />
<!-- 扫描注解的包 ,会扫描子包 -->
<context:component-scan base-package="com.springmvc"></context:component-scan>
<!-- <mvc:annotation-driven/>-->
<bean name="/ContorllerTest" class="com.springmvc.controller.ContorllerTest"></bean>
</beans>
3.1.4 打开浏览器,在地址栏输入“http://localhost:8080/SpringMVCProject/ContorllerTest”:
3.2 实现HttpRequestHandler接口
3.2.1 新建一个类,实现HttpRequestHandler接口:
package com.springmvc.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.HttpRequestHandler;
public class HelloController implements HttpRequestHandler {
@Override
public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("HelloController..");
}
}
3.2.2 修改SpringMVC配置文件
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 打开注解 -->
<context:annotation-config />
<!-- 扫描注解的包 ,会扫描子包 -->
<context:component-scan base-package="com.springmvc"></context:component-scan>
<!-- <mvc:annotation-driven/>-->
<!-- 实现Controller接口 配置Controller的访问路径,为了兼容低版本,这里最好使用name -->
<bean name="/ContorllerTest" class="com.springmvc.controller.ContorllerTest"></bean>
<!-- 实现HttpRequestHandler接口 -->
<bean name="/Hello" class="com.springmvc.controller.HelloController"></bean>
</beans>
3.2.3 打开浏览器,地址栏输入“http://localhost:8080/SpringMVCProject/Hello”
你会发现在Eclipse控制台打印出了“HelloController..”
3.3 自己定义Controller,使用注解的方式
3.3.1 新建MyThirdController类,类中定义几个方法
package com.springmvc.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* 第三种Contller的实现方式,使用注解
* @author oracleOAEC11
*
*/
@Controller
public class MyThirdController {
/**
* 获取所有的用户
* 获取所有的用户 value = "/getUsers" 访问路径,要使用value method=RequestMethod.GET
* 可以指定get或post请求
* @return
*/
@RequestMapping(value="/getUsers",method=RequestMethod.GET)
public ModelAndView getUsers() {
ModelAndView mav = new ModelAndView();
// 添加对象,相当于 request.setAttribute
mav.addObject("username", "lisi");
//执行完后,要返回一个页面
mav.setViewName("/index.jsp");
return mav;
}
@RequestMapping(value = "/getModelAndView")
public ModelAndView getModelAndView() {
// new 一个ModelAndView
ModelAndView mav = new ModelAndView();
mav.addObject("username", "wangwu");
Map<String,Object> map = new HashMap<String,Object>();
map.put("pwd", "123456");
map.put("age", 20);
//添加多个属性使用Map
mav.addAllObjects(map);
// 添加list数据类型
List<String> list = new ArrayList<String>();
list.add("Alice");
list.add("tom");
list.add("jack");
mav.addObject("list",list);
// 执行完成以后,要返回的一个页面 转发
mav.setViewName("redirect:/index.jsp");
return mav;
}
/**
* 返回string
*
* @return
*/
@RequestMapping(value = "/returnString")
public String returnString() {
System.out.println("调用了returnString方法");
return "index.jsp";
}
@RequestMapping(value = "/viewResolverTest")
public ModelAndView viewResolverTest() {
// new 一个ModelAndView
ModelAndView mav = new ModelAndView();
// 添加对象,相当于 request.setAttribute
mav.addObject("username", "lisi");
Map<String, Object> map = new HashMap<String, Object>();
map.put("pwd", "123456");
map.put("age", 20);
// 添加多个属性,使用map
mav.addAllObjects(map);
// 添加list数据类型
List<String> list = new ArrayList<String>();
list.add("Alice");
list.add("Tom");
list.add("Jack");
mav.addObject("list", list);
// 执行完成以后,要返回的一个页面 转发 使用视图解析器,
// 转发的路径为:prefix + projectlist + suffix
// 如果要跳转的页面不在视图解析器的范围内,就要使用全路径跳转,
// 并且指定跳转方式 forward或redirect 如:mav.setViewName("forward:/index.jsp");
mav.setViewName("projectList");
return mav;
}
}
打开浏览器,在地址栏输入“http://localhost:8080/SpringMVCProject/returnString”
4.配置视图解析器
4.1在WebContent目录下新建projectManager文件夹,文件夹中新建两个jsp页面:projectList.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>Document</title>
</head>
<body>
<h1>用户列表</h1>
${projectName }<br>
${projectCode }<br>
${projectType }<br>
</body>
</html>
4.2 修改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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 打开注解 -->
<context:annotation-config />
<!-- 扫描注解的包 ,会扫描子包 -->
<context:component-scan base-package="com.springmvc"></context:component-scan>
<!-- <mvc:annotation-driven/>-->
<!-- 实现Controller接口 配置Controller的访问路径,为了兼容低版本,这里最好使用name -->
<bean name="/ContorllerTest" class="com.springmvc.controller.ContorllerTest"></bean>
<!-- 实现HttpRequestHandler接口 -->
<bean name="/Hello" class="com.springmvc.controller.HelloController"></bean>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!-- 前缀 -->
<property name="prefix" value="/projectManager/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
4.3 修改MyThirdController类中方法返回的页面
package com.springmvc.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* 第三种Contller的实现方式,使用注解
* @author oracleOAEC11
*
*/
@Controller
public class MyThirdController {
/**
* 获取所有的用户
* 获取所有的用户 value = "/getUsers" 访问路径,要使用value method=RequestMethod.GET
* 可以指定get或post请求
* @return
*/
@RequestMapping(value="/getUsers",method=RequestMethod.GET)
public ModelAndView getUsers() {
ModelAndView mav = new ModelAndView();
// 添加对象,相当于 request.setAttribute
mav.addObject("username", "lisi");
//执行完后,要返回一个页面
mav.setViewName("../index");
return mav;
}
@RequestMapping(value = "/getModelAndView")
public ModelAndView getModelAndView() {
// new 一个ModelAndView
ModelAndView mav = new ModelAndView();
mav.addObject("username", "wangwu");
Map<String,Object> map = new HashMap<String,Object>();
map.put("pwd", "123456");
map.put("age", 20);
//添加多个属性使用Map
mav.addAllObjects(map);
// 添加list数据类型
List<String> list = new ArrayList<String>();
list.add("Alice");
list.add("tom");
list.add("jack");
mav.addObject("list",list);
// 执行完成以后,要返回的一个页面 转发
mav.setViewName("redirect:/index.jsp");
return mav;
}
/**
* 返回string
*
* @return
*/
@RequestMapping(value = "/returnString")
public String returnString() {
System.out.println("调用了returnString方法");
return "../index";
}
@RequestMapping(value = "/viewResolverTest")
public ModelAndView viewResolverTest() {
// new 一个ModelAndView
ModelAndView mav = new ModelAndView();
// 添加对象,相当于 request.setAttribute
mav.addObject("username", "lisi");
Map<String, Object> map = new HashMap<String, Object>();
map.put("pwd", "123456");
map.put("age", 20);
// 添加多个属性,使用map
mav.addAllObjects(map);
// 添加list数据类型
List<String> list = new ArrayList<String>();
list.add("Alice");
list.add("Tom");
list.add("Jack");
mav.addObject("list", list);
// 执行完成以后,要返回的一个页面 转发 使用视图解析器,
// 转发的路径为:prefix + projectlist + suffix
// 如果要跳转的页面不在视图解析器的范围内,就要使用全路径跳转,
// 并且指定跳转方式 forward或redirect 如:mav.setViewName("forward:/index.jsp");
mav.setViewName("projectList");
return mav;
}
}
打开浏览器,在地址栏输入“http://localhost:8080/SpringMVCProject/getUsers”
总结
通过本次项目的配置与测试,学习了SpringMVC的简单配置,途中也遇到了“404”,但与以往相比更少了,更多的问题则是出现在编写配置文件的过程中,目前还没有遇到比较大的问题,以后会继续注意Java的编写习惯和减少犯错的几率。