springMVC 学习日志

1、新建WEB项目,导入Spring的jar包。

2、配置WebContent\WEB-INF\Web.xml。在web-app标签里面加入下一配置;

<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<!-- 字符集过滤器 -->
	<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>
 

3、WebContent\WEB-INF目录下添加springMVC-servlet.xml配置文件。

springMVC为第2步配置的<servlet-name>springMVC</servlet-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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		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-3.0.xsd">

	<!-- springMvc 注解驱动 -->
	<mvc:annotation-driven/>
	<!-- 扫描器 -->
	<context:component-scan base-package="com.huizhi"/>
	
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="/view/"></property>
		<!-- 后缀 -->
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	
</beans>

4、在src下添加包com.huizhi.controller,在包下加入hello.java文件。

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class hello {
	
	@RequestMapping(value="/test.do")
	public String test(Model model) {
		model.addAttribute("helloword", "这是后台返回的数据:HelloWord");
		
		//当访问test.do时,返回数据到/view/sayHello.jsp
		return "sayHello";
	}
}

5、在WebContent\view\下加一个sayHello.jsp。在body中使用变量

${helloword}获取后台返回的数据