10.1 SpringMVC
SpringMVC是Spring家族的一个特性,用于WEB开发.官网spring.io
参考<SpringMVC教程>进行配置.
配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring3 中文表单参数支持 -->
<filter>
<filter-name>spring3encoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>spring3encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring3 support -->
<servlet>
<servlet-name>spring3</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup> 1 </load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring3</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
添加spring3-servlet.xml, 复制web.xml改名为spring3-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
default-autowire="byName">
<!-- 描述包含controller的包路径, 以逗号分隔 -->
<context:component-scan base-package="my" > </context:component-scan>
<!-- 默认的注解映射的支持 -->
<mvc:annotation-driven />
<!-- 视图解释类 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
</bean>
<!-- 对静态资源文件的访问 方案一 (二选一) -->
<mvc:default-servlet-handler/>
</beans>
新建一个packge my,下面新建一个class
HelloController
@Controller
public class HelloController
{
@RequestMapping("/test1")
public ModelAndView test1()
{
return new ModelAndView ("test1view", "result", "haha");
}
}
注:包路径my要配置到spring3-servlet.xml里,不然spring3不会加载这个类
解释:Controller控制器
@Controller : 声明这是一个spring3的controller
@RequestMapping("/test1"): 用于声明一个url映射: 当访问 /test1时,请求由此函数处理
new ModelAndView (“test1view”, “result”, “haha”)
指定view是 test1view.jsp 进行显示,同时添加一个属性result用于存放结果数据。(参考下一章的说明)
添加一个test1view.jsp文件在webroot下面.test1view的名字是因为Controller里面起名.
<%@ 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 'index.jsp' starting page</title>
</head>
<body>
spring3mvc: result=${result} <br>
</body>
</html>
MVC=Controller Model View(控制器,数据模型,视图)
先由Controller响应,接收数据发给JSP视图实现.
10.2 SpringMVC(2)自定义的Model
本节课演示一个更复杂的Model
test1view.jsp
<body>
<label>学号:</label> ${result.id }<br>
<label>姓名:</label> ${result.name }<br>
<label>电话:</label> ${result.cellphone}<br>
</body>
建立一个简单的POJO类Student包含int id,String name,String cellphone
控制器
@Controller
public class GoodController
{
@RequestMapping("/test1")
public ModelAndView test1()
{
Student result =new Student();
result.id=20170001;
result.name="xxx";
result.cellphone="13999999";
return new ModelAndView ("test1view", "result", result);
}
}
Model可以是一个复杂的对象,只要有Getter就能在View里访问.
C:test1.do->test1()
M:result=new Student()
V:test1View.jsp
10.3 SpringMVC(3)获取请求参数
添加HelloController.java里面
@RequestMapping("/test3a")
public ModelAndView test3a(int id, String name, String cellphone)
{
System.out.println("请求参数: " + id + "," + name + "," + cellphone);
return new ModelAndView("test3view", "result", "");
}
@RequestMapping("/test3b")
public ModelAndView test3b(HttpServletRequest request, HttpServletResponse response)
{
String id = request.getParameter("id");
String name = request.getParameter("name");
String cellphone = request.getParameter("cellphone");
System.out.println("请求参数3b: " + id + "," + name + "," + cellphone);
return new ModelAndView("test3view", "result", "");
}
@RequestMapping("/test3c")
public ModelAndView test3c(Student stu)
{
System.out.println("请求参数3c: " + stu.id + "," + stu.name + "," + stu.cellphone);
return new ModelAndView("test3view", "result", "");
}
添加对应页面test3.jsp
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
</head>
<body>
<form class='myform' method='post' action='test3a.do' >
<input type='text' name='id' placeholder='学号' /> <br>
<input type='text' name='name' placeholder='姓名' /> <br>
<input type='text' name='cellphone' placeholder='手机号' /> <br>
<input type='submit' value='提交' />
</form>
</body>
</html>
还有跳转页面test3view.jsp
SpringMVC会自动根据参数的名称和类型,将参数值传入到处理函数。
三种方式:
form字段 <-> 函数参数
request中获取 :
映射为pojo : 对应struts的ModelDriven,通过映射的方式把Student POJO类直接取到
10.4 SpringMVC(4)RESTful接口的实现
RESTful 客户端>>json>>服务器
客户端<<json<<服务器
@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,
写入到response对象的body区,通常用来返回JSON数据或者是XML
@Controller
public class HelloController
{
//////////////// 第4节课 ////////////////
@ResponseBody
@RequestMapping(value ="/test4", produces = "text/plain; charset=utf-8") //设置Controller的响应URL,设置格式
public String test4 ( @RequestBody String str ) throws Exception //设置字符编码utf-8
{
JSONObject req = new JSONObject(URLDecoder.decode(str, "UTF-8"));
JSONObject resp = new JSONObject();
resp.put("a", req.getString("name"));
resp.put("b", 1);
return resp.toString( 4 );
}
}