You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.9 KiB
57 lines
1.9 KiB
package de.srsoftware.widerhall.web; |
|
|
|
import de.srsoftware.widerhall.Configuration; |
|
import org.stringtemplate.v4.STGroup; |
|
import org.stringtemplate.v4.STRawGroupDir; |
|
|
|
import javax.servlet.http.HttpServlet; |
|
import javax.servlet.http.HttpServletResponse; |
|
import java.io.File; |
|
import java.io.IOException; |
|
import java.nio.file.Files; |
|
import java.util.Map; |
|
|
|
import static de.srsoftware.widerhall.Util.t; |
|
|
|
public abstract class TemplateServlet extends HttpServlet { |
|
private STGroup templates; |
|
private final String baseDir; |
|
|
|
public TemplateServlet(){ |
|
var config = Configuration.instance(); |
|
baseDir = config.baseDir(); |
|
loadTemplates(); |
|
} |
|
|
|
protected String loadFile(String filename, HttpServletResponse resp) { |
|
var path = String.join(File.separator,baseDir,"static",filename); |
|
var file = new File(path); |
|
if (!file.exists()) return t("Datei {} existiert nicht!",filename); |
|
try { |
|
var content = Files.readString(file.toPath()); |
|
resp.getWriter().println(content); |
|
} catch (IOException e) { |
|
return t("Ladend der Datei '{}' fehlgeschlagen!",filename); |
|
} |
|
return null; |
|
} |
|
|
|
protected String loadTemplate(String path, Map<String, ? extends Object> data, HttpServletResponse resp) { |
|
var template = templates.getInstanceOf(path); |
|
if (template != null){ |
|
try { |
|
template.add("data",data); |
|
resp.getWriter().println(template.render()); |
|
return null; |
|
} catch (IOException e) { |
|
return t("Laden der Vorlage '{}' fehlgeschlagen",path); |
|
} |
|
} |
|
return t("Keine Vorlage für den Pfad '{}' vorhanden!",path); |
|
} |
|
|
|
protected void loadTemplates() { |
|
var templateDir = String.join(File.separator,baseDir,"static","templates"); |
|
templates = new STRawGroupDir(templateDir,'«','»'); |
|
} |
|
}
|
|
|