springmvc
程序员文章站
2022-07-11 11:50:57
...
springmvc主要由 一个DispatcherServlet(不需要开发),三个组件:处理器映射器,处理器适配器,视图解析器(不需要开发)
hanlder(需要开发),view(需要开发)组成
架构流程
- 用户发送请求至前端控制器DispatcherServlet
- DispatcherServlet收到请求调用HandlerMapping处理器映射器。
- 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
- DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
- 执行处理器(Controller,也叫后端控制器)。
- Controller执行完成返回ModelAndView
- HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
- DispatcherServlet将ModelAndView传给ViewReslover视图解析器
- ViewReslover解析后返回具体View
- DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
- DispatcherServlet响应用户
springmvc与struts2不同
- springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过滤器。
- springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
- Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过request域传输到页面。Jsp视图解析器默认使用jstl。
核心配置文件springmvc.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-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 扫描@Controler @Service -->
<context:component-scan base-package="lx" />
<!-- 处理器映射器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
<!-- 处理器适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- 注解驱动 -->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean" />
<!-- 配置Conveter转换器 转换工厂 (日期、去掉前后空格)。。 -->
<bean id="conversionServiceFactoryBean"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 配置 多个转换器 -->
<property name="converters">
<list>
<bean class="lx.springmvc.conversion.DateConveter" />
</list>
</property>
</bean>
<!-- 视图解释器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置异常处理器 -->
<bean class="lx.springmvc.exception.CustomerExceptionResolver"></bean>
<!-- 上传图片配置实现类 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传图片的大小 B 5M 1*1024*1024*5 -->
<property name="maxUploadSize" value="5000000" />
</bean>
<!-- SPringmvc的拦截器 -->
<mvc:interceptors>
<!-- 多个拦截器 -->
<mvc:interceptor>
<mvc:mapping path="/**" />
<!-- 自定义的拦截器类 -->
<bean class="lx.springmvc.interceptor.Interceptor1" />
</mvc:interceptor>
<!-- <mvc:interceptor>
<mvc:mapping path="/**"/>
自定义的拦截器类
<bean class="com.itheima.springmvc.interceptor.Interceptor2"/>
</mvc:interceptor> -->
</mvc:interceptors>
</beans>
默认参数绑定
@RequestMapping("/itemEdit")
public ModelAndView toEdit(HttpServletRequest request,HttpServletResponse response
,Model model){
//servlet时代
String id = request.getParameter("id");
Items items = itemService.selectById(Integer.parseInt(id));
ModelAndView mav = new ModelAndView();
mav.addObject("item", items);
mav.setViewName("editItem");
return mav;
}
简单数据类型绑定
@RequestMapping("/itemEdit")
public ModelAndView toEdit(
/*@RequestParam(value="id",defaultValue="1",required=false)Integer idaa,*/
Integer id,
HttpServletRequest request,HttpServletResponse response
,Model model){
//servlet时代
// String id = request.getParameter("id");
Items items = itemService.selectById(id);
ModelAndView mav = new ModelAndView();
mav.addObject("item", items);
mav.setViewName("editItem");
return mav;
}
绑定pojo
@RequestMapping("/updateitem")
public ModelAndView updateItem(Items item){
itemService.updateItem(item);
ModelAndView mav = new ModelAndView();
mav.setViewName("success");
return mav;
}
绑定包装的pojo
public class QueryVo {
private Items item;
private List<Items> itemsList;
public List<Items> getItemsList() {
return itemsList;
}
public void setItemsList(List<Items> itemsList) {
this.itemsList = itemsList;
}
public Items getItem() {
return item;
}
public void setItem(Items item) {
this.item = item;
}
}
@RequestMapping("/updateitem")
public ModelAndView updateItem(QueryVo vo){
itemService.updateItem(vo.getItem());
ModelAndView mav = new ModelAndView();
mav.setViewName("success");
return mav;
}
页面
<td><input type="text" name="item.name" value="${item.name }" /></td>
绑定数组
@RequestMapping("/item/itemsupdate")
public ModelAndView deleteItem(Integer[] ids){
ModelAndView mav = new ModelAndView();
mav.setViewName("success");
return mav;
}
页面
可以批量删除和修改
<c:forEach items="${itemList }" var="item" varStatus="s">
<tr>
<td><input type="checkbox" name="ids" value="${item.id}"></td>
<td><input type="text" name="itemsList[${s.index}].name" value="${item.name}"></td>
<td><input type="text" name="itemsList[${s.index}].price" value="${item.price}"></td>
<td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
<%-- <td>${item.createtime }</td> --%>
<td>${item.detail }</td>
<td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>
</tr>
</c:forEach>
Controller方法返回值
1.ModelAndView 无敌的,带着数据返回视图路径。
@RequestMapping("/itemList")
public ModelAndView itemList(){
List<Items> list = itemService.queryItemList();
ModelAndView model = new ModelAndView();
model.addObject("itemList", list);
model.setViewName("itemList");
return model;
}
2.String 返回视图路径,model带数据 (推荐:解耦,数据视图分离)
@RequestMapping(value = "/itemlist.action")
public String itemList(Model model) {
List<Items> list = itemService.selectItemsList();
model.addAttribute("itemList", list);
return "itemList";
}
3.void ajax请求合适
重定向与转发
return "redirect:/item/itemlist.action";
return "forward:/item/itemlist.action";
异常处理
CustomerExceptionResolver.java
package lx.springmvc.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
*
* @author lx
*
*/
public class CustomerExceptionResolver implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
Exception e) {
ModelAndView mav = new ModelAndView();
if(e instanceof MessageException){
//已知异常
mav.addObject("error",((MessageException) e).getMsg());
}else{
mav.addObject("error", "未知异常");
}
mav.setViewName("error");
return mav;
}
}
MessageException.java
package lx.springmvc.exception;
public class MessageException extends Exception{
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public MessageException(String msg) {
super();
this.msg = msg;
}
}
上传图片
先配置Tomcat虚拟目录
@RequestMapping(value = "/updateitem.action")
public String updateitem(Items items,MultipartFile pictureFile) throws Exception{
//D:\fileupload
String name = UUID.randomUUID().toString().replaceAll("-", "");
String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
pictureFile.transferTo(new File ("D:\\fileupload\\" + name + "." + ext));
items.setPic(name + "." + ext);
itemService.updateItemsById(items);
return "redirect:/item/itemlist.action";
}
jsp
<!-- 上传图片是需要指定属性 enctype="multipart/form-data" -->
<!-- <form id="itemForm" action="" method="post" enctype="multipart/form-data"> -->
<form id="itemForm" action="${pageContext.request.contextPath }/updateitem.action" method="post" enctype="multipart/form-data">
json数据交互
jsp
<script type="text/javascript">
$(function(){
// alert(1);
var params = '{ "id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';
$.ajax({
url : "${pageContext.request.contextPath }/json.action",
data : params,
contentType : "application/json;charset=UTF-8",
type : "post",
dataType : "json",
success : function(data){
alert(data.name);
}
});
});
</script>
@RequestMapping(value = "/json.action")
public @ResponseBody
Items json(@RequestBody Items items){
// System.out.println(items);
return items;
}
@RequestMapping(value = "/json.action")
public void json(@RequestBody Items items){
System.out.println(items);
}
拦截器
package lx.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 Interceptor1 implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
throws Exception {
System.out.println("页面渲染后");
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("方法后");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
System.out.println("方法前");
// URL http://localhost:8080/springmvc-mybatis/login.action
//URI /login.action
String requestURI = request.getRequestURI();
if(!requestURI.contains("/login")){
String username = (String) request.getSession().getAttribute("USER_SESSION");
if(null == username){
response.sendRedirect(request.getContextPath() + "/login.action");
return false;
}
}
return true;
}
}
@RequestMapping(value = "/login.action",method = RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping(value = "/login.action",method = RequestMethod.POST)
public String login(String username,HttpSession httpSession){
httpSession.setAttribute("USER_SESSION", username);
return "redirect:/item/itemlist.action";
}
推荐阅读
-
如何将mybatis配置到springmvc中
-
SpringMVC + jquery.uploadify实现上传文件功能
-
SpringMVC4 + MyBatis3 + SQL Server 2014整合教程(含增删改查分页)
-
SpringMvc接收参数方法总结(必看篇)
-
Java SSM框架(Spring+SpringMVC+MyBatis)搭建过程
-
springMVC引入Validation的具体步骤详解
-
解决表单post,get到springMVC后台乱码的问题
-
SpringMVC上传文件FileUpload使用方法详解
-
SpringMVC文件上传及查看的示例代码
-
浅谈SpringMVC中Interceptor和Filter区别