Springmvc简介及配置
1. 什么是springMVC?
Spring Web MVC是一种基于Java的实现了MVC设计模式的、请求驱动类型的、轻量级Web框架。
2. SpringMVC处理请求的流程
2.1 首先用户发送请求-->DispatherServlet
2.2 DispatcherServlet-->HandlerMapping
2.3 DispatcherServlet-->HandlerAdapter
2.4 HandlerAdapter-->处理器功能处理方法的调用
2.5 ModelAndView的逻辑视图名-->ViewRecolver
2.6 View-->渲染
2.7 返回控制权给DispatcherServlet,由DispatcherServlet返回呼应给用户,流程结束
3. SpringMVC核心开发步骤
3.1 DispatcherServlet在web.xml中的部署描述,从而拦截请求到springMVC
3.2 HandlerMapping的配置,从而将请求映射到处理器
3.3 HandlerAdapter的配置,从而支持多种类型的处理器
3.4 处理器(页面控制器)的配置,从而刊行功能处理
3.5 ViewResolver的配置,从而将逻辑视图名解析为具体的视图技术
4. SpringMVC的组件
4.1 前端控制器(DispatcherServlet)
4.2 请求到处理器映射(HandlerMapping)
4.3 处理器适配器(HandlerAdapter)
4.4 视图解析器(ViewResolver)
4.5 处理器或页面控制器(Controller)
4.6 验证器(Validator)
4.6 命令对象(Command 请求参数绑定到的对象就叫命令对象)
4.7 表单对象(Form Object提供给表单展示和提交到的对象就叫表单对象)
5. 如何在项目中添加springmvc
5.1 添加相关依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency>
JSTL依赖
缺少下面的这两个jar包会报java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
原因:org.springframework.web.servlet.view.JstlView在视图解析时需要这二个jar包
<!-- 5.3、jstl、standard -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>${standard.version}</version>
</dependency>
<!-- 5.4、tomcat-jsp-api -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat-jsp-api.version}</version>
</dependency>
5.2 在WEB-INF下添加springmvc-servlet.xml(spring-mvc.xml)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 8 <!-- 通过context:component-scan元素扫描指定包下的控制器--> 9 <!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)--> 10 <aop:aspectj-autoproxy/> 11 <context:component-scan base-package="com.yuan"/> 12 13 <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter --> 14 <!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,--> 15 <!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)--> 16 <mvc:annotation-driven></mvc:annotation-driven> 17 18 <!--3) ViewResolver --> 19 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 20 <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar --> 21 <property name="viewClass" 22 value="org.springframework.web.servlet.view.JstlView"></property> 23 <property name="prefix" value="/WEB-INF/"/> 24 <property name="suffix" value=".jsp"/> 25 </bean> 26 27 <!--4) 单独处理图片、样式、js等资源 --> 28 <!--<mvc:resources location="/css/" mapping="/css/**"/>--> 29 <!--<mvc:resources location="/images/" mapping="/images/**"/>--> 30 <!--<mvc:resources location="/js/" mapping="/js/**"/>--> 31 32 <mvc:resources location="/static/" mapping="/static/**"/> 33 34 </beans>
5.3 修改web.xml
1 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 4 version="3.1"> 5 <display-name>Archetype Created Web Application</display-name> 6 7 <welcome-file-list> 8 <welcome-file>login.jsp</welcome-file> 9 </welcome-file-list> 10 11 <context-param> 12 <param-name>contextConfigLocation</param-name> 13 <param-value>classpath:applicationContext.xml</param-value> 14 </context-param> 15 <!-- 读取Spring上下文的监听器 --> 16 <listener> 17 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 18 </listener> 19 <!-- Spring和web项目集成end --> 20 21 <!-- 防止Spring内存溢出监听器 --> 22 <listener> 23 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> 24 </listener> 25 26 <!-- 中文乱码处理 --> 27 <filter> 28 <filter-name>encodingFilter</filter-name> 29 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 30 <!--web.xml 3.0的新特性,是否支持异步--> 31 <async-supported>true</async-supported> 32 <init-param> 33 <param-name>encoding</param-name> 34 <param-value>UTF-8</param-value> 35 </init-param> 36 </filter> 37 <filter-mapping> 38 <filter-name>encodingFilter</filter-name> 39 <url-pattern>/*</url-pattern> 40 </filter-mapping> 41 42 <!-- Spring MVC servlet --> 43 <servlet> 44 <servlet-name>SpringMVC</servlet-name> 45 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 46 <!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml--> 47 <init-param> 48 <param-name>contextConfigLocation</param-name> 49 <param-value>/WEB-INF/springmvc-servlet.xml</param-value> 50 </init-param> 51 <load-on-startup>1</load-on-startup> 52 <!--web.xml 3.0的新特性,是否支持异步--> 53 <async-supported>true</async-supported> 54 </servlet> 55 <servlet-mapping> 56 <servlet-name>SpringMVC</servlet-name> 57 <url-pattern>/</url-pattern> 58 </servlet-mapping> 59 60 </web-app>
Springmvc之helloword实现
1 package com.yuan.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 import java.util.HashMap; 8 import java.util.Map; 9 10 11 /** 12 * 5种情况 13 * 1、转发到页面 14 * 2、转发到根路径下的页面 15 * 3、转发到requestMapping 16 * 4、重定向到根路径下的页面 17 * 5、重定向到requestMapping下 18 */ 19 20 @Controller 21 public class HelloController { 22 23 @ResponseBody 24 @RequestMapping("/hello1") 25 public String hello1(){ 26 System.out.println("holle springmvc 你大爷"); 27 return "holle springmvc 你大爷"; 28 } 29 30 31 @RequestMapping("/hello2") 32 public String hello2(){ 33 System.out.println("holle springmvc 你二大爷"); 34 return "hello"; 35 } 36 37 @ResponseBody 38 @RequestMapping("/hello3") 39 public Map hello3(){ 40 System.out.println("holle springmvc 你二大爷"); 41 Map map = new HashMap(); 42 map.put("total",12); 43 map.put("rows","一串数据"); 44 return map; 45 }
}
Springmvc常用注解及返回值处理
增删改查案例演示
需要用到自定义标签和分页
工具类以及tag
PageBean
1 package com.yuan.util; 2 3 import javax.servlet.http.HttpServletRequest; 4 import java.io.Serializable; 5 import java.util.Map; 6 7 public class PageBean implements Serializable { 8 9 private static final long serialVersionUID = 2422581023658455731L; 10 11 //页码 12 private int page=1; 13 //每页显示记录数 14 private int rows=10; 15 //总记录数 16 private int total=0; 17 //是否分页 18 private boolean isPagination=true; 19 //上一次的请求路径 20 private String url; 21 //获取所有的请求参数 22 private Map<String,String[]> map; 23 24 public PageBean() { 25 super(); 26 } 27 28 //设置请求参数 29 public void setRequest(HttpServletRequest req) { 30 String page=req.getParameter("page"); 31 String rows=req.getParameter("rows"); 32 String pagination=req.getParameter("pagination"); 33 this.setPage(page); 34 this.setRows(rows); 35 this.setPagination(pagination); 36 this.url=req.getContextPath()+req.getServletPath(); 37 this.map=req.getParameterMap(); 38 } 39 public String getUrl() { 40 return url; 41 } 42 43 public void setUrl(String url) { 44 this.url = url; 45 } 46 47 public Map<String, String[]> getMap() { 48 return map; 49 } 50 51 public void setMap(Map<String, String[]> map) { 52 this.map = map; 53 } 54 55 public int getPage() { 56 return page; 57 } 58 59 public void setPage(int page) { 60 this.page = page; 61 } 62 63 public void setPage(String page) { 64 if(null!=page&&!"".equals(page.trim())) 65 this.page = Integer.parseInt(page); 66 } 67 68 public int getRows() { 69 return rows; 70 } 71 72 public void setRows(int rows) { 73 this.rows = rows; 74 } 75 76 public void setRows(String rows) { 77 if(null!=rows&&!"".equals(rows.trim())) 78 this.rows = Integer.parseInt(rows); 79 } 80 81 public int getTotal() { 82 return total; 83 } 84 85 public void setTotal(int total) { 86 this.total = total; 87 } 88 89 public void setTotal(String total) { 90 this.total = Integer.parseInt(total); 91 } 92 93 public boolean isPagination() { 94 return isPagination; 95 } 96 97 public void setPagination(boolean isPagination) { 98 this.isPagination = isPagination; 99 } 100 101 public void setPagination(String isPagination) { 102 if(null!=isPagination&&!"".equals(isPagination.trim())) 103 this.isPagination = Boolean.parseBoolean(isPagination); 104 } 105 106 /** 107 * 获取分页起始标记位置 108 * @return 109 */ 110 public int getStartIndex() { 111 //(当前页码-1)*显示记录数 112 return (this.getPage()-1)*this.rows; 113 } 114 115 /** 116 * 末页 117 * @return 118 */ 119 public int getMaxPage() { 120 int totalpage=this.total/this.rows; 121 if(this.total%this.rows!=0) 122 totalpage++; 123 return totalpage; 124 } 125 126 /** 127 * 下一页 128 * @return 129 */ 130 public int getNextPage() { 131 int nextPage=this.page+1; 132 if(this.page>=this.getMaxPage()) 133 nextPage=this.getMaxPage(); 134 return nextPage; 135 } 136 137 /** 138 * 上一页 139 * @return 140 */ 141 public int getPreivousPage() { 142 int previousPage=this.page-1; 143 if(previousPage<1) 144 previousPage=1; 145 return previousPage; 146 } 147 148 @Override 149 public String toString() { 150 return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination 151 + "]"; 152 } 153 }
PageTag
1 package com.yuan.tag; 2 3 import com.yuan.util.PageBean; 4 5 import javax.servlet.jsp.JspException; 6 import javax.servlet.jsp.JspWriter; 7 import javax.servlet.jsp.tagext.BodyTagSupport; 8 import java.io.IOException; 9 import java.util.Map; 10 import java.util.Map.Entry; 11 import java.util.Set; 12 13 14 public class PageTag extends BodyTagSupport { 15 16 private static final long serialVersionUID = 1L; 17 private PageBean pageBean; 18 public PageBean getPageBean() { 19 return pageBean; 20 } 21 public void setPageBean(PageBean pageBean) { 22 this.pageBean = pageBean; 23 } 24 @Override 25 public int doStartTag() throws JspException { 26 JspWriter out = pageContext.getOut(); 27 try { 28 out.print(toHTML()); 29 } catch (IOException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 return super.doStartTag(); 34 } 35 private String toHTML() { 36 StringBuffer sb = new StringBuffer(); 37 /* 38 * 拼接向后台提交数据的form表单 39 * 注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值 40 */ 41 sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); 42 sb.append("<input type='hidden' name='page'>"); 43 Map<String, String[]> parameterMap = pageBean.getMap(); 44 if(parameterMap != null && parameterMap.size() > 0) { 45 Set<Entry<String, String[]>> entrySet = parameterMap.entrySet(); 46 for (Entry<String, String[]> entry : entrySet) { 47 if(!"page".equals(entry.getKey())) { 48 String[] values = entry.getValue(); 49 for (String val : values) { 50 sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'>"); 51 } 52 } 53 } 54 } 55 sb.append("</form>"); 56 57 /* 58 * 展示的分页条 59 */ 60 sb.append("<div style='text-align: right; font-size: 12px;'>"); 61 sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 <a href='javascript:gotoPage(1)'>首页</a> <a"); 62 sb.append(" href='javascript:gotoPage("+pageBean.getPreivousPage()+")'>上一页</a> <a"); 63 sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a> <a"); 64 sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> <input type='text'"); 65 sb.append(" id='skipPage'"); 66 sb.append(" style='text-align: center; font-size: 12px; 50px;'> <a"); 67 sb.append(" href='javascript:skipPage()'>Go</a>"); 68 sb.append("</div>"); 69 70 /* 71 * 给分页条添加与后台交互的js代码 72 */ 73 sb.append("<script type='text/javascript'>"); 74 sb.append(" function gotoPage(page) {"); 75 sb.append(" document.getElementById('pageBeanForm').page.value = page;"); 76 sb.append(" document.getElementById('pageBeanForm').submit();"); 77 sb.append(" }"); 78 sb.append(" function skipPage() {"); 79 sb.append(" var page = document.getElementById('skipPage').value;"); 80 sb.append(" if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){"); 81 sb.append(" alert('请输入1~N的数字');"); 82 sb.append(" return;"); 83 sb.append(" }"); 84 sb.append(" gotoPage(page);"); 85 sb.append(" }"); 86 sb.append("</script>"); 87 return sb.toString(); 88 } 89 }
BookController
1 package com.yuan.controller; 2 3 import com.yuan.model.Book; 4 import com.yuan.service.BookService; 5 import com.yuan.util.PageBean; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Controller; 8 import org.springframework.web.bind.annotation.PathVariable; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 12 import javax.servlet.http.HttpServletRequest; 13 import java.util.List; 14 15 @Controller 16 @RequestMapping("/book") 17 public class BookController { 18 @Autowired 19 private BookService bookService; 20 21 22 @RequestMapping("/list") 23 public String list(Book book,HttpServletRequest req){ 24 PageBean pageBean = new PageBean(); 25 pageBean.setRequest(req); 26 List<Book> books = this.bookService.listPager1(book, pageBean); 27 req.setAttribute("bookList",books); 28 req.setAttribute("pageBean",pageBean); 29 return "bookList"; 30 } 31 32 @RequestMapping("/preSave") 33 public String preSave(Book book, HttpServletRequest req){ 34 if(book != null && book.getBid() != null && book.getBid() != 0){ 35 Book b = this.bookService.selectByPrimaryKey(book.getBid()); 36 req.setAttribute("book2",b); 37 } 38 return "bookEdit"; 39 } 40 41 @RequestMapping("/add") 42 public String add(Book book, HttpServletRequest req){ 43 this.bookService.insertSelective(book); 44 return "redirect:/book/list"; 45 } 46 47 @RequestMapping("/edit") 48 public String edit(Book book, HttpServletRequest req){ 49 this.bookService.updateByPrimaryKeySelective(book); 50 return "redirect:/book/list"; 51 } 52 53 @RequestMapping("/del/{bid}") 54 public String del(@PathVariable("bid") Integer bid, HttpServletRequest req){ 55 this.bookService.deleteByPrimaryKey(bid); 56 return "redirect:/book/list"; 57 } 58 59 60 }
首页展示
新增
修改
返回值处理
1 package com.yuan.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 import java.util.HashMap; 8 import java.util.Map; 9 10 11 /** 12 * 5种情况 13 * 1、转发到页面 14 * 2、转发到根路径下的页面 15 * 3、转发到requestMapping 16 * 4、重定向到根路径下的页面 17 * 5、重定向到requestMapping下 18 */ 19 20 @Controller 21 public class HelloController { 22 23 24 25 // 转发到页面 26 27 @RequestMapping("/forward1") 28 public String forward1(){ 29 System.out.println("进来了forward"); 30 return "aaa"; 31 } 32 33 // 转发到根路径下的页面 34 @RequestMapping("/forward2") 35 public String forward2(){ 36 return "forward:/bbb.jsp"; 37 } 38 39 // 转发到requestMapping 40 @RequestMapping("/forward3") 41 public String forward3(){ 42 return "forward:/forward1"; 43 } 44 45 // 重定向到根路径下的页面 46 @RequestMapping("/redirect1") 47 public String redirect1(){ 48 return "redirect:/bbb.jsp"; 49 } 50 51 // 重定向到requestMapping下 52 @RequestMapping("/redirect2") 53 public String redirect2(){ 54 return "forward:/forward1"; 55 } 56 57 }
演示结果:
forward1
forward2
forward3
redirect1
redirect2
Springmvc静态资源处理
springmvc不可以直接访问到静态资源文件
我们需要加一个专门处理处理静态资源文件的功能
案例: 访问static的图片
在springmvc-servlet.xml中添加
<mvc:resources location="/static/" mapping="/static/**"/>
添加图片到static/images中
访问结果:
谢谢观看!!!