在项目中,即使是静态资源,也应当防止直接访问,而应当通过一个Controller方法来接收访问,然后返回对应的资源。例如,再访问index页面时,通常的做法如下:
@Controller
public class IndexController {
@RequestMapping(value={"/", "/index"})
public String index(){
return "/index";
}
}
这个index方法没有任何逻辑,只是接收"/index"请求,返回index.html页面。当项目中存在大量的这种页面转向时,代码会显得非常臃肿。
解决办法:
(1)创建一个properties文件,指定请求路径和对应的返回页面;
(2)解析配置文件;
(3)重写WebMvcConfigurer类的addViewControllers方法,将配置文件的对应信息进行处理。
代码如下:
(1)
#requestURI=viewName
/=/index
/index=/index
(2)
public class ViewControllerParsor {
private static final Logger logger = LoggerFactory.getLogger(ViewControllerParsor.class);
public static Map<String, String> parse(){
Map<String, String> vcs = new HashMap<>();
Resource res = new ClassPathResource("view-controller.properties");
Properties props = null;
try {
props = PropertiesLoaderUtils.loadProperties(res);
} catch (IOException e) {
logger.error("view-controller.properties文件解析异常[{}]", e);
}
if(props != null){
Enumeration<String> names = (Enumeration<String>)props.propertyNames();
while(names.hasMoreElements()){
String name = names.nextElement();
vcs.put(name, props.getProperty(name));
}
}
return vcs;
}
}
(3)
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
Map<String, String> vcs = ViewControllerParsor.parse();
vcs.forEach((k, v)->{
registry.addViewController(k).setViewName(v);
});
}
}