这次是事儿B地想要统一控制前后端的数据字典名称。
在做后台管理系统时,通常会遇见很多数据字典。例如,学生的性别(男/女)、政治面貌(党员/团员/群众)等。在新增和编辑时,这类字段通常以下拉列表的形式呈现;而下拉列表的内容可以直接在后端查询并使用模板引擎渲染,也可以异步查询、JS动态渲染。
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private DictionaryService dictionaryService;
@GetMapping("/view/{id}")
public String view(@PathVariable Integer id) {
model.addAttribute("student", studentService.getById(id));
model.addAttribute("sexes", dictionaryService.findItemsBy("sex"));
model.addAttribute("politics", dictionaryService.findItemsBy("politic"));
}
}
上述代码是在请求页面时就查询字典项,利用模板引擎渲染完毕之后再返回给前端。这里存在一个问题:如果字典sex
有很多地方用到了,某天我决定给他换个名称(比如xingbie
),那就得一处一处地改代码。于是我将所有字典名称写在一个接口类中:
public interface AppConstant {
String DICT_SEX = "sex";
String DICT_POLITIC = "politic";
}
所有代码都通过接口类来选择字典:
@GetMapping("/view/{id}")
public String view(@PathVariable Integer id) {
model.addAttribute("student", studentService.getById(id));
model.addAttribute(AppConstant.DICT_SEX + "es", dictionaryService.findItemsBy(AppConstant.DICT_SEX));
model.addAttribute(AppConstant.DICT_POLITIC + "s", dictionaryService.findItemsBy(AppConstant.DICT_POLITIC));
}
这样,当字典名称发生变更时,只需要修改一处即可。
但问题又来了,后端的字典名称统一了,传给前端的字典名称依旧是千变万化,前端被迫将字典名称写死在代码中:
<!-- Thymeleaf -->
<select class="form-control" id="sex" readonly>
<!-- student.sex为整型:0-男,1-女 -->
<option th:each="e : ${sexes}" th:text="${e.val}" th:selected="${e.name eq (student.sex + '')}"></option>
</select>
考虑到JSP能够直接调用Java类的静态成员,SpEL也提供了类似的功能:T(com.xx.xx.AppConstant).DICT_SEX
。然后我将所有字典以Map<String, List<DictionaryItem>>
的形式打包后再传给前端,通过SpEL的map[KEY]
获取对应的字典:
<!-- Thymeleaf -->
<select class="form-control" id="sex" readonly>
<option th:each="e : ${dictionaryTable[T(com.xx.AppConstant).DICT_SEX + 'es']}"
th:text="${e.val}"
th:selected="${e.name eq (student.sex + '')}"></option>
</select>
最初,我是想直接使用
${T(com.xx.xx.AppConstant).DICT_SEX}
等价${sex}
获取后端传递过来的sex
参数,但发现前者实际上就是一个字符串。所以变通了一下,将其作为键名,将字典打包成Map
。