ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

分级菜单案例(spring+mybatis+springmvc)

2021-01-24 23:01:03  阅读:99  来源: 互联网

标签:name springmvc spring pid public children int mybatis id


需求:在浏览器上展现一个两级的菜单,点击一级菜单 第二级菜单展示或消失

数据库设计

  • pid表示所属上级菜单,将通过pid来进行筛选分类,
  • 查询一级菜单即pid=0,然后查询到id=1和id=2的两个对象,
  • id=1的对象去查询pid=1,将查询到的对象放到自己对象集合中,id=2的对象同理
create table menu(
	id int(10) primary key auto_increment,
	name varchar(20),
	pid int(10)
);
insert into menu values(default,'系统设置',0);
insert into menu values(default,'销售管理',0);
insert into menu values(default,'修改密码',1);
insert into menu values(default,'添加用户',1);
insert into menu values(default,'销售人员新增',2);
insert into menu values(default,'删除销售人员',2);

在这里插入图片描述

三个配置文件

web.xml

spring的部分加载applicaitonContext配置文件
springmvc部分加载springmvc配置文件,并且设置resp.setCharacterEncoding

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <!--spring  -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--springmvc  -->
 <servlet>
 	<servlet-name>springmvc</servlet-name>
 	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 	<init-param>
 		<param-name>contextConfigLocation</param-name>
 		<param-value>classpath:springmvc.xml</param-value>
 	</init-param>
 	<load-on-startup>1</load-on-startup>
 </servlet>
 
 <servlet-mapping>
 	<servlet-name>springmvc</servlet-name>
 	<!--拦截除了jsp之外所有的请求,如果写/*  包括jsp在内的所有请求都会被当做servlet别名,就请求不到jsp  
 		除了jsp之外,要是请求图片等静态资源,也会被当做sersvlet别名,这个一般在springmvc配置文件中过滤掉这些文件,让这些文件不走这个控制器-->
 	<url-pattern>/</url-pattern>
 </servlet-mapping>
 
<!--设置响应编码格式,resp.CharacterEncoding 
请求编码格式一般jsp开头中都有设置content-type,使得通过jsp返回给后台的请求编码格式为utf-8,所以不用单独设置 -->
<filter>
	<filter-name>encoding</filter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	<init-param>
		<param-name>encoding</param-name>
		<param-value>utf-8</param-value>
	</init-param>
</filter> 
<filter-mapping>
	<filter-name>encoding</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
 
 
</web-app>

数据源配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/login
jdbc.password=wityy
jdbc.username=root

applicationContext.xml

同mybatis+spring时基本没有变化,springmvc主要是改变了servlet部分的功能

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
        
        <!--注解扫描   spring只扫描impl,springmvc只扫描controller-->
        <context:component-scan base-package="cn.wit.serviceImpl"></context:component-scan>
        <!-- 加载属性文件,数据源需要的数据 --> 
        <context:property-placeholder location="classpath:db.properties"/>
        <!--数据源  -->
        <bean id="dataSource" class=" org.springframework.jdbc.datasource.DriverManagerDataSource">
        	<property name="driverClassName" value="${jdbc.driver}"></property>
        	<property name="url" value="${jdbc.url}"></property>
        	<property name="username" value="${jdbc.username}"></property>
        	<property name="password" value="${jdbc.password}"></property>
        </bean>
        
        <!--SqlSessionFactory  -->
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
			<property name="dataSource" ref="dataSource"></property>
			<property name="typeAliasesPackage" value="cn.wit.pojo"></property>
		</bean>
		<!-- 扫描器相当于 mybatis.xml 中 mappers 下 package 标 签,扫描 cn.wit.mapper 包后会给对应接口创建对象-->
		<bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer">
			<property name="basePackage" value="cn.wit.mapper"></property>
			<property name="sqlSessionFactoryBeanName" value="factory"></property>
		</bean>
        
        <!--事务管理器  -->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        	<property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:advice id="txAdvice" transaction-manager="txManager">
        	<tx:attributes>
        		<tx:method name="ins*"/>
        		<tx:method name="del*"/>
        		<tx:method name="upd*"/>
        		<tx:method name="*" read-only="true"/>
        	</tx:attributes>
        </tx:advice>
        <!--aop  -->
        <aop:config>
        	<aop:pointcut expression="execution(* cn.wit.serviceImpl.*.*(..))" id="mypoint"/>
        	<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
        </aop:config>
        
</beans>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
      xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--使用springmvc已经封装好了servlet,用controller代替了原先的servlet  -->
        
      <!--扫描注解,只扫描controller,applicaitonContext.xml中的注解是扫描Impl的  -->
      <context:component-scan base-package="cn.wit.controller"></context:component-scan>
      <!--注解驱动  -->
      <mvc:annotation-driven></mvc:annotation-driven>
      
      <!--静态资源 阻止拦截  -->
      <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
      <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
      <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
      
      
      <!--视图解析器  ,可以设置简化jsp的路径,在controller中return jsp的时候,经过解析器拼写完整路径
      	prefix表示前面加字符串,suffix表示后面加字符串
      -->
      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      	<property name="prefix" value="/"></property>
      	<property name="suffix" value=".jsp"></property>
      </bean>
      
      
      
 </beans>

pojo

Menu

public class Menu {
	private int id;
	private String name;
	private int pid;
	private List<Menu> children;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public List<Menu> getChildren() {
		return children;
	}
	public void setChildren(List<Menu> children) {
		this.children = children;
	}
	@Override
	public String toString() {
		return "Menu [id=" + id + ", name=" + name + ", pid=" + pid + ", children=" + children + "]";
	}
	public Menu(int id, String name, int pid, List<Menu> children) {
		super();
		this.id = id;
		this.name = name;
		this.pid = pid;
		this.children = children;
	}
	public Menu() {
		super();
	}
	
}

cn.wit.mapper

MenuMapper接口

public interface MenuMapper {
	List<Menu>selByPid(int pid);
}

MenuMapper.xml

分级菜单用递归,下边注解分析了过程

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <mapper namespace="cn.wit.mapper.MenuMapper">
  <!--resultmap可以返回单个对象,也可以返回对个对象
  这里希望通过一次调用拿到所有数据,通过map体现菜单层次
  	外边Impl中传入0,然后resultmap查询到两个一级菜单,
  	将一级菜单的id作为参数进行查询,与之前resultMap不同的是,
  	之前是查询另一个select,这次是递归查询同一个
  	比如其中一个一级菜单的id是1
  	select *from menu where pid=1
  	返回两条数据resultmap中collection存放两个对象,id分别是3,4
  	比如id等于3的这条数据在创建对象时需要赋值collection,继续向下查找
  	select *from menu where pid=3,此时数据库并没有这条数据,返回null,这条递归结束,其他递归同理
    -->
 	<resultMap type="menu" id="mymap">
 		<id property="id" column="id"/>
 		<id property="name" column="name"/>
 		<collection property="children" select="cn.wit.mapper.MenuMapper.selByPid"  column="id"></collection>
 	</resultMap> 
  	<select id="selByPid" parameterType="int" resultMap="mymap">
  		select* from menu where pid=#{0}
  	</select>
  </map

cn.wit.service

MenuService接口

public interface MenuService {
	List<Menu>show();
}

Impl

使用注解,注入Mapper

@Service
public class MenuServiceImpl implements MenuService{
	/*
	 * 可以不在applicationContext中设置bean,用注解进行替换
	 * */
	@Resource
	private MenuMapper menuMapper;
	@Override
	public List<Menu> show() {
		return menuMapper.selByPid(0);
	}
	

}

cn.wit.controller

MenuController

本类也交给spring进行管理,然后注入MenuServiceImpl(注意byName,首字母小写)
RequestMapping表示请求的servlet别名为show时,调用本方法,springmvc的方法参数很灵活
使用ResponseBody对ajax进行简化,表明不是jsp,返回list给底层去转为jason给浏览器,具体内容在springmvc环境搭建那篇文章有写

@Controller
public class MenuController {
	
	@Resource
	private MenuService menuServiceImpl;
	
	@RequestMapping("show")
	@ResponseBody
	public List<Menu>show(){
		return menuServiceImpl.show();
	}
	
	
}

jsp

ajax技术
动态对每个dt添加点击事件,具体细节查阅w3c

$("dt").live("click",function(){
		$(this).siblings().slideToggle();
	}) 
<%@ page language="java" contentType="text/html;charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
	$(function(){
		$.post("show",function(data){
			var result="";
			for(var i=0;i<data.length;i++){
				result+="<dl>";
				result+="<dt style='cursor:pointer'>"+data[i].name+"</dt>";//顶头
				for(var j=0;j<data[i].children.length;j++){
					result+="<dd>"+data[i].children[j].name+"</dd>"
				}
				result+="</dl>";//缩进
			}
			$("body").html(result);
		});
	})
	//对所有父菜单添加点击事件
	//live("事件名,多个事件使用空格分隔")
	 $("dt").live("click",function(){
		$(this).siblings().slideToggle();
	}) 
</script>
</head>
<body>
	
</body>
</html>

标签:name,springmvc,spring,pid,public,children,int,mybatis,id
来源: https://blog.csdn.net/WA_MC/article/details/113096718

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有