【问题标题】:How to render a jsp file of different CSS and images spring mvcspring mvc如何渲染不同CSS和图片的jsp文件
【发布时间】:2017-04-26 10:00:45
【问题描述】:

我正在开发 Spring MVC 应用程序。根据要求,我有 35 个类别,所有类别页面将具有相同的结构,但不同的颜色和图像不同,并且它们都使用不同的 url 调用。

例如:

cat1.html https://drive.google.com/file/d/0BzYl1Amc-L0YR0RrXy05cWFmSFE/view?usp=sharing

cat2.html https://drive.google.com/file/d/0BzYl1Amc-L0YZnh2b2ZpT19md2c/view?usp=sharing

我的妈妈建议为所有类别创建不同的 JSP 文件。但是我觉得用单个JSP文件动态渲染会更好。

我们可以那样做吗?

我尝试使用 rest request /{cat}.html 并匹配它以加载不同的 CSS 和图像文件以进行这样的建模,但没有奏效。

@Controller

公共类 ViewController {

List<UI> uiList = new ArrayList<UI>();

@RequestMapping(value = "/{cat}.html", method = RequestMethod.GET)
public String article(@PathVariable("cat") String cat, ModelMap model,
        HttpServletRequest request) {

    UI cat1 = new UI();
    cat1.setId(1);
    cat1.setCatCssFile("app-cat1.css");
    cat1.setCalendarImage("pic1.png");
    cat1.setCat("cat1");
    uiList.add(cat1);

    UI cat2 = new UI();
    cat2.setId(2);
    cat2.setCatCssFile("app-cat2.css");
    cat2.setCat("cat2");
    cat2.setCalendarImage("pic2.png");
    uiList.add(cat2);


    for (UI ui : uiList) {
        if (ui.getCat().equals(cat)) {
            model.addAttribute("ui", ui);
        }
    }

    return "article";
}

【问题讨论】:

    标签: java spring jsp spring-mvc


    【解决方案1】:

    我认为您已接近最佳解决方案,我会这样做:

    @RequestMapping(value = "/{cat}.html", method = RequestMethod.GET)
    public String article(@PathVariable("cat") String cat, ModelMap model,
            HttpServletRequest request) {
            //code
            model.addAttribute("cat", cat);
            return "article"
    }
    

    在您的 HTML 文件中(我使用来自 thymeleaf 的符号,您应该使用 JSP 选项来呈现控制器变量)

    <link rel="stylesheet" th:href="@{'/app/css/' + ${cat} + '.css'}" type="text/css"/>
    

    【讨论】:

    • 感谢您的回复。我不知道百里香叶。我现在就试试。我们不能没有百里香吗?
    • 当然。您可以在普通 JSP 中使用它,并从控制器模型中读取类别值
    猜你喜欢
    • 1970-01-01
    • 2011-05-02
    • 2016-05-08
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多