在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}