当前位置 : 主页 > 编程语言 > java >

spingboot视图层实例(JSP+Freemaker)以及自定义配置读取

来源:互联网 收集:自由互联 发布时间:2021-06-25
一、项目目录结构 二、创建MVN项目 freemaker支持比较简单,只需在pom.xml加上: dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-freemarker/artifactId/dependency jsp支持除了加上:

一、项目目录结构

二、创建MVN项目

freemaker支持比较简单,只需在pom.xml加上:

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

jsp支持除了加上:

<!-- servlet 依赖. -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<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>

还需在配置文件中设置spring.mvc.view,具体见(三)的application.yml。

详细的pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
	<artifactId>springboot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springboot</name>
	<description>Demo project for Spring Boot</description>


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

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- servlet 依赖. -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<scope>provided</scope>
		</dependency>
		<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>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

三、application.yml

spring:  
  datasource:  
    url : jdbc:mysql://localhost:3306/test?useSSL=false  
    username :  your-user  
    password :  your-passwd  
    driver-class-name : com.mysql.jdbc.Driver
  test2ds:  
    url : jdbc:mysql://localhost:3306/test2?useSSL=false  
    username : your-user  
    password :  your-passwd  
    driver-class-name : com.mysql.jdbc.Driver   
  mvc:  
    view:  
      prefix:  /WEB-INF/jsp/
      suffix: .jsp  
# 自定义属性,可以在Controller中读取  
  hello: Hello Angel From application 
       
myProps: #自定义的属性和值  
  simpleProp: simplePropValue  
  arrayProps: 1,2,3,4,5  
  listProp1:  
    - name: abc  
      value: abcValue  
    - name: efg  
      value: efgValue  
  listProp2:  
    - config2Value1  
    - config2Vavlue2  
  mapProps:  
    key1: value1  
    key2: value2

其中数据源本例没有用到。spring.mvc.view是为了实现jsp配置。spring.hello和myProps为自定义属性,在接下去的Controller中使用。

四、视图层

jsp页面在src/main/webapp/WEB-INF/jsp下面。

helloJsp.jsp

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>在此处插入标题</title>
</head>
<body>
    helloJsp  
    <br>  
    ${hello}  
</body>
</html>

freemaker在src/main/resources/templates下面

web.ftl

<!DOCTYPE html>  
  <html lang="zh">  
  <body>  
    Date: ${time?date}  
    <br>  
    时间: ${time?time}  
    <br>  
    Message: ${message}
    <br>  
    simpleProp: ${simpleProp}  
</body>  
</html>

now.ftl

<!DOCTYPE html>  
 <html lang="zh">  
  <body>  
    时间: ${mynow}
    <br>  
  </body>  
</html>

error.ftl

<!DOCTYPE html>
<html lang="en">
<body>
	Something wrong: ${status} ${error}
</body>
</html>

五、两个控制类

HelloController调用jsp页面

package com.example.jsp.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller  
public class HelloController {
    //从spring中读取配置,如取不到默认值为hello jack  
    @Value("${spring.hello:hello jack}")  
    private String hello;  
  
    @RequestMapping("/helloJsp")  
    public String helloJsp(Map<String, Object> map){  
        System.out.println("HelloController.helloJsp().hello="+hello);  
        map.put("hello", hello);  
        return "helloJsp";  
    }  
}

FtlWebContrpller需要一个读取myProps属性的辅助类MyProps

package com.example.freemarker.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component  
@ConfigurationProperties(prefix="myProps") //接收application.yml中的myProps下面的属性  
public class MyProps {  
    private String simpleProp;  
    private String[] arrayProps;  
    private List<Map<String, String>> listProp1 = new ArrayList<Map<String, String>>(); //接收prop1里面的属性值  
    private List<String> listProp2 = new ArrayList<String>(); //接收prop2里面的属性值  
    private Map<String, String> mapProps = new HashMap<String, String>(); //接收prop1里面的属性值     
      
    public String getSimpleProp() {  
        return simpleProp;  
    }  
      
    //String类型的一定需要setter来接收属性值;maps, collections, 和 arrays 不需要  
    public void setSimpleProp(String simpleProp) {  
        this.simpleProp = simpleProp;  
    }  
      
    public List<Map<String, String>> getListProp1() {  
        return listProp1;  
    }  
    public List<String> getListProp2() {  
        return listProp2;  
    }  
  
    public String[] getArrayProps() {  
        return arrayProps;  
    }  
  
    public void setArrayProps(String[] arrayProps) {  
        this.arrayProps = arrayProps;  
    }  
  
    public Map<String, String> getMapProps() {  
        return mapProps;  
    }  
  
    public void setMapProps(Map<String, String> mapProps) {  
        this.mapProps = mapProps;  
    }  
}

FtlWebContrpller代码

package com.example.freemarker.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;  
import java.util.Map;  
  
/** 
 * Created by LK on 2016/5/7. 
 */  
@Controller  
public class FtlWebContrpller {  
    @Value("${application.message:1234556677}")  
    private String message = "hi,hello world......";  
    @Autowired  
    private MyProps myProps;  
    @RequestMapping("/")  
    public String web(Map<String,Object> model){  
        model.put("time",new Date());  
        model.put("message",this.message); 
        model.put("simpleProp",this.myProps.getSimpleProp());  
        return "web";//返回的内容就是templetes下面文件的名称  
    }  
    
	@RequestMapping("/now")
	String now(Map<String,Object> model) {
		model.put("mynow",(new Date()).toString()); 
        return "now";//返回的内容就是templetes下面文件的名称  
	}

}

六、主类

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;

@SpringBootApplication
public class SpringbootTestApp implements EmbeddedServletContainerCustomizer{
	public static void main(String[] args) {
		SpringApplication.run(SpringbootTestApp.class, args);
	}

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		// TODO 自动生成的方法存根
		container.setPort(8080);
	}
}

运行:

.   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.8.RELEASE)

2017-11-02 22:54:51.384  INFO 17207 --- [           main] com.example.SpringbootTestApp            : Starting SpringbootTestApp on mymotif-Vostro-14-5480 with PID 17207 (/home/mymotif/workspace/springboot/target/classes started by mymotif in /home/mymotif/workspace/springboot)
2017-11-02 22:54:51.388  INFO 17207 --- [           main] com.example.SpringbootTestApp            : No active profile set, falling back to default profiles: default
2017-11-02 22:54:51.490  INFO 17207 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@353d0772: startup date [Thu Nov 02 22:54:51 CST 2017]; root of context hierarchy
2017-11-02 22:54:52.167  WARN 17207 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.example]' package. Please check your configuration.
2017-11-02 22:54:53.535  INFO 17207 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-11-02 22:54:53.553  INFO 17207 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-11-02 22:54:53.555  INFO 17207 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-11-02 22:54:53.876  INFO 17207 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner     : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2017-11-02 22:54:53.882  INFO 17207 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-11-02 22:54:53.882  INFO 17207 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2396 ms
2017-11-02 22:54:54.055  INFO 17207 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-11-02 22:54:54.060  INFO 17207 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-11-02 22:54:54.061  INFO 17207 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-11-02 22:54:54.061  INFO 17207 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-11-02 22:54:54.062  INFO 17207 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-11-02 22:54:54.462  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@353d0772: startup date [Thu Nov 02 22:54:51 CST 2017]; root of context hierarchy
2017-11-02 22:54:54.578  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/now]}" onto java.lang.String com.example.freemarker.controller.FtlWebContrpller.now(java.util.Map<java.lang.String, java.lang.Object>)
2017-11-02 22:54:54.580  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.example.freemarker.controller.FtlWebContrpller.web(java.util.Map<java.lang.String, java.lang.Object>)
2017-11-02 22:54:54.581  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/helloJsp]}" onto public java.lang.String com.example.jsp.controller.HelloController.helloJsp(java.util.Map<java.lang.String, java.lang.Object>)
2017-11-02 22:54:54.591  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-02 22:54:54.592  INFO 17207 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-02 22:54:54.660  INFO 17207 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-02 22:54:54.661  INFO 17207 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-02 22:54:54.729  INFO 17207 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-02 22:54:55.409  INFO 17207 --- [           main] o.s.w.s.v.f.FreeMarkerConfigurer         : ClassTemplateLoader for Spring macros added to FreeMarker configuration
2017-11-02 22:54:55.674  INFO 17207 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-11-02 22:54:55.752  INFO 17207 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-11-02 22:54:55.760  INFO 17207 --- [           main] com.example.SpringbootTestApp            : Started SpringbootTestApp in 4.898 seconds (JVM running for 5.267)
2017-11-02 22:55:17.802  INFO 17207 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-11-02 22:55:17.802  INFO 17207 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-11-02 22:55:17.822  INFO 17207 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 20 ms

localhost:8080/helloJsp转到helloJsp.jsp

localhost:8080/now转到now.ftl 

localhost:8080/转到web.ftl

不存在页面转到error.ftl

网友评论