1.需求
自定义标签类中调用smm框架中的dao层,获取数据,在页面展示当前登陆用户的信息。
2.数据库
3.MyTag.java继承RequestContextAwareTag类
package com.zy.tag;
import javax.servlet.jsp.JspWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.tags.RequestContextAwareTag;
import com.zy.mapper.UserMapper;
import com.zy.pojo.User;
public class MyTag extends RequestContextAwareTag{
private static final long serialVersionUID = 1L;
@Autowired
private UserMapper um;
@Override
protected int doStartTagInternal() throws Exception {
JspWriter out = pageContext.getOut();
//获取bean
um =this.getRequestContext().getWebApplicationContext().getBean(UserMapper.class);
String loginName = (String) pageContext.getSession().getAttribute("loginname");
User u = um.selectByLoginName(loginName);
out.write("当前用户的登陆名:"+u.getLoginname()+",性别:"+u.getSex()+",用户名:"+u.getUsername());
out.flush();
return 0;
}
}
4.myTag.tld
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd" > <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.0</jsp-version> <short-name>myTag</short-name> <uri>http://www.zy.myTag</uri> <tag> <name>loginName</name> <tag-class>com.zy.tag.MyTag</tag-class> <body-content>scriptless</body-content> </tag> </taglib>
5.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="http://www.zy.myTag" prefix="myTag" %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>首页</title> </head> <body background="../img/body-bg.png"> <hr/> <myTag:loginName/> </body> </html>
6.效果