第一步新建一个Controller,以产品信息为例(ProductController)
package com.xcy.ctrl;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controller@RequestMapping("/Product")public class ProductController { @RequestMapping("/index") public ModelAndView index(HttpServletRequest req, HttpServletResponse res){ ModelAndView mv = new ModelAndView();//mv初始化 mv.setViewName("true");//设定访问页面为 true.jsp return mv; }}
第二步建Service, 它只是一个接口,真正是通过ServiceImpl实现
**在public class productInfoServiceImpl implements ProductInfoService之前要有@Service进行注解
package com.xcy.service;import java.util.List;import com.xcy.bean.ProductInfo;public interface ProductInfoService { public ListgetAllProduct();//获得所有产品信息列表}
package com.xcy.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.xcy.bean.ProductInfo;import com.xcy.mapper.ProductInfoMapper;import com.xcy.service.ProductInfoService;@Servicepublic class ProductInfoServiceImpl implements ProductInfoService{// @Autowired// public ProductInfoMapper chanpin; @Override public ListgetAllProduct() { // TODO Auto-generated method stub //return chanpin.queryAll(); System.out.println("getAllProduct"); return null; }}
第三步建一个Mapper,它也是一个接口,在 .xml文件中编辑相应的sql语句
package com.xcy.mapper;import java.util.List;import com.xcy.bean.ProductInfo;public interface ProductInfoMapper { public ListqueryAll();}
之后要将Product.xml文件引入到mybatisConfig.xml文件中 <mapper resource="spring/mapping/Product.xml"/>
第四步 查询产品详细信息
for(int i = 0; i< list.size() ;i++){
ProductInfo c = list.get(i);
System.out.println("Id:"+ c.getId() +
" Name:" + c.getName() + " Spec:"+ c.getSpec()
+ " Price:" + c.getPrice());
}//输出每个产品的编号、名称、规格、价格
package com.xcy.ctrl;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import com.xcy.bean.ProductInfo;import com.xcy.service.ProductInfoService;@Controller@RequestMapping("/Product")public class ProductController { @Autowired public ProductInfoService cp; @RequestMapping("/index") public ModelAndView index(HttpServletRequest req, HttpServletResponse res){ ModelAndView mv = new ModelAndView();//mv初始化 mv.setViewName("true");//设定访问页面为 true.jsp Listlist = cp.getAllProduct();//获得所有产品信息列表 for(int i = 0; i< list.size() ;i++){ ProductInfo c = list.get(i); System.out.println("Id:"+ c.getId() + " Name:" + c.getName() + " Spec:"+ c.getSpec() + " Price:" + c.getPrice()); }//输出每个产品的编号、名称、规格、价格 return mv; }}
第五步新增产品信息