SpringBoot中SpringMVC的配置

在springboot中使用springmvc

要在springboot中使用springmvc,只需要引入spring-boot-starter-web即可(前提是项目的pom文件是继承自spring-boot-starter-parent):

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

然后可以在application.properties文件中对springmvc的一些参数进行配置,例如从加载jsp的跟路径等等:

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

再说点网上没有的

如果我们有些变量需要在jsp(注意这里是jsp,而非freemarker等,freemarker的配置方式在后面)中被${xxx}的形式引用,而这些变量的值又是在java代码中赋值的,我们可以使用@ControllerAdvice这个注解,同时配合UrlBasedViewResolver对象及@PostConstruct@InitBinder等注解就可以达到我们的效果:

@ControllerAdvice
public class SpringmvcConfiguration {

    @Autowired
    UrlBasedViewResolver urlBasedViewResolver;

    @PostConstruct
    void init(){
        //配置request中的可被${}使用的变量↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
        Map<String, Object> m = new HashMap<>();
        m.put("xxx", "xxx");
        urlBasedViewResolver.setAttributesMap(m);
    }

    //此处配置springmvc的参数转换器,每个参数转换器都是继承自PropertyEditorSupport类
    @InitBinder
    public void bind(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new DateConvertEditor());
        binder.registerCustomEditor(List.class, new StringListConvertEditor());
        binder.registerCustomEditor(int.class, new IntegerConvertEditor());
        binder.registerCustomEditor(String[].class, new StringListConvertEditor());
        binder.registerCustomEditor(boolean.class, new BooleanConvertEditor());
    }

}

上面的 示例还展示了如何在springmvc中注入参数转换器,例如我们需要将前台传递的字符串"2018-3-9 17:48:00"转换为Date对象,上面的DateConvertEditor类就可以完成转换。

在freemarker中

如果要在freemarker中变量的注入变量或使用shiro 标签,我们可以使用FreeMarkerConfigurer对象来实现:

@Configuration("Mv6gFBYZ3VDmPeSjTpQC")
public class ShiroTagFreeMarkerConfigurer implements InitializingBean {

    @Autowired
    FreeMarkerConfigurer freeMarkerConfigurer;

    @Override
    public void afterPropertiesSet() throws IOException, TemplateException {
        //可以在ftl文件中使用shiro标签
        freeMarkerConfigurer.getConfiguration().setSharedVariable("shiro", new ShiroTags());
        //可以在ftl文件中
        freeMarkerConfigurer.getConfiguration().setSharedVariable("xxx", "xxx");
    }

}

此时如果我们要在freemarker中使用shiro标签,就可以这样:

<@shiro.hasPermission name="quanxian">
</@shiro.hasPermission>

同样的,如果需要使用上面注册的xxx变量,可以这样:

${xxx}
  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值