第十四章 springmvc快速入门(注解版本)
1)springmvc快速入门(传统版)
步一:创建springmvc-day02这么一个web应用
步二:导入springioc,springweb和springmvc相关的jar包
------------------------------------------------------springWEB模块 org.springframework.web-3.0.5.RELEASE.jar org.springframework.web.servlet-3.0.5.RELEASE.jar(mvc专用) ------------------------------------------------------springIOC模块 org.springframework.asm-3.0.5.RELEASE.jar org.springframework.beans-3.0.5.RELEASE.jar org.springframework.context-3.0.5.RELEASE.jar org.springframework.core-3.0.5.RELEASE.jar org.springframework.expression-3.0.5.RELEASE.jar |
步三:在/WEB-INF/下创建web.xml文件
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
步四:创建HelloAction.java控制器类
@Controller
public class HelloAction {
@RequestMapping(value = "/hello")
public String helloMethod(Model model) throws Exception {
System.out.println("HelloAction::helloMethod()");
model.addAttribute("message", "这是我的第二个springmvc应用程序");
return "/success.jsp";
}
}
步五:在/WebRoot/下创建success.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>这是我的第二个springmvc应用程序</title>
</head>
<body>
success.jsp
<br /> ${message}
</body>
</html>
步六:在/src/目录下创建spring.xml配置文件
<!-- Action控制器 -->
<context:component-scan base-package="cn.itcast.javaee.springmvc.helloannotation" />
<!-- 基于注解的映射器(可选) -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <!-- 基于注解的适配器(可选) -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <!-- 视图解析器(可选) -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
步七:部署web应用到tomcat中,通过浏览器访问如下URL:
http://127.0.0.1:8080/springmvc-day02/hello.action
第十五章 一个Action中,可以写多个类似的业务控制方法
1)通过模块根路径 + 功能子路径 = 访问模块下子功能的路径
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/add")
public String add(Model model) throws Exception {
System.out.println("HelloAction::add()");
model.addAttribute("message", "增加用户");
return "/success.jsp";
} @RequestMapping(value = "/find")
public String find(Model model) throws Exception {
System.out.println("HelloAction::find()");
model.addAttribute("message", "查询用户");
return "/success.jsp";
}
}
增加用户:http://127.0.0.1:8080/myspringmvc-day02/user/add.action
查询用户:http://127.0.0.1:8080/myspringmvc-day02/user/find.action
第十六章 在业务控制方法中写入普通变量收集参数
1)可以在业务控制方法中,以参数形式收集客户端参数,springmvc采用方法参数形式的
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/add")
public String add(Model model, int id, String name, Double sal) throws Exception {
System.out.println("HelloAction::add()");
System.out.println(id + ":" + name + ":" + sal);
model.addAttribute("message", "增加用户");
return "/success.jsp";
}
}
http://127.0.0.1:8080/myspringmvc-day02/user/add.action?id=1&name=zhaojun&sal=5000
第十七章 限定某个业务控制方法,只允许GET或POST请求方式访问
1)可以在业务控制方法前,指明该业务控制方法只能接收GET或POST的请求
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, int id, String name, double sal) throws Exception {
System.out.println("HelloAction::add()::POST");
System.out.println(id + ":" + name + ":" + sal);
model.addAttribute("message", "增加用户");
return "/success.jsp";
}
}
如果不书写method=RequestMethod.POST的话,GET和POST请求都支持
第十八章 在业务控制方法中写入Request,Response等传统web参数
1)可以在业务控制方法中书写传统web参数,这种方式我们不提倡,耦合了
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void add(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("HelloAction::add()::POST");
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
double sal = Double.parseDouble(request.getParameter("sal"));
System.out.println(id + ":" + name + ":" + sal);
request.getSession().setAttribute("id", id);
request.getSession().setAttribute("name", name);
request.getSession().setAttribute("sal", sal);
response.sendRedirect(request.getContextPath() + "/register.jsp");
}
}
第十九章 在业务控制方法中写入模型变量收集参数,且使用@InitBind来解决字符串转日期类型
1) 在默认情况下,springmvc不能将String类型转成java.util.Date类型,所有我们只能在Action
中自定义类型转换器
<form action="${pageContext.request.contextPath}/user/add.action" method="POST">
编号:<input type="text" name="id" value="${id}" /><br />
姓名:<input type="text" name="name" value="${name}" /><br />
薪水:<input type="text" name="sal" value="${sal}" /><br />
入职时间:<input type="text" name="hiredate"
value='<fmt:formatDate value="${hiredate}" type="date"/>' /><br />
<input type="submit" value="注册" />
</form>
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
} @RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(int id, String name, double sal, Date hiredate, Model model) throws Exception {
System.out.println("HelloAction::add()::POST");
model.addAttribute("id", id);
model.addAttribute("name", name);
model.addAttribute("sal", sal);
model.addAttribute("hiredate", hiredate);
return "/register.jsp";
}
}
第二十章 在业务控制方法中写入User,Admin多个模型收集参数
1) 可以在业务控制方法中书写1个模型来收集客户端的参数
2) 模型中的属性名必须和客户端参数名一一对应
3) 这里说的模型不是Model对象,Model是向视图中封装的数据
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
} @RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(User user, Model model) throws Exception {
System.out.println("HelloAction::add()::POST");
model.addAttribute("user", user);
return "/register.jsp";
}
}
第二十一章 在业务控制方法中写入包装User的模型来收集参数
可以在业务控制方法中书写0个或多个模型来收集客户端的参数
1) 如果多个模型中有相同的属性时,可以用user.name或admin.name来收集客户端参数
2) 用一个新的模型将User和Admin再封装一次
User.java
public class User {
private Integer id;
private String name;
private Double sal;
private Date hiredate; public User() {
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Double getSal() {
return sal;
} public void setSal(Double sal) {
this.sal = sal;
} public Date getHiredate() {
return hiredate;
} public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
} @Override
public String toString() {
return this.id + ":" + this.name + ":" + this.sal + ":" + this.hiredate;
}
}
Bean.java
public class Bean {
private User user;
private Admin admin; public Bean() {
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public Admin getAdmin() {
return admin;
} public void setAdmin(Admin admin) {
this.admin = admin;
}
}
PersonAction.java
@Controller
@RequestMapping(value = "/person")
public class PersonAction {
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
} @RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Bean bean, Model model) throws Exception {
System.out.println(bean.getUser());
System.out.println(bean.getAdmin());
System.out.println("PersonAction::add()::POST");
model.addAttribute("bean", bean);
return "/register.jsp";
}
}
register.jsp
普通用户
<form action="${pageContext.request.contextPath}/person/add.action" method="POST">
编号:<input type="text" name="user.id" value="${bean.user.id}"/><br/>
姓名:<input type="text" name="user.name" value="${bean.user.name}"/><br/>
薪水:<input type="text" name="user.sal" value="${bean.user.sal}"/><br/>
入职时间:<input type="text" name="user.hiredate" value='<fmt:formatDate value="${bean.user.hiredate}" type="both" />'/><br/>
<input type="submit" value="注册"/>
</form>
第二十二章 在业务控制方法中收集数组参数
批量删除用户
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/delete")
public String deleteMethod(int[] ids, Model model) throws Exception {
System.out.println("UserAction::deleteMethod()");
System.out.println("需要删除的id为:");
for (int id : ids) {
System.out.print(id + " ");
}
model.addAttribute("message", "批量删除成功");
return "/success.jsp";
}
}
第二十三章 在业务控制方法中收集List<JavaBean>参数
批量注册用户
UserAction.java
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/addAll")
public String addAll(Bean bean, Model model) throws Exception {
for (User user : bean.getUserList()) {
System.out.println(user.getName() + ":" + user.getGender());
}
model.addAttribute("message", "批量增加用户成功");
return "/success.jsp";
}
}
Bean.java
public class Bean {
private List<User> userList = new ArrayList<User>(); public Bean() {
} public List<User> getUserList() {
return userList;
} public void setUserList(List<User> userList) {
this.userList = userList;
}
}
registerAll.jsp
<form action="${pageContext.request.contextPath}/user/addAll.action" method="POST">
姓名:<input type="text" name="userList[0].name" value="哈哈"/>
性别:<input type="text" name="userList[0].gender" value="男"/>
<hr/> 姓名:<input type="text" name="userList[1].name" value="呵呵"/>
性别:<input type="text" name="userList[1].gender" value="男"/>
<hr/> 姓名:<input type="text" name="userList[2].name" value="嘻嘻"/>
性别:<input type="text" name="userList[2].gender" value="女"/>
<hr/> <input type="submit" value="批量注册"/>
</form>
第二十四章 结果的转发和重定向
1) 在转发情况下,共享request域对象,会将参数从第一个业务控制方法传入第二个业务控制方法,
反之,重定向则不行
删除id=10号的用户,再查询用户
@Controller
@RequestMapping(value = "/user")
public class UserAction { @RequestMapping(value = "/delete")
public String delete(int id) throws Exception {
System.out.println("删除用户->" + id);
// 转发到find()
return "forward:/user/find.action";
// 重定向到find()
// return "redirect:/user/find.action";
} @RequestMapping(value = "/find")
public String find(int id) throws Exception {
System.out.println("查询用户->" + id);
return "/success.jsp";
} }
第二十五章 异步发送表单数据到JavaBean,并响应JSON文本返回
1) 提交表单后,将JavaBean信息以JSON文本形式返回到浏览器
bean2json.jsp
<form>
编号:<input type="text" name="id" value="1"/><br/>
姓名:<input type="text" name="name" value="哈哈"/> <br />
薪水:<input type="text" name="sal" value="5000" /><br />
<input type="button" value="异步提交注册" />
</form> <script type="text/javascript">
$(":button").click(function() {
var url = "${pageContext.request.contextPath}/user/add.action";
var sendData = {
"id" : 1,
"name" : "哈哈",
"sal" : 5000
};
$.post(url, sendData, function(backData, textStatus, ajax) {
alert(ajax.responseText);
});
});
</script>
User.java
public class User {
private Integer id;
private String name;
private Double sal;
public User() {
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Double getSal() {
return sal;
} public void setSal(Double sal) {
this.sal = sal;
}
}
UserAction.java
@Controller
@RequestMapping(value = "/user")
public class UserAction {
@RequestMapping(value = "/add")
public @ResponseBody User add(User user) throws Exception {
System.out.println(user.getId() + ":" + user.getName() + ":" + user.getSal());
return user;
}
}
spring.xml
<!-- Action控制器 -->
<context:component-scan base-package="cn.itcast.javaee.springmvc.app25" /> <!-- 配适器 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
注意:使用mvc注解驱动可以代替spring.xml中适配器和映射器的配置信息,包括对json的配置
<mvc:annotation-driven/>
拦截器
springmvc拦截器是针对mapping的拦截配置。
配置方法:
1.针对某种mapping配置拦截器 符合mapping的handler才能被拦截到。
2.针对所有mapping配置全局拦截器:达到目的:所有请求都走这个拦截器配置。
springmvc框架自动将这个拦截器配置注入到所有的mapping中。
<!-- 拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器,顺序执行 -->
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="cn.itcast.springmvc.filter.HandlerInterceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="cn.itcast.springmvc.filter.HandlerInterceptor2"></bean>
</mvc:interceptor>
</mvc:interceptors>
原理及场景分析:
package cn.itcast.springmvc.interceptor; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; public class HandlerInterceptor1 implements HandlerInterceptor { /**
* 此方法是在进行handler方法之前执行
* arg2:要执行的handler
* 场景:用户权限的拦截
*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception { //返回一个false表示拦截,后边的拦截器不再执行
//如果返回一个true表示放行
System.out.println("HandlerInterceptor1..preHandle");
return true;
}
/**
* 此方法是在执行handler完毕,返回modenAndview之前执行
* 场景:对ModelAndView进行修改,比如统一添加页面导航(页面所需要的公用数据)
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("HandlerInterceptor1..postHandle"); }
/**
* 此方法是在执行handler完毕,且返回ModelAndView之后执行
* 场景:在这里记录执行的时间,并且在preHandle方法中也记录执行的开始时间,统一action执行时间,完成执行性能监视
* 场景:统一在这里进行日志记录
* 场景:统一进行异常处理
*/
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("HandlerInterceptor1..afterCompletion"); } }
例子:
拦截器用户认证应用: 所有的请求都由用户认证拦截器进行拦截: 判断如果用户的session没有要跳转到登录页面