使用SpringMVC时,发现Controller层的list,delete,add,update这几个基本数据操作对于每个实体都是公共的。就想到进行泛化以提高代码的复用。挺有意思的是父类的@RequestMapping能够被子类继承。因为这个注解的@Retention(value=RUNTIME).对注解不太熟悉的推荐看下面两篇博客。
http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html
http://blog.csdn.net/fly_sky520/article/details/21522903
若发现错误或不足欢迎交流,一起进步。
转载请注明出处
<a target=_blank href="http://blog.csdn.net/u012413167/article/details/50277195">http://blog.csdn.net/u012413167/article/details/50277195</a>
基类代码如下
public class BaseController<T>{
private Class<T> entityClass;
public BaseController(){
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
entityClass = (Class) params[0];
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
//加载对应的Dao实现类的bean @Resource的name必须是常量所以不能使用@Resource注解注入
baseDao=(BaseDao<T>) wac.getBean(firstLetterToLowerCase(entityClass.getSimpleName())+"DaoImpl");
}
public Class<T> getEntityClass() {
return entityClass;
}
//把类名的首字母变为小写,因为我的标识符使用小驼峰法,类命名使用大驼峰法
private String firstLetterToLowerCase(String s)
{
char[] charArray=s.toCharArray();
if(charArray[0]<97) charArray[0]+='a'-'A';
return String.valueOf(charArray);
}
private BaseDao<T> baseDao;
//列出所有记录 ,返回页面
@RequestMapping("/list")
public ModelAndView list(String view){
List<T> list=baseDao.loadAll();
ModelAndView mav=new ModelAndView(view);
mav.addObject("list", list);
return mav;
}
//列出所有记录 ,返回json串
@RequestMapping("/listRJson")
public @ResponseBody List<T> listByJson()
{
List<T> list=baseDao.loadAll();
return list;
}
@RequestMapping("/add")
public ModelAndView add(T entity,String view)
{
String msg="添加成功";
if(!baseDao.save(entity))
msg="添加失败";
ModelAndView mav=new ModelAndView(view);
mav.addObject("msg",msg);
return mav;
}
@RequestMapping("/addRMsg")
public void addRMsg(T entity,HttpServletResponse res) throws IOException
{
String msg="添加成功";
if(!baseDao.save(entity))
msg="添加失败";
res.getWriter().println(msg);
}
@RequestMapping("/delete")
public ModelAndView delete(Serializable[] ids,String view)
{
if(ids!=null)
for(Serializable id:ids)
baseDao.remove(id);
ModelAndView mav=new ModelAndView(view);
return mav;
}
}
TeacherController代码如下
@Controller
@RequestMapping("/teacher")
public class TeacherController extends BaseController<Teacher>{
}
访问 http://localhost:8080/***/teacher/listRJson结果如下
[{"tId":"1","password":"1","tName":"中","introduction":"123"}]