2.2、Action层
BaseAction.java
package com.rk.core.action;
import com.opensymphony.xwork2.ActionSupport;
import com.rk.core.entity.PageResult;
public abstract class BaseAction extends ActionSupport {
protected String[] selectedRow;
protected PageResult pageResult;
protected int pageNo;
protected int pageSize;
protected String searchContent;
public String[] getSelectedRow() {
return selectedRow;
}
public void setSelectedRow(String[] selectedRow) {
this.selectedRow = selectedRow;
}
public PageResult getPageResult() {
return pageResult;
}
public void setPageResult(PageResult pageResult) {
this.pageResult = pageResult;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getSearchContent() {
return searchContent;
}
public void setSearchContent(String searchContent) {
this.searchContent = searchContent;
}
}
其中对查询条件支持的字段有:
protected String searchContent;
其中对分页查询支持的字段有:
protected PageResult pageResult;
protected int pageNo;
protected int pageSize;
InfoAction.java 主要关注listUI()方法,其它方法只是为了参考和理解
//列表页面
public String listUI(){
//加载分类集合
ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
//分页数据查询
QueryHelper queryHelper = new QueryHelper(Info.class, "i");
try {
if(StringUtils.isNotBlank(searchContent)){
searchContent = URLDecoder.decode(searchContent, "UTF-8");
queryHelper.addCondition("i.title like ?", "%"+searchContent+"%");
}
} catch (Exception e) {
e.printStackTrace();
}
queryHelper.addOrderByProperty("i.createTime", QueryHelper.ORDER_BY_DESC);
String hql = queryHelper.getQueryListHql();
pageResult = infoService.getPageResult(queryHelper, pageNo, pageSize);
return "listUI";
}
//跳转到新增页面
public String addUI(){
//加载分类集合
ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
info = new Info();
info.setCreateTime(new Timestamp(new Date().getTime())); // 是为了在页面中显示出当前时间
return "addUI";
}
//保存新增
public String add(){
if(info != null){
infoService.save(info);
}
return "list";
}
//跳转到编辑页面
public String editUI(){
//加载分类集合
ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
if(info != null && info.getInfoId() != null){
info = infoService.findById(info.getInfoId());
}
return "editUI";
}
//保存编辑
public String edit(){
if(info != null){
infoService.update(info);
}
return "list";
}
//删除
public String delete(){
if(info != null && info.getInfoId() != null){
infoService.delete(info.getInfoId());
}
return "list";
}
//批量删除
public String deleteSelected(){
if(selectedRow != null){
for(String id : selectedRow){
infoService.delete(id);
}
}
return "list";
}
其中,searchContent/pageNo/pageSize/pageResult变量继承自父类(BaseAction)。
除了实现条件查询(分页查询)之外,还要在进行“删除和编辑”操作时,需要记录“查询关键字”、“页码”。而新增操作,则不需要记住原来的“查询关键字”和“页码”,因为我们进行添加操作后,想看到的就是自己新添加的对象,而不是原来查询条件下记录。
在struts-tax.xml中,action是进行如下映射的:
/WEB-INF/jsp/tax/info/{1}.jsp
info_listUI
${searchContent}
${pageNo}
true
此处对searchContent内容进行Url encode的转换,因为在listUI()方法代码中,
searchContent = URLDecoder.decode(searchContent, "UTF-8");
对于URLEncoder和URLDecoder的一个小测试 @Test
public void test() throws Exception{
String str = "中国";
String strEncode = URLEncoder.encode(str,"utf-8");
String strDecode = URLDecoder.decode(strEncode, "utf-8");
String strDecode2 = URLDecoder.decode(str, "utf-8");
System.out.println(str);
System.out.println(strEncode);
System.out.println(strDecode);
System.out.println(strDecode2);
} 输出 中国
%E4%B8%AD%E5%9B%BD
中国
中国 UrlEncoder的源码 public class URLDecoder {
// The platform default encoding
static String dfltEncName = URLEncoder.dfltEncName;
/**
* Decodes a application/x-www-form-urlencoded string using a specific
* encoding scheme.
*
* The supplied encoding is used to determine what characters
* are represented by any consecutive sequences of the form "%xy".
*
*
* Note: The World Wide Web Consortium Recommendation states that
* UTF-8 should be used. Not doing so may introduce incompatibilites.
*
*
* @param s the String to decode
* @param enc The name of a supported character encoding
* @return the newly decoded String
*/
public static String decode(String s, String enc)
throws UnsupportedEncodingException{
boolean needToChange = false;
int numChars = s.length();
StringBuffer sb = new StringBuffer(numChars > 500 ? numChars / 2 : numChars);
int i = 0;
if (enc.length() == 0) {
throw new UnsupportedEncodingException ("URLDecoder: empty string enc parameter");
}
char c;
byte[] bytes = null;
while (i < numChars) {
c = s.charAt(i);
switch (c) {
case '+':
sb.append(' ');
i++;
needToChange = true;
break;
case '%':
/*
* Starting with this instance of %, process all
* consecutive substrings of the form %xy. Each
* substring %xy will yield a byte. Convert all
* consecutive bytes obtained this way to whatever
* character(s) they represent in the provided
* encoding.
*/
try {
// (numChars-i)/3 is an upper bound for the number
// of remaining bytes
if (bytes == null)
bytes = new byte[(numChars-i)/3];
int pos = 0;
while ( ((i+2) < numChars) &&
(c=='%')) {
int v = Integer.parseInt(s.substring(i+1,i+3),16);
if (v < 0)
throw new IllegalArgumentException("URLDecoder: Illegal hex characters in escape (%) pattern - negative value");
bytes[pos++] = (byte) v;
i+= 3;
if (i < numChars)
c = s.charAt(i);
}
// A trailing, incomplete byte encoding such as
// "%x" will cause an exception to be thrown
if ((i < numChars) && (c=='%'))
throw new IllegalArgumentException(
"URLDecoder: Incomplete trailing escape (%) pattern");
sb.append(new String(bytes, 0, pos, enc));
} catch (NumberFormatException e) {
throw new IllegalArgumentException(
"URLDecoder: Illegal hex characters in escape (%) pattern - "
+ e.getMessage());
}
needToChange = true;
break;
default:
sb.append(c);
i++;
break;
}
}
return (needToChange? sb.toString() : s);
}
} |
3、JSP页面
3.1、pageNavigator.jsp
在WebRoot/common目录下
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
注意:在这最后一段Javascript中引用了一个list_url变量,它需要在主页面(listUI.jsp)内提供它的值。
3.2、listUI.jsp
<%@page import="org.apache.struts2.components.Include"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/common/header.jsp"%>
信息发布管理
知识点(1):在点击搜索的时候,要将页码设置为1
function doSearch(){
//重置页号
$('#pageNo').val(1);
document.forms[0].action = list_url;
document.forms[0].submit();
}
知识点(2):现在获取的显示数据不再是List对象,而是PageResult对象
知识点(3):为了引入通用的pageNavigator.jsp,需要定义一个list_url变量
var list_url = "${basePath}/tax/info_listUI.action";
引入页面
<%@include file="/common/pageNavigator.jsp" %>
3.3、editUI.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/common/header.jsp"%>
信息发布管理