Spring Boot 中这个默认视图名有点意思,看懂直呼内行内行!

Spring Boot第4章Spring Boot视图技术 第4章 视图技术4.1 Spring Boot支持的视图技术4.2 Thymeleaf基本语法4.3 Thymeleaf基本使用4.4 使用Thymeleaf完成数据的页面展示 4.1 Spring Boot支持的视图技术 Spring Boot模板引擎技术: (1)FreeMarker (2)Groovy (3)Thymeleaf (4)Mustache Spring Boot不太支持常用的JS... 阅读详情

今日分享开始啦,请大家多多指教~

在 Spring Boot 项目中,有的时候我们想返回一段 JSON,结果却忘了写 @ResponseBody 注解,像下面这样:

@Controller
public class HelloController {
    @GetMapping("/01")
    public void hello() {
        System.out.println("01");
    }
}

这个时候当项目跑起来,肯定会报错,具体报什么错,则要看用的什么视图解析器,如果用了 Freemarker,你可能会看到如下错误:在这里插入图片描述
这个错误是说陷入到循环调用中了。
如果用了 Thymeleaf,你可能会看到如下错误:在这里插入图片描述
这个是说一个名叫 01 的视图不存在。

我只是少加了一个 @ResponseBody 注解而已,为什么用不同的视图解析器会报不同的错误?并且这些错误实在看不出和 @ResponseBody 注解有什么关联。

1.方法入口

  • SpringMVC 源码分析之 DispatcherServlet

在这篇文章中,有一个小小细节,就是在 doDispatch 方法中,有如下一段代码:

applyDefaultViewName(processedRequest, mv);

当这段代码执行的时候,接口方法已经通过反射调用完成了,并且将返回值封装成了一个 ModelAndView 对象(如果接口方法用到了 @ResponseBody 注解,则此时拿到的 ModelAndView 对象为 null),但是这个时候的 ModelAndView 对象还没有渲染,此时会调用 applyDefaultViewName 方法去判断返回的 ModelAndView 对象中有没有 view,如果没有,则给出一个默认的视图名。

这行代码就是切入点,接下来我们就来分析一下 applyDefaultViewName 方法。

2.applyDefaultViewName

private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws Exception {
 if (mv != null && !mv.hasView()) {
  String defaultViewName = getDefaultViewName(request);
  if (defaultViewName != null) {
   mv.setViewName(defaultViewName);
  }
 }
}

可以看到,这里的判断逻辑很简单,首先检查 mv 是否为 null(如果用户添加了 @ResponseBody 注解,mv 就为 null),然后去判断 mv 中是否包含视图,如果不包含视图,则调用 getDefaultViewName 方法去获取默认的视图名,并将获取到的默认视图名交给 mv。

3.getDefaultViewName

@Nullable
protected String getDefaultViewName(HttpServletRequest request) throws Exception {
 return (this.viewNameTranslator != null ? this.viewNameTranslator.getViewName(request) : null);
}

这里涉及到一个新的组件 viewNameTranslator,如果 viewNameTranslator 不为 null,则调用其 getViewName 方法获取默认的视图名。

viewNameTranslator 其实就是 RequestToViewNameTranslator,我们一起来看下:

public interface RequestToViewNameTranslator {
 @Nullable
 String getViewName(HttpServletRequest request) throws Exception;
}

这个接口很简单,里边就一个方法 getViewName 方法来返回视图名称。在 SpringMVC 中,RequestToViewNameTranslator 接口只有一个默认的实现类 DefaultRequestToViewNameTranslator,我们来看下实现类中的 getViewName 方法:

@Override
public String getViewName(HttpServletRequest request) {
 String path = ServletRequestPathUtils.getCachedPathValue(request);
 return (this.prefix + transformPath(path) + this.suffix);
}
@Nullable
protected String transformPath(String lookupPath) {
 String path = lookupPath;
 if (this.stripLeadingSlash && path.startsWith(SLASH)) {
  path = path.substring(1);
 }
 if (this.stripTrailingSlash && path.endsWith(SLASH)) {
  path = path.substring(0, path.length() - 1);
 }
 if (this.stripExtension) {
  path = StringUtils.stripFilenameExtension(path);
 }
 if (!SLASH.equals(this.separator)) {
  path = StringUtils.replace(path, SLASH, this.separator);
 }
 return path;
}

在 getViewName 方法中,首先提取出来当前请求路径,如果请求地址是 http://localhost:XX80/01,那么这里提取出来的路径就是 /01,然后通过 transformPath 方法对路径进行处理,再分别加上前后缀后返回,默认的前后缀都是空字符串(如有需要,也可以自行配置)。

transformPath 则主要干了如下几件事:

  1. 去掉路径开始的 /。
  2. 去掉路径结尾的 /。
  3. 如果请求路径有扩展名,则去掉扩展名,例如请求路径是 /01.txt,经过这一步处理后,就变成了 /01。
  4. 如果 separator 与 SLASH不同,则替换原来的分隔符(默认是相同的)。

好了,经过这一波处理后,正常情况下,我们就拿到了一个新的视图名,这个新的视图名就是你的请求路径。

例如请求路径是 http://localhost:XX80/01,那么获取到的默认视图名就是 01。

现在大家就知道了,在没有写 @ResponseBody 的情况下,SpringMVC 会自动提取出一个默认的视图名,并且根据这个视图名去查找视图。

4.问题分析

要搞清楚这个问题,需要大家对视图解析器有一定了解:

  • SpringMVC 九大组件之 ViewResolver 深入分析
  • SpringMVC 中如何同时存在多个视图解析器

看完视图解析器的分析之后,接下来的内容就很好理解了。

4.1 Freemarker

先来看使用了 Freemarker 后为什么报循环调用的错。

根据前面两篇文章的分析,现在我们在 Spring Boot 中默认使用的视图解析器是 ContentNegotiatingViewResolver,在这个视图解析器中会首先选出所有候选的 View,由于我们的代码中并不存在一个名为 01 的 Freemarker 视图(如果刚好存在一个名为 01 的 Freemarker 视图就不会报错了,就直接将该视图展示出来了),而 FreeMarkerViewResolver 的父类 UrlBasedViewResolver 中的 loadView 方法在加载视图的时候,会去检查视图是否存在,结果发现视图吧不存在,导致最终返回 null。所以当 01 这个视图不存在时,最终负责处理该视图的并不是 FreeMarkerViewResolver,而是否则兜底的 InternalResourceViewResolver,该视图解析器最终构建出来的视图就是 InternalResourceView。

InternalResourceView 在最终渲染之前,会有一个预处理,代码如下:

protected String prepareForRendering(HttpServletRequest request, HttpServletResponse response)
  throws Exception {
 String path = getUrl();
 Assert.state(path != null, "'url' not set");
 if (this.preventDispatchLoop) {
  String uri = request.getRequestURI();
  if (path.startsWith("/") ? uri.equals(path) : uri.equals(StringUtils.applyRelativePath(uri, path))) {
   throw new ServletException("Circular view path [" + path + "]: would dispatch back " +
     "to the current handler URL [" + uri + "] again. Check your ViewResolver setup! " +
     "(Hint: This may be the result of an unspecified view, due to default view name generation.)");
  }
 }
 return path;
}

这个地方的 getUrl 参数是在 buildView 方法中设置的(具体参见:SpringMVC 九大组件之 ViewResolver 深入分析),它返回的视图的完整路径名,也就是 prefix + viewName + suffix,如果这个路径和当前请求路径一致,就抛出异常,抛出的异常就是我们一开始截图中看到的异常(其实异常中也说了,这个问题可能是由于自动生成 viewName 导致的)。

这就是为什么当我们使用 Freemarker 依赖时报循环请求的异常。

4.2 Thymeleaf

再来看 Thymeleaf,使用 Thymeleaf 时报的异常是模版不存在。

首先我们找到异常抛出的位置是在
TemplateManager#resolveTemplate 方法中:

private static TemplateResolution resolveTemplate(
        final IEngineConfiguration configuration,
        final String ownerTemplate,
        final String template,
        final Map<String, Object> templateResolutionAttributes,
        final boolean failIfNotExists) {
    for (final ITemplateResolver templateResolver : configuration.getTemplateResolvers()) {
        final TemplateResolution templateResolution =
                templateResolver.resolveTemplate(configuration, ownerTemplate, template, templateResolutionAttributes);
        if (templateResolution != null) {
            return templateResolution;
        }
    }
    if (!failIfNotExists) {
        return null;
    }
    throw new TemplateInputException(
            "Error resolving template [" + template + "], " +
            "template might not exist or might not be accessible by " +
            "any of the configured Template Resolvers");
}

可以看到,这个方法在执行的过程中如果没能提前返回,最终就会抛出异常,抛出的异常也就是我们在控制台所看到的异常。执行到这一步的原因是前面获取到的 templateResolution 为 null,并且 failIfNotExists 参数为 true,failIfNotExists 参数在调用的时候固定传入,这个没啥好说的,问题的核心在于获取到的 templateResolution 是否为 null。

templateResolution 则是在 AbstractTemplateResolver#resolveTemplate 方法中获取到的,如下:

public final TemplateResolution resolveTemplate(
        final IEngineConfiguration configuration,
        final String ownerTemplate, final String template,
        final Map<String, Object> templateResolutionAttributes) {
    if (!computeResolvable(configuration, ownerTemplate, template, templateResolutionAttributes)) {
        return null;
    }
    final ITemplateResource templateResource = computeTemplateResource(configuration, ownerTemplate, template, templateResolutionAttributes);
    if (templateResource == null) {
        return null;
    }
    if (this.checkExistence && !templateResource.exists()) { // will only check if flag set to true
        return null;
    }
    return new TemplateResolution(
            templateResource,
            this.checkExistence,
            computeTemplateMode(configuration, ownerTemplate, template, templateResolutionAttributes),
            this.useDecoupledLogic,
            computeValidity(configuration, ownerTemplate, template, templateResolutionAttributes));
    
}

可以看到,在拿到 templateResource 之后,会调用 templateResource.exists() 方法判断资源是否存在,也就是相应的模版文件是否存在,如果不存在就会返回 null,进而导致上一个方法抛出异常。

小结

主要和小伙伴们分享了一下 SpringMVC 中默认视图名的问题。

今日份分享已结束,请大家多多包涵和指点!

Spring Boot默认异常处理 在日常的 Web 开发中,会经常遇到大大小小的异常,此时往往需要一个统一的异常处理机制,来保证客户端能接收较为友好的提示。Spring Boot 同样提供了一套默认的异常处理机制,本节将对它进行详细的介绍。Spring Boot 默认异常处理机制 Spring Boot 提供了一套默认的异常处理机制,一旦程序中出现了异常,Spring Boot 会自动识别客户端的类型(浏览器客户端或机器客户端),并根据客户端的不同,以不同的形式展示异常信息。图1:Spring Boot 默认错误白页下面,我们依次对这四个组 阅读详情

相关推荐

Spring Boot:Web开发之视图模板技术的整合

Spring Boot Web开发之视图模板技术的整合介绍

啊Q老师 6773

SpringBoot

概述 SpringBoot呢,就是一个javaweb的开发框架,和SpringMVC类似,对比其他javaweb框架的好处,官方说是简化开发,约定大于配置, you can "just run",能迅速的开发web应用,几行代码开发一个http接口。 Java企业级应用->J2EE->spring->springboot的过程。 实操 hello word 自动创建目录结构: 可以直接将项目 package ,在命令行 用 java -jar 运行 自动装配原理 .

不贪吃的猪 440

Spring Boot(24)——使用Freemarker视图

使用Freemarker视图 Spring Boot默认对Freemarker也有支持,需哟使用Freemarker的第一步是加入Freemarker的依赖。 <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId>...

Elim的博客 2465

SpringBoot中常见的注解说明(包含使用实例)详细(一)

Spring Boot是一个快速开发框架,快速的将一些常用的第三方依赖整合(通过Maven子父亲工程的方式),简化xml配置,全部采用注解形式,内置Http服务器(Jetty和Tomcat),最终以Java应用程序进行执行。

全栈技术分享,项目分享,资料分享 586

Spring Boot(23)——使用Jsp视图

使用Jsp视图 使用内置的Tomcat容器时如果需要使用Jsp视图,需要在pom.xml中添加如下依赖。 <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <...

Elim的博客 1272

Oracle EBS报表开发入门:Report Builder安装避坑指南(Win10/11兼容版)

本文详细介绍了在Windows 10/11系统上成功安装和配置Oracle Report Builder的完整避坑指南。通过修改系统兼容性、解决虚拟内存报错、正确设置NLS_LANG和TNS连接等关键步骤,确保开发环境稳定运行。同时,阐述了Report Builder与BI Publisher在现代Oracle EBS报表开发中的协作定位与工作流,帮助开发者高效搭建报表开发环境。

d6e7f8的博客 753

SpringMvc 源码分析 (RequestMappingHandlerAdapter 的使用细节) (十)

SpringMvc 源码分析之 RequestMappingHandlerAdapter 使用细节中的返回值处理。

959 696

论文阅读:Visual Relationship Detection with Language Priors

Visual Relationship Detection with Language Priors(ECCV2016) 文章   尽管大多数的relationship并不常见,但是它们的object和predicate却更频繁地独立出现。paper用这个insight分别独立训练训练object和predicate的模型,然后再进行组合来预测relationship。Visual relatio...

Kivee的博客 2877

60--SpringMVC返回视图

1. 引 前两节分析了HandlerAdapter的handler方法过程,接下来回到doDispatch方法里来看其后续处理工作都还有哪些: 1.1 applyDefaultViewName设置默认视图名 private void applyDefaultViewName(HttpServletRequest request, @Nullable ModelAndView mv) throws ...

闲来也无事 875

数据工程师——ETL

文章摘要 ETL(数据抽取、转换、加载)是数据处理的核心流程,负责将分散数据源整合为高质量数据。ETL与ELT的主要区别在于转换步骤顺序,分别适用于不同规模数据场景。数据仓库通过ETL从多个数据源集成数据,支持分析决策。维度建模中的事实表记录业务指标,维度表提供上下文信息。缓慢变化维度(SCD)处理随时间变化的维度数据,常见类型包括直接覆盖型、新增版本型等。数据清洗解决数据缺失、重复、错误等问题,确保数据质量。数据血缘记录数据流转路径,便于问题排查和影响分析。常用ETL工具如Kettle通过转换和作业实现数

weixin_45729710的博客 1558

QProgressBar:常用接口、样式表及自定义进度条实现

在Qt开发中,QProgressBar 是一个非常常用的控件,用于显示任务的进度。无论是文件下载、数据处理还是其他耗时操作,QProgressBar 都能直观地展示当前进度。本文将详细介绍QProgressBar 的使用方法,包括常用接口、样式表设置,并额外补充一个自定义进度条的C++实现。

u011186532的专栏 1012

spring boot viewResolver

spring mvc允许注册多个viewResolver。spring mvc通过循环调用viewResolver解析View。View不为空则直接返回。相应代码在DispatcherServlet中 protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest re

迷然 3252

极智嘉嵌入式面试题及参考答案

IIC(Inter-Integrated Circuit)即集成电路总线,是一种由 PHILIPS 公司开发的两线式串行总线,用于连接微控制器及其外围设备。它仅使用两根线,即串行数据线 SDA 和串行时钟线 SCL,就能实现多个设备之间的通信,具有简单、高效、占用资源少等优点,广泛应用于各种嵌入式系统中。

大模型大数据攻城狮的专栏 916

Spring Boot中关于SpringMVC视图解析

一、注解说明 在spring-boot+spring mvc 的项目中,有些时候我们需要自己配置一些项目的设置,就会涉及到这三个,那么,他们之间有什么关系呢? 首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法。 所以有以下几种使用方式: @E...

wang5421488的博客 1541

手把手教你学Simulink--基于Simulink的近端策略优化(PPO)路径规划仿真建模

本文详细介绍了如何利用Simulink进行近端策略优化(PPO)路径规划的仿真建模。首先,文章概述了PPO路径规划的特点和挑战,强调了其在连续或离散动作空间问题中的高效性和稳定性。接着,列出了所需的工具和环境,包括MATLAB/Simulink、Reinforcement Learning Toolbox等。随后,文章分步骤详细讲解了从定义任务需求到验证与分析的整个仿真建模过程,包括创建Simulink项目、集成智能体模型、构建环境模型、编写PPO路径规划逻辑、将逻辑集成到Simulink模型中以及最终的验

MHD0815的博客 165

YOLO11 锚框机制全解析:从改进 K-means 聚类到自适应优化,附多场景实战(附代码)

摘要 YOLO11的锚框机制采用"自适应、动态化、场景感知"的设计理念,通过数据驱动的锚框生成、多尺度感知分配和实时优化策略,显著提升目标检测性能。相较于早期YOLO版本,YOLO11的锚框完全基于训练集目标分布自适应生成,并引入智能分配策略,使不同尺寸目标获得最优匹配。技术架构包含自适应锚框生成、多尺度分配器和动态优化模块,通过改进的K-means聚类和交并比计算实现精准匹配。YOLO11锚框机制在检测精度、训练稳定性和场景适应性方面均有显著提升,为复杂场景下的目标检测提供更优解决方案

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 1318

Spring Boot视图技术

Spring Boot视图技术Spring Boot支持的视图技术Thymeleaf基本语法常用标签标准表达式变量表达式选择变量表达式消息表达式链接表达式片段表达式Thymeleaf基本使用Thymeleaf模板基本设置静态资源访问使用Thymeleaf完成数据的页面展示 Spring Boot支持的视图技术 前端引擎技术的出现,使前端开发人员无须关注后端业务的具体实现,值关注自己呈现的效果即可,从而解决了前端代码错综复杂的问题,实现了前后端分离开发。Spring Boot对很多模块引擎技术提供了支持,具体

qq_50834939的博客 1761

S7-200SMART 的运动控制(一)向导配置具体步骤(图文)

S7-200SMART 的运动控制(一)向导配置具体步骤(图文)

Robot_PLC_HMI_Automation 3849

spring-boot入门(三)使用HTML视图

spring-boot入门(二)前后端分离使用HTML作为展示视图前后端分离能使项目整体开发效率提高,后端无需再像写jsp一样将原本的html改写为jsp,加入jstl表达式或者一些java代码,这对于前端或者后端来说都是一件痛苦的事情。要做到真正的前后端分离,后端只需提供相应的restful接口返回前端请求的数据,同时前后端应用也可以完全分开。

lan墨的博客 2万+

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Spring Boot实践——SpringMVC视图解析

一、注解说明   在spring-boot+spring mvc 的项目中,有些时候我们需要自己配置一些项目的设置,就会涉及到这三个,那么,他们之间有什么关系呢? 首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩...

chihe8021的博客 230

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

spring boot设置默认访问网页

第一步引入依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> ...

旅人的博客 595

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot(Spring Boot视图技术)

第四章、Spring Boot视图技术4.1 Spring Boot支持的视图技术小提示4.2 Thymeleaf 基本语法4.2.1 常用标签小提示4.2.2 标准表达式1.变量表达式2.选择变量表达式3.消息表达式4.链接表达式5.片段表达式4.3 Thymeleaf 基本使用4.3.1 Thymeleaf模板基本配置4.3.2 静态资源的访问4.4 配置国际化页面1.编写国际化文件2.编写配置文件3.定制区域信息解析器 在一个Web应用中,通常会采用MVC设计模式实现对应的模型、视图、和控制器,其中,

qq_42462016的博客 519

springboot applications.yml配置HTML视图解析器_Spring Boot实践——SpringMVC视图解析

一、注解说明在spring-boot+spring mvc 的项目中,有些时候我们需要自己配置一些项目的设置,就会涉及到这三个,那么,他们之间有什么关系呢? 首先,@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法。所以有以下几种使用方式:@Enab...

weixin_39522927的博客 1440
上一篇: 40 图|我用 M1 玩转 SpringCloud
下一篇: 【SpringSecurity系列】自定义认证逻辑
「已注销」
博客等级 码龄6年 9粉丝 24原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值