- JSP如何开发使用自定义标签?
提示信息的一个tag示例如下:
<% @ taglib prefix=”someprefix” uri=”/sometaglib” %>
1.从一个指定的标签库中识别出代表这种自定义行为的标签
2.找到实现这些自定义行为的具体类
自定义JSP标签的处理过程:
1.在JSP中引入标签库:
2.在JSP中使用标签库标签:
3.Web容器根据第二个步骤中的prefix,获得第一个步骤中声明的taglib的uri属性值
4.Web容器根据uri属性在web.xml找到对应的元素
5.从元素中获得对应的元素的值
6.Web容器根据元素的值从WEB-INF/目录下找到对应的.tld文件
7.从.tld文件中找到与tagname对应的元素
8.凑元素中获得对应的元素的值
9.Web容器根据元素的值创建相应的tag handle class的实例
10. Web容器调用这个实例的doStartTag/doEndTag方法完成相应的处理
public class TipMsgTag extends BodyTagSupport{
/**参数参数*/
private static final long serialVersionUID = -6910550230181838779L;
@SuppressWarnings("static-access")
@Override
public int doStartTag() throws JspException {
//使用try catch
try {
//request
HttpServletRequest request = (HttpServletRequest)this.pageContext.getAttribute(this.pageContext.REQUEST);
HttpSession session = request.getSession();
JspWriter out = this.pageContext.getOut();
Object successMsg = request.getAttribute(Constant.SUCCESS);
if(successMsg!=null){
request.removeAttribute(Constant.SUCCESS);
}
else{
successMsg = session.getAttribute(Constant.SUCCESS);
session.removeAttribute(Constant.SUCCESS);
}
if(successMsg!=null){
out.print("<div class='successMSG'>"+successMsg+"</div>");
}
Object errMsg = request.getAttribute(Constant.ERROR);
if(errMsg!=null){
request.removeAttribute(Constant.ERROR);
}
else{
errMsg = session.getAttribute(Constant.ERROR);
session.removeAttribute(Constant.ERROR);
}
if(errMsg!=null){
out.print("<div class='errorMSG'>"+errMsg+"</div>");
}
}
catch (IOException e) {
throw new SysException(e.getMessage(),e);
}
return super.doStartTag();
}
}
2.X-Requested-With有什么作用?
X-Requested-With头域是用来判断一个请求是传统的HTTP请求,还是Ajax请求。
if(request.getHeader("X-Requested-With") != null
&&request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")){
out.print("该请求是 AJAX 异步HTTP请求。");
}else{
out.print("该请求是传统的 同步HTTP请求。");
}
3.@ModelAttribute注解有何作用?
* 运用在参数上,会将客户端传递过来的参数按名称注入到指定对象中,并且会将这个对象自动加入ModelMap中,便于View层使用;
* 运用在方法上,会在每一个@RequestMapping标注的方法前执行,如果有返回值,则自动将该返回值加入到ModelMap中;
private static final ThreadLocal modelContainer = new ThreadLocal
4.@JoinColumn(name=”user”) 注解有什么用?
@JoinColumn注释的是保存表与表之间关系的字段,它要标注在实体属性上,而@Column标注的是表中不包含表关系的字段。 与@Column标记一样,name属性是用来标识表中所对应的字段的名称。
4.@ManyToOne(fetch=FetchType.EAGER) 注解有什么用?
fetch属性,设定关联对象的加载策略或方式。可选值如下: FetchType.LAZY:懒加载,关联对象不立刻加载(即从数据库读入到内存),在使用到的时候加载。 FetchType.EAGER:立刻加载,在加载主体对象时,同时加载关联属性对象。
5.@RequestMapping(value=”/scan”)注解其它设置?
@RequestParam 注解使用的时候可以有一个值,也可以没有值。这个值指定了需要被映射到处理方法参数的请求参数,
@RequestParam(value = "person", defaultValue = "John")