Spring MVC(Model-View-Controller)是一个基于Java的Web应用程序框架,用于构建Web应用程序。它是Spring框架的一部分,提供了一种组织和开发Web应用程序的方式,将应用程序分为模型、视图和控制器三个部分,以实现松散耦合和分层架构。
以下是关于Spring MVC的一些重要概念和特点:
模型(Model):模型代表应用程序的业务逻辑和数据。通常,模型对象包含应用程序的数据,以及对这些数据的操作方法。在Spring MVC中,模型通常由POJO(Plain Old Java Object)表示。
视图(View):视图负责呈现模型数据给用户。视图通常是模板文件(例如JSP、Thymeleaf、FreeMarker等),可以将模型数据渲染成HTML,然后返回给客户端浏览器显示。
控制器(Controller):控制器是处理HTTP请求的组件。它接收客户端请求,决定如何处理请求,并将请求委托给适当的服务方法。Spring MVC的控制器通常是基于注解的Java类。
前端控制器(Front Controller):Spring MVC框架的核心部分是前端控制器(DispatcherServlet),它是一个Servlet,用于接收所有进入应用程序的HTTP请求,并将请求分派给适当的处理程序。
请求映射(Request Mapping):Spring MVC通过注解或配置文件来映射HTTP请求到特定的控制器方法。请求映射定义了哪个控制器方法将处理特定URL的请求。
视图解析器(View Resolver):视图解析器用于将控制器返回的逻辑视图名称解析为实际的视图。它可以将逻辑视图名称映射到具体的视图模板文件。
模型和视图之间的通信:控制器方法可以将模型数据存储在Model对象中,并将视图名称返回给前端控制器。前端控制器会将模型数据传递给适当的视图模板,以便渲染页面。
拦截器(Interceptors):拦截器允许您在请求进入控制器之前或之后执行自定义逻辑。它们可以用于实现日志记录、安全性检查、权限验证等功能。
表单处理:Spring MVC提供了强大的表单处理功能,可以轻松地处理表单提交、数据绑定、验证和错误处理。
RESTful支持:Spring MVC支持构建RESTful Web服务,可以使用注解来定义REST端点,支持HTTP方法如GET、POST、PUT和DELETE。
国际化支持:Spring MVC支持多语言和国际化,使您能够轻松地本地化您的应用程序。
异常处理:Spring MVC提供了强大的异常处理机制,允许您定义全局异常处理器,以捕获和处理应用程序中的异常
- package com.YU.web;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- /**
- * @author YU
- * @create 2023-09-07 14:41
- */
- @Controller
- public class PageController {
-
- @RequestMapping("/page/{page}")
- public String toPage(@PathVariable("page") String page){
- return page;
- }
-
- @RequestMapping("/page/{dir}{page}")
- public String toDirPage(
- @PathVariable("dir") String dir,
- @PathVariable("page") String page){
- return dir + "/" + page;
- }
- }
在生成后的HBookMapper接口中,需要加上@Repository给Spring进行托管
2.1切面类:
- package com.YU.aspect;
-
- import com.YU.utils.PageBean;
- import com.github.pagehelper.PageHelper;
- import com.github.pagehelper.PageInfo;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.Around;
- import org.aspectj.lang.annotation.Aspect;
- import org.springframework.stereotype.Component;
-
- import java.util.List;
-
- /**
- * @author YU
- * @create 2023-08-25 17:17
- */
- @Aspect //代表当前类为切面类
- @Component //代表当前类交给Spring进行管理
- public class PagerAspect {
- @Around("execution(* *..*biz.*Pager(..))")
- public Object invoke(ProceedingJoinPoint args) throws Throwable {
- PageBean pageBean = null;
- //获取目标方法的所有参数
- Object[] ars = args.getArgs();
- for (Object param : ars) {
- if(param instanceof PageBean){
- pageBean = (PageBean)param;
- break;
- }
- }
-
- if(pageBean != null && pageBean.isPagination())
- PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
-
- Object list = args.proceed();
-
- if(null != pageBean && pageBean.isPagination()){
- PageInfo pageInfo = new PageInfo((List) list);
- pageBean.setTotal((int) pageInfo.getTotal());
- }
- return list;
- }
-
- }
2.2 工具类
- package com.YU.utils;
-
- import javax.servlet.http.HttpServletRequest;
- import java.io.Serializable;
- import java.util.Map;
-
- public class PageBean implements Serializable {
-
- private static final long serialVersionUID = 2422581023658455731L;
-
- //页码
- private int page=1;
- //每页显示记录数
- private int rows=10;
- //总记录数
- private int total=0;
- //是否分页
- private boolean isPagination=true;
- //上一次的请求路径
- private String url;
- //获取所有的请求参数
- private Map
map; -
- public PageBean() {
- super();
- }
-
- //设置请求参数
- public void setRequest(HttpServletRequest req) {
- String page=req.getParameter("page");
- String rows=req.getParameter("rows");
- String pagination=req.getParameter("pagination");
- this.setPage(page);
- this.setRows(rows);
- this.setPagination(pagination);
- this.url=req.getContextPath()+req.getServletPath();
- this.map=req.getParameterMap();
- }
- public String getUrl() {
- return url;
- }
-
- public void setUrl(String url) {
- this.url = url;
- }
-
- public Map
getMap() { - return map;
- }
-
- public void setMap(Map
map) { - this.map = map;
- }
-
- public int getPage() {
- return page;
- }
-
- public void setPage(int page) {
- this.page = page;
- }
-
- public void setPage(String page) {
- if(null!=page&&!"".equals(page.trim()))
- this.page = Integer.parseInt(page);
- }
-
- public int getRows() {
- return rows;
- }
-
- public void setRows(int rows) {
- this.rows = rows;
- }
-
- public void setRows(String rows) {
- if(null!=rows&&!"".equals(rows.trim()))
- this.rows = Integer.parseInt(rows);
- }
-
- public int getTotal() {
- return total;
- }
-
- public void setTotal(int total) {
- this.total = total;
- }
-
- public void setTotal(String total) {
- this.total = Integer.parseInt(total);
- }
-
- public boolean isPagination() {
- return isPagination;
- }
-
- public void setPagination(boolean isPagination) {
- this.isPagination = isPagination;
- }
-
- public void setPagination(String isPagination) {
- if(null!=isPagination&&!"".equals(isPagination.trim()))
- this.isPagination = Boolean.parseBoolean(isPagination);
- }
-
- /**
- * 获取分页起始标记位置
- * @return
- */
- public int getStartIndex() {
- //(当前页码-1)*显示记录数
- return (this.getPage()-1)*this.rows;
- }
-
- /**
- * 末页
- * @return
- */
- public int getMaxPage() {
- int totalpage=this.total/this.rows;
- if(this.total%this.rows!=0)
- totalpage++;
- return totalpage;
- }
-
- /**
- * 下一页
- * @return
- */
- public int getNextPage() {
- int nextPage=this.page+1;
- if(this.page>=this.getMaxPage())
- nextPage=this.getMaxPage();
- return nextPage;
- }
-
- /**
- * 上一页
- * @return
- */
- public int getPreivousPage() {
- int previousPage=this.page-1;
- if(previousPage<1)
- previousPage=1;
- return previousPage;
- }
-
- @Override
- public String toString() {
- return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
- + "]";
- }
- }
- package com.YU.biz;
-
- import com.YU.model.HBook;
- import com.YU.utils.PageBean;
-
- import java.util.List;
-
- public interface HBookbiz {
- int deleteByPrimaryKey(Integer bid);
-
- int insert(HBook record);
-
- int insertSelective(HBook record);
-
- HBook selectByPrimaryKey(Integer bid);
-
- int updateByPrimaryKeySelective(HBook record);
-
- int updateByPrimaryKey(HBook record);
-
- List
listPager(HBook hBook, PageBean pageBean); - }
注:
这个方法为查询返回列表方法,包含分页,因为切面类对其进行切面,所以在命名时,必须以Pager结尾
- <select id="selectBycon" resultType="com.YU.model.HBook" parameterType="com.YU.model.HBook" >
- select
- <include refid="Base_Column_List" />
- from t_mvc_book
- <where>
- <if test="bname != null">
- and bname like concat('%',#{bname},'%')
- if>
- where>
- select>
List selectBycon(HBook hBook);
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- 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-4.3.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
-
- <context:component-scan base-package="com.YU"/>
-
-
- <mvc:annotation-driven />
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView">property>
- <property name="prefix" value="/WEB-INF/jsp/"/>
- <property name="suffix" value=".jsp"/>
- bean>
-
-
-
-
- <aop:aspectj-autoproxy/>
- beans>
- package com.YU.tag;
-
- import java.io.IOException;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.Set;
-
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.JspWriter;
- import javax.servlet.jsp.tagext.BodyTagSupport;
-
- import com.YU.utils.PageBean;
-
- public class PageTag extends BodyTagSupport{
- private PageBean pageBean;// 包含了所有分页相关的元素
-
- public PageBean getPageBean() {
- return pageBean;
- }
-
- public void setPageBean(PageBean pageBean) {
- this.pageBean = pageBean;
- }
-
- @Override
- public int doStartTag() throws JspException {
- // 没有标签体,要输出内容
- JspWriter out = pageContext.getOut();
- try {
- out.print(toHTML());
- } catch (IOException e) {
- e.printStackTrace();
- }
- return super.doStartTag();
- }
-
- private String toHTML() {
- StringBuffer sb = new StringBuffer();
- // 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
- // 上一次请求的URL
- sb.append(");
- sb.append(" ");
- // 上一次请求的参数
- Map
paramMap = pageBean.getMap(); - if(paramMap != null && paramMap.size() > 0) {
- Set
> entrySet = paramMap.entrySet(); - for (Entry
entry : entrySet) { - // 参数名
- String key = entry.getKey();
- // 参数值
- for (String value : entry.getValue()) {
- // 上一次请求的参数,再一次组装成了新的Form表单
- // 注意:page参数每次都会提交,我们需要避免
- if(!"page".equals(key)) {
- sb.append(" ");
- }
- }
- }
- }
- sb.append("");
-
- // 分页条
- sb.append("
"
); - sb.append("
- );
- sb.append(" href='javascript:gotoPage(1)'>首页");
- sb.append("
- );
- sb.append(" href='javascript:gotoPage("+pageBean.getPreivousPage()+")'><");// less than 小于号
- // sb.append("
- 1
"); - // sb.append("
- 2
"); - sb.append("
- "
+pageBean.getPage()+""); - sb.append("
- >
"); - sb.append("
- 尾页
"); - sb.append("
- 到第);
- sb.append(" type='text' id='skipPage' name='' />页");
- sb.append("
- );
- sb.append(" href='javascript:skipPage()'>确定");
- sb.append("
- 共"
+pageBean.getTotal()+"条"); - sb.append("");
-
- // 分页执行的JS代码
- sb.append("");
-
- return sb.toString();
- }
- }
- "1.0" encoding="UTF-8" ?>
-
- <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
- version="2.0">
-
- <description>YU 1.1 core librarydescription>
- <display-name>YU coredisplay-name>
- <tlib-version>1.1tlib-version>
- <short-name>YUshort-name>
- <uri>http://jsp.veryedu.cnuri>
-
-
- <tag>
- <name>pagename>
- <tag-class>com.YU.tag.PageTagtag-class>
- <body-content>JSPbody-content>
- <attribute>
- <name>pageBeanname>
- <required>truerequired>
- <rtexprvalue>truertexprvalue>
- attribute>
- tag>
-
- taglib>
- package com.YU.web;
-
- import com.YU.biz.HBookbiz;
- import com.YU.model.HBook;
- import com.YU.utils.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.List;
-
- /**
- * @author YU
- * @create 2023-09-07 16:07
- */
- @Controller
- @RequestMapping("book")
- public class HbookController {
-
- @Autowired
- private HBookbiz hBookbiz;
-
- //增加
- @RequestMapping("/add")
- public String add(HBook hBook){
- hBookbiz.insertSelective(hBook);
- return "redirect:/book/list";
- }
- //删除
- @RequestMapping("/del/{bid}")
- public String del(@PathVariable("bid")Integer bid){
- hBookbiz.deleteByPrimaryKey(bid);
- return "redirect:/book/list";
- }
- //修改
- @RequestMapping("/edit")
- public String edit(HBook hBook){
- hBookbiz.updateByPrimaryKeySelective(hBook);
- return "redirect:list";
- }
- //查询
- @RequestMapping("/list")
- public String list(HBook hBook, HttpServletRequest request){
- // hbook用来接收前台传递后台的参数
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- List
hBooks = hBookbiz.listPager(hBook, pageBean); - request.setAttribute("lst",hBooks);
- request.setAttribute("pageBean",pageBean);
- return "book/list";
- }
- //数据回显
- @RequestMapping("/preSave")
- public String preSave(HBook hBook, Model model){
- if(hBook !=null && hBook.getBid()!=null && hBook.getBid()!=0){
- HBook b = hBookbiz.selectByPrimaryKey(hBook.getBid());
- model.addAttribute("b",b);
- }
- return "book/edit";
- }
- }
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <link
- href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
- rel="stylesheet">
- <script
- src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js">script>
- <title>博客列表title>
- <style type="text/css">
- .page-item input {
- padding: 0;
- width: 40px;
- height: 100%;
- text-align: center;
- margin: 0 6px;
- }
-
- .page-item input, .page-item b {
- line-height: 38px;
- float: left;
- font-weight: 400;
- }
-
- .page-item.go-input {
- margin: 0 10px;
- }
- style>
- head>
- <body>
- <form class="form-inline"
- action="${pageContext.request.contextPath }/book/list" method="get">
- <div class="form-group mb-2">
- <input type="text" class="form-control-plaintext" name="cname"
- placeholder="请输入班级名称">
-
-
- <%-- <input name="pagination" value="false" type="hidden">--%>
- div>
- <button type="submit" class="btn btn-primary mb-2">查询button>
- <a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book/preSave">新增a>
- form>
-
- <table class="table table-striped">
- <thead>
- <tr>
- <th scope="col">书籍IDth>
- <th scope="col">书籍名称th>
- <th scope="col">书籍价格th>
- <%-- <th scope="col">班级图片th>--%>
- <th scope="col">操作th>
- tr>
- thead>
- <tbody>
- <c:forEach var="b" items="${lst }">
- <tr>
- <td>${b.bid }td>
- <td>${b.bname }td>
- <td>${b.price }td>
- <td>
- <a href="${pageContext.request.contextPath }/book/preSave?bid=${b.bid}">修改a>
- <a href="${pageContext.request.contextPath }/book/del/${b.bid}">删除a>
- td>
- tr>
- c:forEach>
- tbody>
- table>
- <z:page pageBean="${pageBean }">z:page>
- ${pageBean }
- body>
- html>
- <body>
- <form action="${pageContext.request.contextPath }/${empty b ? 'book/add' : 'book/edit'}" method="post">
- cid:<input type="text" name="bid" value="${b.bid }"><br>
- bname:<input type="text" name="bname" value="${b.bname }"><br>
- price:<input type="text" name="price" value="${b.price }"><br>
- <input type="submit">
- form>
- body>
感谢各位大大的收看,各位的支持和三连是博主更新的动力,感谢谢谢谢!!!!