Spring Boot基础知识(四)----springMVC与模板引擎

依赖注入

您可以自由使用任何标准的Spring Framework技术来定义您的bean及其注入的依赖关系。为了简单起见,我们经常发现使用@ComponentScan 查找你的bean,结合@Autowired构造函数注入效果很好。

如果您按上述建议构建代码(将应用程序类定位到根包中),则可以添加@ComponentScan任何参数。您的所有应用程序组件(的@Component,@Service,@Repository,@Controller等)将自动注册为bean。

示例:

public interface ProjectService {

    //这里是简单实例,简单返回一个bean吧
    Project findOneProject();
}

@Service
public class ProjectServiceImpl implements ProjectService{

    @Autowired
    private Project project;

    //这里只简单展示注入
    @Override
    public Project findOneProject() {
        return project;
    }

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }
}

@RestController
public class HelloController {

    //==============以下是依赖注入的简单示例=======================================
    @Autowired
    private ProjectService projectService;

    @RequestMapping("/handleBean")
    public String handleBean() {
        return projectService.findOneProject().getAuthor();
    }
}

访问http://localhost:8080/handleBean显示:cc

页面跳转

既然做到前台项目springMVC肯定要考虑到跳转到页面上传值过去,熟悉的就是jsp但是
页面上一直显示这个错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
。。。

很无语。去网上查了资料终于调通可以用jsp,el表达式获取值了—-

前情提要:

  1. springboot对jsp的支持不是很好,有很多限制,比如用的时候需要自己配置路径啊,需要引入依赖啊等等,最主要的是,用maven打成jar包的话,这个项目可能就悄悄的忽略了它,这很可怕
  2. 我们之前通过官网拿到的项目没有webapp的目录,但是jsp的话需要这个,要自己加上

下面的解决参考了以下网址:
http://www.cnblogs.com/shijiaoyun/p/5841867.html
https://www.oschina.net/question/347227_250528
http://www.cnblogs.com/huzi007/p/7087570.html

支持jsp

pom依赖文件加上:

<!-- 前台页面跳转相关 -->
       <!-- servlet 依赖. -->
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <scope>provided</scope>
       </dependency>
        <!--
           JSTL(JSP Standard Tag Library,JSP标准标签库)是一个不断完善的开放源代码的JSP标签库,是由apache的jakarta小组来维护的。
           JSTL只能运行在支持JSP1.2和Servlet2.3规范的容器上,如tomcat 4.x。在JSP 2.0中也是作为标准支持的。
           不然报异常信息:
           javax.servlet.ServletException: Circular view path [/helloJsp]: would dispatch back to 
           the current handler URL [/helloJsp] again. Check your ViewResolver setup! (Hint: This may be
            the result of an unspecified view, due to default view name generation.)
        -->
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>jstl</artifactId>
       </dependency>
       <!-- tomcat 的支持.-->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
           <scope>provided</scope>
       </dependency>
       <dependency>
           <groupId>org.apache.tomcat.embed</groupId>
           <artifactId>tomcat-embed-jasper</artifactId>
           <scope>provided</scope>
       </dependency>

Application.properties配置前后缀

首先,你的目录应该长成这样:
这里写图片描述

spring.mvc.view.prefix = /WEB-INF/jsp/
spring.mvc.view.suffix = .jsp

Controller:

@RestController
@RequestMapping("/hello")
public class HelloController {
    //==============以下是springmvc相关知识==============================
    @RequestMapping("/handleMVC")
    public ModelAndView handleMVC() {
        ModelAndView mav = new ModelAndView();
        Student student = new Student();
        student.setName("cc");
        student.setSex(1);
        student.setTelephone("18800000000");

        mav.setViewName("hello/hello1");
        mav.addObject("student",student);
        return mav;
    }
}

hello1.jsp

<h1>Student:</h1>
<input type="text" value="${student.name }"/>
<input type="text" value="${student.sex }"/>
<input type="text" value="${student.telephone }"/>

主类

@SpringBootApplication
public class SpringbootDemoApplication extends SpringBootServletInitializer {

    /*
     * 如果要使用tomcat来加载jsp的话就必须继承springbootServletInitializer类重写其中的configure方法
     * @see org.springframework.boot.web.support.SpringBootServletInitializer#configure(org.springframework.boot.builder.SpringApplicationBuilder)
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootDemoApplication.class);
    }


    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }
}

访问http://localhost:8080/hello/handleMVC,显示:
这里写图片描述
到此,我们的web项目就可以正常跳转前后台传值等操作了。
But!!!!!!前面说了springboot对于jsp的支持并不是很好,我们构建成maven的jar包,启动:
$ java –jar springbootDemo-0.0.1-SNAPSHOT.jar
访问http://localhost:8080/hello/handleMVC,显示:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
这是因为。。。webapp这个包标准用在war包中,用在jar包里面,很多构建工具根本不会去识别它,会忽略它。很可怕吧。

<!-- web项目依赖:springmvc tomcat 
        用了这个包,就会有一个约定俗成的配置jsp为webapp/web-inf底下的-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>    
        </dependency>

所以,springboot并不鼓励我们用jsp,它鼓励我们静态页面资源使用模板,哈哈哈哈哈哈哈哈哈,所以下面我们找出其中一个模板来学习一下。
注意啦springboot1.5版本不在支持velocity模板啦,所以我把pom中的依赖包换成了1.4.2之后看的

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

Velocity模板引擎

参考:
http://www.jianshu.com/p/a9e695a2f3f6使用
http://www.360doc.com/content/12/0105/16/1007797_177482053.shtml语法
http://velocity.apache.org/ 官网
http://blog.csdn.net/zhangxing52077/article/details/73194948 访问静态域动态不同

Pom:

spring boot会自动配置 FreeMarker,Thymeleaf,Velocity,只需要在pom中加入相应的依赖即可:

      <!--velocity模板引擎  -->
       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-velocity</artifactId>
       </dependency>

默认配置下spring boot会从src/main/resources/templates目录中去找模板

Application.properties:

# velocityAutoConfiguration
spring.velocity.charset = UTF-8
spring.velocity.properties.input.encoding=UTF-8
spring.velocity.properties.output.encoding=UTF-8
spring.velocity.suffix = .html
spring.velocity.toolbox-config-location=/WEB-INF/toolbox.xml

这样,SB会从src/main/resources/templates目录中去找以.html后缀的模板文件.

Bean:

我承认我一直在用同一个bean…

@Component//把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
public class Student implements java.io.Serializable{
    private static final long serialVersionUID = 1L;
    //名称
    private String name;
    //性别
    private Integer sex;
    //电话
    private String telephone;
    //生日
    private Date birthday;

    public Student() {}
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSex() {
        return sex;
    }
    public void setSex(Integer sex) {
        this.sex = sex;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

}

Controller:

@RestController
@RequestMapping("/hello")
public class HelloController {
    //==============以下是springmvc相关知识==============================
    @RequestMapping("/handleMVC")
    public ModelAndView handleMVC() {
        ModelAndView mav = new ModelAndView();
        Student student = new Student();
        student.setName("cc");
        student.setSex(1);
        student.setTelephone("18800000000");
        student.setBirthday(new Date());
        mav.setViewName("hello1");
        mav.addObject("student",student);
        return mav;
    }
}

toolbox.xml:

这里写图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!-- 这样我们就可以在模板文件中使用类似DateTool这样的工具类了.同时我们也可以在代码里自己实现工具类,然后配置到toolbox.xml文件里. -->
<toolbox>
    <tool>
        <key>DateTool</key>
        <scope>application</scope>
        <class>org.apache.velocity.tools.generic.DateTool</class>
    </tool>
</toolbox>

Hello1.html:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    #tb{width:300px;height:400px;border:1px solid black;}
    td{width:100%;height:100%;border:1px solid black;}
</style>
</head>
<body>
    <h1>Student:</h1>
    <table id="tb">
        <thead>
            <td>姓名</td>
            <td>性别</td>
            <td>电话</td>
            <td>生日</td>
        </thead>
        <tbody>
            <td>$!student.name</td>
            <td>$!student.sex</td>
            <td>$!student.telephone</td>
            <td>$!DateTool.format('yyyy-MM-dd HH:mm:ss',$!student.birthday)</td>
        </tbody>
    </table>
    <!—生日用的DateTool就是toolbox里面引用的工具 -->
</body>
</html>

访问:http://localhost:8080/hello/handleMVC显示
这里写图片描述
以上是通过controller跳转的,如果直接访问此html是找不到的,404
查了下官方文档:
默认情况下, Spring Boot从classpath下一个叫/static提供静态资源
如果我们把hello1.html写在static下面
这里写图片描述
访问http://localhost:8080/hello1.html,显示:
这里写图片描述
一般放一些静态资源js,css等文件。。。

因为springboot最新版本不支持了嘛,所以我们学了也有点囧,木有啥意义,网上推荐了FreeMarker,我们来简单学下这个

FreeMarker模板引擎

参考:
http://blog.csdn.net/songhaifengshuaige/article/details/54136984
http://blog.csdn.net/z69183787/article/details/73850417 使用

Pom依赖文件加上

<!-- freemarker 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

Application.properties:

我这里都是使用的默认的,模板默认找templates包,模板默认ftl结尾等
可以自行去设置

# freemarker
# define the ftl location
#spring.freemarker.template-loader-path = classpath:/templates
# static location: js,css
#spring.mvc.static-path-pattern = /static/**

Controller:

@RestController
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/handleMVC2")
    public ModelAndView handleMVC2() {
        ModelAndView mav = new ModelAndView();
        Student student = new Student();
        student.setName("cc");
        student.setSex(1);
        student.setTelephone("18800000000");
        student.setBirthday(new Date());
        mav.setViewName("hello3");
        mav.addObject("student",student);
        return mav;
    }
}

Hello3.tfl:

<html>
    <body>
        welcome ${student.name} to freemarker!
    </body>
</html>

访问http://localhost:8080/hello/handleMVC2,显示:
welcome cc to freemarker!
如果想学习相关语法可以参考以下:
http://blog.csdn.net/fhx007/article/details/7902040/
http://freemarker.org/docs/官网文档

我们发现返回json的时候ie老是提示要下载,呵呵。

问题:ie老是提示下载json

因为之前写过,解决这个问题是通过拦截来实现的,写在了xml中,在springboot中有点不好看,不太合适,也没必要非要返回project对不对,哈哈哈哈哈,返回json到时候去取也好啊,嘿嘿,曲线救国:
Controller:

 @RequestMapping(value="/handleBean5")//防止到页面上乱码
    public String handleBean5(HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException {
        Project pro1 = projectService.findOneProject();
        //规避代理类不能转化为json的错误
        Project pro = new Project();
        pro.setAuthor(pro1.getAuthor());
        pro.setName(pro1.getName());
        //WebUtil.writeJson(response, data); spring4
        //WebUtils.writeHtml(response, pro); // 返回text/html格式的数据

        //jackson2转化对象为json
         ObjectMapper mapper = new ObjectMapper();          
         // Convert object to JSON string  
         String json =  mapper.writeValueAsString(pro);

         return json;
    }

访问http://localhost:8080/project/handleBean5,显示:
这里写图片描述
至于怎么在springboot里面解决ie返回json提示下载的问题,欢迎有朋友来告诉我一下~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值