struts2

xiaoxiao2021-02-28  116

1. 条件查询 <1>sql语句生成

String sql = "select * from s_user where 1=1 "; List<Object> params=new ArrayList<Object>(); String username = user.getUserName(); if (username != null && username.trim().length() > 0) { sql += " and userName like ?"; params.add("%"+username+"%"); } String sex = user.getSex(); if (sex != null && sex.trim().length() > 0) { sql += " and sex=?"; params.add(sex); } String education = user.getEducation(); if (education != null && education.trim().length() > 0) { sql += " and education=?"; params.add(education); } String isupload = user.getIsUpload(); if ("1".equals(isupload)) { sql += " and filename is not null"; } else if ("2".equals(isupload)) { sql += " and filename is null"; }

<2>参数怎样传递?  创建一个List,在每一次判断时,直接将参数添加到集合中,最后将集合转换成Object[],做为参数传递到query方法中。

QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); return runner.query(sql, new BeanListHandler<User>(User.class),params.toArray());

2. 删除操作 <1>修改JSP页面上的链接标签 原标签:

<a href="${pageContext.request.contextPath}/user/list.jsp?userID=15"> <img src="${pageContext.request.contextPath}/images/i_del.gif" width="16" height="16" border="0" style="CURSOR: hand"> </a>

使用struts2标签修改:

<1>第一种方式 <s:a href="路径"> <2>第二种方式 <s:a action="" namespace=""> <s:param name="" value=""> </s:a> <3>第三种方式 <s:url>标签来定义一个路径 <s:a href="url">来导入url值 <s:url namespace="/" action="user_del" var="delUrl"> <s:param name="id" value="%{#u.userID}"/> </s:url> <s:a href="%{#delUrl}"> <img src="${pageContext.request.contextPath}/images/i_del.gif" width="16" height="16" border="0" style="CURSOR: hand"> </s:a>

3. 异常处理  对于action中的操作,出现问题,直接抛出自定义异常。  在struts.xml文件中:

//这就可以让特定的异常,跳转到自定的页面。 <global-exception-mappings> <exception-mapping result="login" exception="cn.itcast.user.exception.FindByIdException"> </exception-mapping> </global-exception-mappings>

 struts2,默认加载的18个拦截器的第一个是exception这个拦截器,它没有做任何操作,直接放行,,只是它将 invocation.invoke()操作使用try-catch进行了处理。 其它的拦截器,或是action只要向外抛出异常,exception拦截器就会将其捕获。

转载请注明原文地址: https://www.6miu.com/read-58455.html

最新回复(0)