1. 搭建和测试SpringMVC的开发环境
- 在web.xml中配置DispatcherServlet前端控制器
<!--配置前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc.xml配置文件-->
<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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 在web.xml中配置DispatcherServlet过滤器解决中文乱码
<!--解决post请求中文乱码的过滤器-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 创建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: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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描controller的注解,别的不扫描-->
<context:component-scan base-package="com.qcby.controller"/>
<!-- 配置视图解析器-->
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--JSP文件所在的目录-->
<property name="suffix" value="/pages/"/>
<!--文件的后缀名-->
<property name="prefix" value=".jsp"/>
</bean>
<!--设置静态资源不过滤-->
<mvc:resources mapping="/source/css/**" location="/source/css/"/>
<mvc:resources mapping="/source/js/**" location="/source/js/"/>
<mvc:resources mapping="/source/images/**" location="/source/images/"/>
<!--开启springmvc-->
<mvc:annotation-driven/>
</beans>
- 测试SpringMVC的框架搭建是否成功
1. 编写index.jsp和list.jsp编写,超链接
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="/account/findAll">查询所有</a>
</body>
</html>
2. 创建AccountController类,编写方法,进行测试
package com.qcby.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/account")
public class AccountController {
/**
* 查询所有
* @return
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
System.out.println("表现层:查询所有");
ModelAndView mv = new ModelAndView();
mv.setViewName("suc");
return mv;
}
}