1.SpringMVC的工作原理
- 浏览器发出一个http请求给服务器,如果匹配DispatcherServlet的请求映射路径(在web.xml中指定),服务器将请求转交给DispatcherServlet.
- DipatcherServlet接收到这个请求之后,根据请求的路径,将请求转交给相应的Controller
- Controller处理后,返回ModelAndView对象(封装跳转页面,要传递的数据)
- DispatcherServlet根据ViewResolver视图解析器,找到ModelAndView指定的JSP。(ModelAndView只是逻辑视图并不是一个正式的视图)
- 将JSP显示到浏览器中
2.代码
1.项目目录
2.ApplicationContext-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 如果显示找不到mvc:resources标签而报错的话,可能因为编辑器中的schema过于陈旧,这时将
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd的结尾的3.0改成3.2即可 -->
<!-- 要扫描的包 -->
<context:component-scan base-package="org.jsoft.action."/>
<!-- 启用注解和对对应目录下静态资源的访问 -->
<mvc:annotation-driven/>
<mvc:resources mapping="/assets/**" location="/assets/"/>
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置springMVC的servlet -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置ApplicationContext.xml的路径 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/ApplicationContext-mvc.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>
</web-app>
4.vo类
public class Student {
private Long id;
private String name;
private Integer age;
/**getter and setter*/
}
5.C层StudentAction
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.jsoft.vo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("studentAction")
public class StudentAction {
//方法一,返回的是一个字符串,根据视图解析器,会自动在前面加上/,在后面加上".jsp",在访问这个jsp页面
@RequestMapping("/login")
public String login(){
System.out.println("StudentAction.login()");
return "index";
}
//方法二,返回一个最常用的ModelAndView,里面可以添加要传向浏览器的数据和页面
@RequestMapping("/register")
public ModelAndView register(){
Student student = new Student();
student.setAge(50);
student.setName("PinkFloyd");
student.setId(1L);
ModelAndView mv = new ModelAndView();
mv.setViewName("register");//设置返回的页面
mv.addObject("student", student);//添加键值对形式的返回数据
mv.addObject("firstName", "David");
mv.addObject("lastName", "Gilmour");
return mv;
}
//方法三,需要接受页面数据时可以在方法的参数里添加request和response
@RequestMapping("/update")//这是Ajax形式的请求
public void update(HttpServletRequest request,HttpServletResponse response) throws Exception{
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Student student = new Student();
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
student.setAge(new Integer(age));
student.setName(name);
student.setId(new Long(id));
PrintWriter out = response.getWriter();
out.print(JSONObject.fromObject(student).toString());//已json的形式返回
}
}
6.V层register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'register.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="assets/js/jquery-1.10.1.js"></script>
</head>
<body>
Register.jsp <br/>
Welcome!${student.id},${student.age},${student.name}乐队的
<%=request.getAttribute("firstName") %> ${lastName}
<form id="f">
乐队id:<input name="id" value="${student.id}"/>
乐队年龄:<input name="age" value="${student.age}"/>
乐队名称:<input name="name" value="${student.name}"/>
<input id="btn" type="button" value="修改">
</form>
<script type="text/javascript" >
$(function(){
$("#btn").click(function(){
$.ajax({
url:"studentAction/update",
type:"post",
data:$("#f").serialize(),
dataType:"json",
success : function(msg){
alert(msg.name);
}
})
})
});
</script>
</body>
</html>