SpringMVC学习笔记(springmvc基础知识)

  本篇文章为你整理了SpringMVC学习笔记(springmvc基础知识)的详细内容,包含有springmvc入门实例 springmvc基础知识 springmvc快速入门 springmvc实例教程 SpringMVC学习笔记,希望能帮助你了解 SpringMVC学习笔记。

   project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"

   modelVersion 4.0.0 /modelVersion

   groupId priv.dandelion /groupId

   artifactId 08_ssm /artifactId

   version 1.0-SNAPSHOT /version

   packaging war /packaging

   dependencies

   dependency

   groupId org.springframework /groupId

   artifactId spring-webmvc /artifactId

   version 5.2.10.RELEASE /version

   /dependency

   dependency

   groupId org.springframework /groupId

   artifactId spring-jdbc /artifactId

   version 5.2.10.RELEASE /version

   /dependency

   dependency

   groupId org.springframework /groupId

   artifactId spring-test /artifactId

   version 5.2.10.RELEASE /version

   /dependency

   dependency

   groupId org.mybatis /groupId

   artifactId mybatis /artifactId

   version 3.5.6 /version

   /dependency

   dependency

   groupId org.mybatis /groupId

   artifactId mybatis-spring /artifactId

   version 1.3.0 /version

   /dependency

   dependency

   groupId mysql /groupId

   artifactId mysql-connector-java /artifactId

   version 5.1.47 /version

   /dependency

   dependency

   groupId com.alibaba /groupId

   artifactId druid /artifactId

   version 1.1.16 /version

   /dependency

   dependency

   groupId junit /groupId

   artifactId junit /artifactId

   version 4.12 /version

   scope test /scope

   /dependency

   dependency

   groupId javax.servlet /groupId

   artifactId javax.servlet-api /artifactId

   version 3.1.0 /version

   scope provided /scope

   /dependency

   dependency

   groupId com.fasterxml.jackson.core /groupId

   artifactId jackson-databind /artifactId

   version 2.9.0 /version

   /dependency

   /dependencies

   build

   plugins

   plugin

   groupId org.apache.tomcat.maven /groupId

   artifactId tomcat7-maven-plugin /artifactId

   version 2.1 /version

   configuration

   port 80 /port

   path / /path

   /configuration

   /plugin

   /plugins

   /build

   /project

  

 

 

  
@PropertySource("classpath:jdbc.properties")

  @Import({JdbcConfig.class,MybatisConfig.class})

  // 开启事务

  @EnableTransactionManagement

  public class SpringConfig {

  

 

 

  
DruidDataSource dataSource = new DruidDataSource();

   dataSource.setDriverClassName(driver);

   dataSource.setUrl(url);

   dataSource.setUsername(username);

   dataSource.setPassword(password);

   return dataSource;

   // 事务控制管理器,数据源使用自动装配(由Spring管理)

   @Bean

   public PlatformTransactionManager transactionManager(DataSource dataSource){

   DataSourceTransactionManager ds = new DataSourceTransactionManager();

   ds.setDataSource(dataSource);

   return ds;

  

 

 

  
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){

   SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

   factoryBean.setDataSource(dataSource);

   factoryBean.setTypeAliasesPackage("priv.dandelion.entity");

   return factoryBean;

   @Bean

   public MapperScannerConfigurer mapperScannerConfigurer(){

   MapperScannerConfigurer msc = new MapperScannerConfigurer();

   msc.setBasePackage("priv.dandelion.dao");

   return msc;

  

 

 

  
web 项目入口配置类

  

public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {

 

   //加载Spring配置类

   protected Class ? [] getRootConfigClasses() {

   return new Class[]{SpringConfig.class};

   //加载SpringMVC配置类

   protected Class ? [] getServletConfigClasses() {

   return new Class[]{SpringMvcConfig.class};

   //设置SpringMVC请求地址拦截规则

   protected String[] getServletMappings() {

   return new String[]{"/"};

   //设置post请求中文乱码过滤器

   @Override

   protected Filter[] getServletFilters() {

   CharacterEncodingFilter filter = new CharacterEncodingFilter();

   filter.setEncoding("utf-8");

   return new Filter[]{filter};

  

 

  
insert into `tbl_book`(`id`,`type`,`name`,`description`) values (1,计算机理论,Spring实战 第五版,Spring入门经典教程,深入理解Spring原理技术内幕),(2,计算机理论,Spring 5核心原理与30个类手写实践,十年沉淀之作,手写Spring精华思想),(3,计算机理论,Spring 5设计模式,深入Spring源码刨析Spring源码中蕴含的10大设计模式),(4,计算机理论,Spring MVC+Mybatis开发从入门到项目实战,全方位解析面向Web应用的轻量级框架,带你成为Spring MVC开发高手),(5,计算机理论,轻量级Java Web企业应用实战,源码级刨析Spring框架,适合已掌握Java基础的读者),(6,计算机理论,Java核心技术 卷Ⅰ 基础知识(原书第11版),Core Java第11版,Jolt大奖获奖作品,针对Java SE9、10、11全面更新),(7,计算机理论,深入理解Java虚拟机,5个纬度全面刨析JVM,大厂面试知识点全覆盖),(8,计算机理论,Java编程思想(第4版),Java学习必读经典,殿堂级著作!赢得了全球程序员的广泛赞誉),(9,计算机理论,零基础学Java(全彩版),零基础自学编程的入门图书,由浅入深,详解Java语言的编程思想和核心技术),(10,市场营销,直播就这么做:主播高效沟通实战指南,李子柒、李佳奇、薇娅成长为网红的秘密都在书中),(11,市场营销,直播销讲实战一本通,和秋叶一起学系列网络营销书籍),(12,市场营销,直播带货:淘宝、天猫直播从新手到高手,一本教你如何玩转直播的书,10堂课轻松实现带货月入3W+);

  

 

 

  
// @Insert("insert into tbl_book values(null,#{type},#{name},#{description})")

   @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")

   public void save(Book book);

   @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")

   public void update(Book book);

   @Delete("delete from tbl_book where id = #{id}")

   public void delete(Integer id);

   @Select("select * from tbl_book where id = #{id}")

   public Book getById(Integer id);

   @Select("select * from tbl_book")

   public List Book getAll();

  

 

 

  
import org.springframework.beans.factory.annotation.Autowired;

  import org.springframework.stereotype.Service;

  import priv.dandelion.dao.BookDao;

  import priv.dandelion.entity.Book;

  import priv.dandelion.service.BookService;

  import java.util.List;

  @Service

  public class BookServiceImpl implements BookService {

   @Autowired

   private BookDao bookDao;

   @Override

   public boolean save(Book book) {

   bookDao.save(book);

   return true;

   @Override

   public boolean update(Book book) {

   bookDao.update(book);

   return true;

   @Override

   public boolean delete(Integer id) {

   bookDao.delete(id);

   return true;

   @Override

   public Book getById(Integer id) {

   return bookDao.getById(id);

   @Override

   public List Book getAll() {

   return bookDao.getAll();

  

 

 

  


@RunWith(SpringJUnit4ClassRunner.class)

 

  @ContextConfiguration(classes = SpringConfig.class)

  public class BookServiceTest {

  

 

  


@RunWith(SpringJUnit4ClassRunner.class)

 

  @ContextConfiguration(classes = SpringConfig.class)

  public class BookServiceTest {

   @Autowired

   private BookService bookService;

   @Test

   public void testGetById() {

   Book byId = bookService.getById(1);

   System.out.println(byId);

   @Test

   public void testGetAll() {

   List Book all = bookService.getAll();

   System.out.println(all);

  

 

  
多个相同的返回类型可能是不同操作,便于区分不同操作;另外,可以对code进行规定,如末位为0代表失败,为1代表成功

  
public static final Integer SAVE_OK = 20011;

   public static final Integer DELETE_OK = 20021;

   public static final Integer UPDATE_OK = 20031;

   public static final Integer GET_OK = 20041;

   public static final Integer SAVE_ERR = 20010;

   public static final Integer DELETE_ERR = 20020;

   public static final Integer UPDATE_ERR = 20030;

   public static final Integer GET_ERR = 20040;

  

 

 

  
boolean flag = bookService.save(book);

   return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR, flag);

   @PutMapping

   public Result update(@RequestBody Book book) {

   boolean flag = bookService.update(book);

   return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);

   @DeleteMapping("/{id}")

   public Result delete(@PathVariable Integer id) {

   boolean flag = bookService.delete(id);

   return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR, flag);

   @GetMapping("/{id}")

   public Result getById(@PathVariable Integer id) {

   Book book = bookService.getById(id);

   Integer code = book != null ? Code.GET_OK : Code.GET_ERR;

   String msg = book != null ? "" : "查询的数据不存在,请重试";

   return new Result(code, book, msg);

   @GetMapping

   public Result getAll() {

   List Book all = bookService.getAll();

   Integer code = all != null ? Code.GET_OK : Code.GET_ERR;

   String msg = all != null ? "" : "数据查询失败,请重试";

   return new Result(code, all, msg);

  

 

 

  
框架内部抛出的异常:因使用不合规导致

  数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)

  业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)

  表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)

  工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)

  
各级均可能出现异常,为保证统一处理,需要向上抛出,直至表现层统一处理

  关于MVC模式与三层架构的关系可以参考:三层架构

  
在表现层中创建统一异常处理类 ProjectExceptionAdvice

  不一定非要写在表现层对应的 controller 包下,但是一定要保证 SpringMVC 控制类的包扫描配置能扫描到异常处理器类

  3.2.2 使用步骤

  
设置指定异常的处理方案,功能等同于控制器方法,
出现异常后终止原始控制器执行,并转入当前方法执行

  
因为异常的种类有很多,如果每一个异常都对应一个@ExceptionHandler,那得写多少个方法来处理各自的异常,所以在处理异常之前,需要对异常进行一个分类

  
规范的用户行为产生的异常:如用户在页面输入内容的时候未按照指定格式进行数据填写,如在年龄框输入字符串

  不规范的用户行为操作产生的异常:如故意传递错误数据

  


// 继承RuntimeException,可以不做处理自动上抛

 

  public class SystemException extends RuntimeException{

   private Integer code;

   public SystemException(Integer code, String message) {

   super(message);

   this.code = code;

   public SystemException(Integer code, String message, Throwable cause) {

   super(message, cause);

   this.code = code;

   public Integer getCode() {

   return code;

   public void setCode(Integer code) {

   this.code = code;

  

 

  
业务异常(BusinessException)

  

public class BusinessException extends RuntimeException{

 

   private Integer code;

   public BusinessException(Integer code, String message) {

   super(message);

   this.code = code;

   public BusinessException(Integer code, String message, Throwable cause) {

   super(message, cause);

   this.code = code;

   public Integer getCode() {

   return code;

   public void setCode(Integer code) {

   this.code = code;

  

 

  
}catch (ArithmeticException ae){

   throw new SystemException(Code.SYSTEM_TIMEOUT_ERR, "服务器访问超时");

  

 

 

  


public static final Integer SYSTEM_ERR = 50001;

 

  public static final Integer SYSTEM_TIMEOUT_ERR = 50002;

  public static final Integer SYSTEM_UNKNOWN_ERR = 59999;

  public static final Integer BUSINESS_ERR = 60001;

  

 

  
@ExceptionHandler(SystemException.class)

   public Result doException(SystemException ex) {

   // 记录日志

   // 发送消息给运维

   // 邮件发送ex的对象给开发

   // 返回消息内容

   return new Result(ex.getCode(), null, ex.getMessage());

   // 拦截异常

   @ExceptionHandler(BusinessException.class)

   public Result doException(BusinessException ex) {

   // 记录日志

   // 发送邮件给开发

   // 返回消息内容

   return new Result(ex.getCode(), null, ex.getMessage());

   // 仍然保留,用于处理其他异常

   @ExceptionHandler(Exception.class)

   // 修改返回值类型,向前端返回异常信息

   public Result doException(Exception ex) {

   // 记录日志

   // 发送消息给运维

   // 邮件发送ex的对象给开发

   // 返回消息内容

   return new Result(Code.SYSTEM_UNKNOWN_ERR, null, "系统繁忙请稍后再试");

  

 

 

  
meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport"

   !-- 引入样式 --

   link rel="stylesheet" href="../plugins/elementui/index.css"

   link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css"

   link rel="stylesheet" href="../css/style.css"

   /head

   body

   div id="app"

   div

   h1 图书管理 /h1

   /div

   div

   div

   div

   el-input placeholder="图书名称" v-model="pagination.queryString" /el-input

   el-button @click="getAll()" 查询 /el-button

   el-button type="primary" @click="handleCreate()" 新建 /el-button

   /div

   el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row

   el-table-column type="index" align="center" label="序号" /el-table-column

   el-table-column prop="type" label="图书类别" align="center" /el-table-column

   el-table-column prop="name" label="图书名称" align="center" /el-table-column

   el-table-column prop="description" label="描述" align="center" /el-table-column

   el-table-column label="操作" align="center"

   template slot-scope="scope"

   el-button type="primary" size="mini" @click="handleUpdate(scope.row)" 编辑 /el-button

   el-button type="danger" size="mini" @click="handleDelete(scope.row)" 删除 /el-button

   /template

   /el-table-column

   /el-table

   !-- 新增标签弹层 --

   div

   el-dialog title="新增图书" :visible.sync="dialogFormVisible"

   el-form ref="dataAddForm" :model="formData" :rules="rules" label-position="right" label-width="100px"

   el-row

   el-col :span="12"

   el-form-item label="图书类别" prop="type"

   el-input v-model="formData.type"/

   /el-form-item

   /el-col

   el-col :span="12"

   el-form-item label="图书名称" prop="name"

   el-input v-model="formData.name"/

   /el-form-item

   /el-col

   /el-row

  
el-form ref="dataEditForm" :model="formData" :rules="rules" label-position="right" label-width="100px"

   el-row

   el-col :span="12"

   el-form-item label="图书类别" prop="type"

   el-input v-model="formData.type"/

   /el-form-item

   /el-col

   el-col :span="12"

   el-form-item label="图书名称" prop="name"

   el-input v-model="formData.name"/

   /el-form-item

   /el-col

   /el-row

   el-row

   el-col :span="24"

   el-form-item label="描述"

   el-input v-model="formData.description" type="textarea" /el-input

   /el-form-item

   /el-col

   /el-row

   /el-form

   div slot="footer"

   el-button @click="dialogFormVisible4Edit = false" 取消 /el-button

   el-button type="primary" @click="handleEdit()" 确定 /el-button

   /div

   /el-dialog

   /div

   /div

   /div

   /div

   /body

   !-- 引入组件库 --

   script src="../js/vue.js" /script

   script src="../plugins/elementui/index.js" /script

   script type="text/javascript" src="../js/jquery.min.js" /script

   script src="../js/axios-0.18.0.js" /script

   script

   var vue = new Vue({

   el: #app,

   data:{

   pagination: {},

   dataList: [],//当前页要展示的列表数据

   formData: {},//表单数据

   dialogFormVisible: false,//控制表单是否可见

   dialogFormVisible4Edit:false,//编辑表单是否可见

   rules: {//校验规则

   type: [{ required: true, message: 图书类别为必填项, trigger: blur }],

   name: [{ required: true, message: 图书名称为必填项, trigger: blur }]

   //钩子函数,VUE对象初始化完成后自动执行

   created() {

   this.getAll();

   methods: {

   //列表

   getAll() {

   //弹出添加窗口

   handleCreate() {

   //重置表单

   resetForm() {

   //添加

   handleAdd () {

   //弹出编辑窗口

   handleUpdate(row) {

   //编辑

   handleEdit() {

   // 删除

   handleDelete(row) {

   /script

   /html

  

 

 

  
protected void addResourceHandlers(ResourceHandlerRegistry registry) {

   registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");

   registry.addResourceHandler("/css/**").addResourceLocations("/css/");

   registry.addResourceHandler("/js/**").addResourceLocations("/js/");

   registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");

  

 

 

  
axios.get("/books").then((res)= {

   // 注意第二个data是实体类中封装的属性data,二者意义不同

   this.dataList = res.data.data;

  

 

 

  
Dao

  

@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")

 

  // @Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")

  public int save(Book book);

  @Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")

  public int update(Book book);

  @Delete("delete from tbl_book where id = #{id}")

  public int delete(Integer id);

  

 

  
拦截器概念:拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行

  
归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术

  拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强(取决于 web 服务器配置类中 SpringMVC 的访问内容设置)

  
需要 SpringMVC 配置类和已经配置好的Controller,笔者使用上面的 SSM 整合案例的代码进行演示

  5.2.2 拦截器开发

  
拦截器一般写在 controller 包下,一般只给 controller 用

  拦截器也可以写在其他位置,但是要保证 SpringMVC 配置类的包扫描可以扫描到

  
@Override

   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

   System.out.println("preHandle");

   return true;

   @Override

   public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

   System.out.println("postHandle");

   @Override

   public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

   System.out.println("afterCompletion");

  

 

 

  
此处写在了 SpringMvcSupport 中,注意配置类注解

  要保证 SpringMVC 配置类的包扫描可以扫描到

  
protected void addInterceptors(InterceptorRegistry registry) {

   // 使用到的两个参数均为可变参数,可以直接写多个,addResourceHandlers()中相同,不再赘述

   // registry.addInterceptor(projectInterceptor).addPathPatterns("/books", "/books/*");

   // 也可以采用这种形式,拦截/books,/books/*,/books/*/*...

   registry.addInterceptor(projectInterceptor).addPathPatterns("/books/**");

   @Override

   protected void addResourceHandlers(ResourceHandlerRegistry registry) {

   registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");

   registry.addResourceHandler("/css/**").addResourceLocations("/css/");

   registry.addResourceHandler("/js/**").addResourceLocations("/js/");

   registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");

  

 

 

  
preHandle() 返回 true 时,按照上面的执行顺序执行

  preHandle() 返回 true 时,中止原始操作的执行,原始操作后的拦截器操作也不执行

  
假设拦截内容为/book,当使用 Rest 风格时,GET /books 与 POST /book/1 不同,/book/1不会被拦截

  假设拦截内容为/book*,当使用 Rest 风格时,PUT /books/1 与 POST /book/1 都会被拦截

  
可以直接在 SpringMvcConfig 中继承 WebMvcConfigurer 接口,覆写相应方法,效果相同

  相比 SpringMvcSupport 具有一定侵入性

  
public void addInterceptors(InterceptorRegistry registry) {

   registry.addInterceptor(projectInterceptor).addPathPatterns("/books/**");

   @Override

   public void addResourceHandlers(ResourceHandlerRegistry registry) {

   registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");

   registry.addResourceHandler("/css/**").addResourceLocations("/css/");

   registry.addResourceHandler("/js/**").addResourceLocations("/js/");

   registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");

  

 

 

  5.3 拦截器参数

  拦截器代码见 5.2.2

  5.3.1 前置处理方法

  
request:请求对象,获取请求数据中的内容,如获取请求头的Content-Type

  

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

 

   String contentType = request.getHeader("Content-Type");

   System.out.println("preHandle..."+contentType);

   return true;

  

 

  
handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装。可以获取方法的相关信息

  

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

 

   HandlerMethod hm = (HandlerMethod)handler;

   String methodName = hm.getMethod().getName();//可以获取方法的名称

   System.out.println("preHandle..."+methodName);

   return true;

  

 

  
ModelAndView modelAndView:如果处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整,目前开发返回 JSON 数据较多,其使用率不高

  5.3.3 完成处理方法

  Exception ex:如果处理器执行过程中出现异常对象,可以针对异常情况进行单独处理,如表现层抛出的异常。现在已经有全局异常处理器类,所以该参数的使用率也不高。

  5.4 拦截器链运行顺序

  
拦截器链的运行顺序参照拦截器添加顺序为准

  当拦截器中出现对原始处理器的拦截,后面的拦截器均终止运行

  当拦截器运行中断,仅运行配置在前面的拦截器的 afterCompletion 操作

  以上就是SpringMVC学习笔记(springmvc基础知识)的详细内容,想要了解更多 SpringMVC学习笔记的内容,请持续关注盛行IT软件开发工作室。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: