springboot如何使用jsp/templates

一:如何使用jsp

1.springboot默认是不支持jsp的,要想用jsp的话,需要导一个插件,在pom.xml里添加依赖

<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
</dependency>

2.然后在src/main下面创建webapp文件夹 ,创建的时候右键项目,名字必须为webapp

3.在配置文件中上视图解析器:

4.然后在后台写个两个jsp跳转的方法,就可以了,over!

二:如何使用templates

templates文件夹下一般放置的是.html页面,当然也可以在里面创建各种文件夹存放不同的.html页面使用

thymeleaf有什么好处:
  因为thymeleaf是html格式的,可以本地打开。美工和开发人员都可以访问,美工打开的是静态页面,开发人员打开的是动态页面。
  
如何使用thymeleaf:
  pom.xml 添加spring-boot-starter-thymeleaf
  thymeleaf和jsp功能一样,不能同时存在。
  thymeleaf文件默认放在resources/templates目录下
  修改thymeleaf的目录:
  springboot默认配置文件中spring.thymeleaf.prefix
  新建html文档,默认是html5格式的
  如何声明th前缀:
  在html标签声明th前缀 xmlns:th="http://www.thymeleaf.org"

1.在pom.xml中把jsp依赖注掉,添加thymeleaf依赖;

扫描二维码关注公众号,回复: 4915704 查看本文章
        <!--<dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2.创建一个html文件,添加th命名空间,然后就可以从后台动态获取数据;

也是从四大域中获取数据,用session时就用${session.}(我这里后台传过来的是session,传过来什么写什么);

servletContext也是;传一个对象过来的话,就用对象点它的属性值,例如 ${user.userName}这种;

3.如果想修改默认的文件夹,可以在配置文件里进行修改:

   1)这种用${}的称为变量表达式:

其他地方不需要做修改,就ok了!这样就可以使用templates了。

还有几种声明方式:

2)*{}称为:选择表达式 从指定对象中选取变量值

<div th:object="${user1}" style="border: 2px solid red;width: 500px;height: 300px;text-align: center">
    <h3><span th:text="*{userName}"></span></h3>
    <h3><span th:text="*{id}"></span></h3>
    <h3><span th:text="*{phone}"></span></h3>
    <h3><span th:text="*{password}"></span></h3>
    <h3><span th:text="*{dept}"></span></h3>
</div>

3)#{}:消息表达式
   一般用来做国际化i18n   xxx_en_US    xxx_zh_CN
   读取resources目录下的.properties文件


   #resources目录下消息文件(.properties),不加语言修饰的基本的名称
   默认配置文件中默认配置是:spring.messages.basename=messages,如果想要修改文件夹名也可以,记得把配置文件里这个默认配置也改了;
   
   定义一个区域解析器,区域解析器设置的是什么国家,就会读取哪个国家的消息文件

如上图,这个Unicode中英文转换,网址:http://tool.chinaz.com/tools/unicode.aspx

写一个配置类:定义区域解析器,定义显示的语言类型

controller写一个方法:

这样就可以了;

4)@{}:链接表达式  :用在所有的路径上
  可以自动添加上下文路径
  如何带参数 :th:href="@{/user(id=1)}"

如果在配置文件中配置了上下文路径,用链接表达式时不用带上下文路径,直接写跳到哪个方法就可以,它自己会自动匹配上下文路径;

猜你喜欢

转载自blog.csdn.net/qq_43154385/article/details/85301647
今日推荐