struts2 声明式异常处理

struts.xml

(1)Action中进行异常映射(局部的,针对单个action)

(2)package中进行异常映射(全局的,其他package中的action要用到这个异常,需要继承这个异常package)





    
    
    
	
		
			/error.jsp
		
		
		
			
		
	
 	
 	
	
		
		
		
		
			/admin/index.jsp
		
		
		
			/admin/Category_list.jsp
			category!list
			/admin/Category_update.jsp
			/admin/Category_add.jsp
			
			


			
		
		
	

	
		
		
		
		
			/index.jsp
		
		
	

 

CategoryAction.java

package com.test.bbs.action;

import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.test.bbs.model.Category;
import com.test.bbs.service.CategoryService;

public class CategoryAction extends ActionSupport {

	private CategoryService objCategoryService = new CategoryService();
	private List lstCategory;

	public String list() throws Exception {
		lstCategory = objCategoryService.list();
		return SUCCESS;
	}

	public List getLstCategory() {
		return lstCategory;
	}

	public void setLstCategory(List lstCategory) {
		this.lstCategory = lstCategory;
	}

}

 

CategoryService.java

package com.test.bbs.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.test.bbs.model.Category;
import com.test.bbs.util.DB;

public class CategoryService {

	/**
	 * 获取所有的种类
	 * 
	 * @return
	 */
	public List list() throws SQLException {
		List lstCategory = new ArrayList();
		Connection conn = DB.getConnection();
		String sql = "select * from _category";
		PreparedStatement pstmt = DB.getStatement(conn, sql);
		ResultSet rs = null;
		try {
			rs = pstmt.executeQuery();
			Category objCategory = null;
			while (rs.next()) {
				objCategory = new Category();
				objCategory.setId(rs.getInt("id"));
				objCategory.setName(rs.getString("name"));
				objCategory.setDescription(rs.getString("description"));

				lstCategory.add(objCategory);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw (e);// 异常抛给struts框架去处理
		} finally {
			DB.close(rs);
			DB.close(pstmt);
			DB.close(conn);
		}
		return lstCategory;
	}

}

 

struts2中异常处理由拦截器实现的(观察struts-default.xml),实际上struts2的大多数功能都是由拦截器实现的。

你可能感兴趣的:(struts2)