首先看实现效果:
下面代码实现:
1.后台初始化类别数据:
/*** 初始化加载数据* @Author tony* @Date 10:40 2019/12/25**/
@Component("initSystem")
public class InitSystem implements ServletContextListener,ApplicationContextAware{
private static ApplicationContext applicationContext; // 获取实例beanpublic static Map<Integer,ArcType> arcTypeMap=new HashMap<Integer,ArcType>();/*** 加载数据到application缓存中* @param application 整个项目的域* ServletContext :上下文*/public void loadData(ServletContext application){
ArcTypeService arcTypeService=(ArcTypeService) applicationContext.getBean("arcTypeService");List<ArcType> allArcTypeList = arcTypeService.listAll(Sort.Direction.ASC, "sort");// 所有类别存到map里面 for (ArcType arcType: allArcTypeList){
arcTypeMap.put(arcType.getId(), arcType);}application.setAttribute("allArcTypeList", allArcTypeList);}@Overridepublic void contextInitialized(ServletContextEvent sce) {
this.loadData(sce.getServletContext());}@Overridepublic void contextDestroyed(ServletContextEvent sce) {
}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;}}
2.前台取出数据:
<ul><li><a href="/"><span id="t_0">全部</span></a></li><li th:each="arcType:${application.allArcTypeList}"><a th:href="'/article/list/1?typeId='+${arcType.id}" th:title="${arcType.name}"><span th:id="'t_'+${arcType.id}" th:text="${arcType.name}"></span></a></li></ul>
3.点击某个类别后 再次请求后台:
@RequestMapping("/list/{id}")public ModelAndView list(@RequestParam(value="typeId",required=false)Integer typeId,@PathVariable(value="id",required=false)Integer page,HttpServletRequest request){
ModelAndView mav=new ModelAndView();Article s_article = new Article();s_article.setState(2); //查询审核通过的帖子if(typeId == null){
mav.addObject("title","第"+page+"页");request.getSession().setAttribute("tMenu",null);}else {
//根据typeId 获取资源类别实体ArcType arcType = InitSystem.arcTypeMap.get(typeId);s_article.setArcType(arcType);mav.addObject("title",arcType.getName()+"-第"+page+"页");request.getSession().setAttribute("tMenu","t_"+typeId); // 点击某个类别 该类别标红 这里将t+typeId设置为前台类别的id}.........
}
4.前台页面操控样式:
<script th:inline="javascript">/*<![CDATA[*/layui.use(['element'], function(){
var element = layui.element; //导航的hover效果、二级菜单等功能,需要依赖element模块var tMenu = [[${
session.tMenu}]];$("#"+tMenu).css("color","red");});/*]]>*/
</script>