经常我们开发中一般不会再用JSP了,都会选择freemarker或者thymeleaf。对于JSP,它前后端耦合性太差,而且JSP需要tomcat来解析,nginx解析不了,已经跟不上时代的潮流。我更倾向使用freemarker,他可以很好的解耦前后端,甚至在完全静态化这方面做的相当不错,所有对于那种内容管理型的网站,用freemarker可以大大的节省服务器的开支。
如何集成JSP呢?
1. pom.xml
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
2.application.yml
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
3.MVCConfig.java (进行MVC注解配置,如果第二步不生效)
package org.joseph.mysite.web.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 配置请求视图映射
*
* @return
*/
@Bean
public InternalResourceViewResolver resourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//请求视图文件的前缀地址
internalResourceViewResolver.setPrefix("/WEB-INF/jsp/");
//请求视图文件的后缀
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
WebMvcConfigurer.super.addCorsMappings(registry);
registry.addMapping("/cors/**")
.allowedHeaders("*")
.allowedMethods("POST", "GET")
.allowedOrigins("*");
}
/**
* 视图配置
*
* @param registry
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
WebMvcConfigurer.super.configureViewResolvers(registry);
registry.viewResolver(resourceViewResolver());
/*registry.jsp("/WEB-INF/jsp/",".jsp");*/
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
configurer.enable("defaultServletName");
}
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
}
}
4. Application.java (放在controller的父级目录)
package org.joseph.mysite.web;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication(scanBasePackages = {"org.joseph.mysite.web"})
@MapperScan("org.joseph.mysite.db.dao")
@EnableTransactionManagement
@EnableScheduling
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
如何集成Freemarker呢?
1. pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2. application.yml
spring:
http:
encoding:
force: true
charset: UTF-8
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
suffix: .html
template-loader-path: classpath:/templates
settings:
urlEscapingCharset: UTF-8
templateUpdateDelay: 5
tagSyntax: autoDetect
whitespaceStripping: true
classicCompatible: true
numberFormat: 0.######
booleanFormat: true,false
datetimeFormat: yyyy-MM-dd HH:mm:ss
dateFormat: yyyy-MM-dd
timeFormat: HH:mm:ss
apiBuiltinEnabled: true
objectWrapper: DefaultObjectWrapper(2.3.28)
templateExceptionHandler: org.joseph.mysite.cmsfreemarker.configuration.FreemarkerExceptionHandler
mvc:
static-path-pattern: /static/**
3. FreemarkerConfig.java (配置文件)
package org.joseph.mysite.cmsfreemarker.configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Properties;
@Configuration
public class FreemarkerConfig {
@Resource
void configureFreemarkerConfigurer(FreeMarkerConfig configurer) {
configurer.getConfiguration().setObjectWrapper(new CustomObjectWrapper());
}
private static class CustomObjectWrapper extends DefaultObjectWrapper {
@Override
public TemplateModel wrap(Object obj) throws TemplateModelException {
if (obj instanceof LocalDateTime) {
Timestamp timestamp = Timestamp.valueOf((LocalDateTime) obj);
return new SimpleDate(timestamp);
}
if (obj instanceof LocalDate) {
Date date = Date.valueOf((LocalDate) obj);
return new SimpleDate(date);
}
if (obj instanceof LocalTime) {
Time time = Time.valueOf((LocalTime) obj);
return new SimpleDate(time);
}
return super.wrap(obj);
}
}
}
4. 异常处理
package org.joseph.mysite.cmsfreemarker.configuration;
import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.Writer;
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(FreemarkerExceptionHandler.class);
@Override
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
log.warn("[Freemarker Error: " + te.getMessage() + "]");
String missingVariable = "undefined";
try {
String[] tmp = te.getMessageWithoutStackTop().split("\n");
if (tmp.length > 1)
tmp = tmp[1].split(" ");
if (tmp.length > 1)
missingVariable = tmp[1];
out.write("");
log.error("[出错了,请联系网站管理员]", te);
} catch (IOException e) {
throw new TemplateException(
"Failed to print error message. Cause: " + e, env);
}
}
}
发表评论
所有评论(0)
谢谢keke的支持~
加油哈哈哈哈哈
新人上路,中间会遇到很多坑~