1. 程式人生 > >java異常在實際開發中的應

java異常在實際開發中的應

異常是java的一大特色,用好了受益匪淺!不瞎扯了,開始寫用法,這裡控制層用的spring mvc!

思考問題,我們如何做才能使得service層徹底處理所有業務邏輯從而基本實現service和controller層的完全解耦?

所有做過開發的都知道,struts2在處理伺服器驗證的時候一般會把驗證邏輯放在action,這樣做沒有什麼不好,但是如果放在service是否更好,還有其他一些特殊的邏輯要放在service層,有時候特別不方便!現在,我講講我所使用的異常轉換問題,相信各位大神輕鬆理解,在自己實際專案中也可以用到!

以service層處理引數驗證問題為例:

1.定義parameter異常來封裝無需和資料庫互動的引數錯誤資訊:

public class ParameterException extends Exception {

	private static final long serialVersionUID = 1L;
	
	private Map<String, String> fields = new HashMap<String, String>();
	
	public Map<String, String> getFields() {
		return fields;
	}

	public void setFields(Map<String, String> fields) {
		this.fields = fields;
	}
	
	public void addFields(String key, String value) {
        fields.put(key, value);
    }

    public boolean isEmpty() {
        return fields.isEmpty();
    }

	public ParameterException() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ParameterException(String message, String flag) {
		super(message);
	}
	
	
}


</pre><p></p><pre>
2.定義ServiceException來封裝需要和資料庫互動的引數錯誤資訊,如密碼不正確
public class ServiceException extends Exception {
    private static final long serialVersionUID = 1L;

    private int code = 0;
    private String message = null;

    public ServiceException(int code, String message) {
        this.message = message;
        this.code = code;
    }

    public ServiceException() {

    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

}

3.Service層以login為例,驗證使用者名稱,密碼資訊:
@Override
	public User login(String userNumber, String password)
			throws ParameterException, ServiceException {//這裡丟擲具體的異常
		User user = null;
		password = DigestUtils.md5Hex(password);
		ParameterException parameterException = new ParameterException();
		if (StringUtil.isEmpty(userNumber) || StringUtil.isEmpty(password)) {
			parameterException.addFields("loginMessage", "使用者名稱或密碼為空");
			throw parameterException;
		}
		user = userDao.getUserByUserNumber(userNumber);
		if (user == null) {
			throw new ServiceException(10000, "使用者不存在");
		} else if (!password.equals(user.getPassword())
				&& !userNumber.equals(user.getUserName())) {
			throw new ServiceException(10001, "密碼不正確");
		}
		return user;
	}

4.controller層處理異常,返回資訊到頁面:
@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(String userNumber, String password, HttpSession session) {
		ModelAndView mav = null;	
		User user = null;
		try {
			user = userService.login(userNumber, password);
		} catch (ParameterException parameterException) {//這裡進行catch操作,出現異常則返回資訊到頁面
			Map<String, String> fields = parameterException.getFields();
			mav = new ModelAndView("login");
			mav.addObject("fields", fields);
			return mav;
		} catch (ServiceException serviceException) {
			mav = new ModelAndView("login");
			mav.addObject("loginMessage", serviceException.getMessage());
			return mav;
		}
		user.setPassword(null);
		session.setAttribute("user", user);
		Role role = null;
		if(user != null) {
			role = userService.getRoleByUserId(user.getId());
			session.setAttribute("roleName", role.getRoleName());
			if("系統管理員".equals(role.getRoleName())) {
				mav = new ModelAndView(new RedirectView("list", true));
			}
			if("學生".equals(role.getRoleName())) {
				 mav = new ModelAndView(new RedirectView("/student/list", true));
			}
			if("老師".equals(role.getRoleName())) {
				mav = new ModelAndView(new RedirectView("/teacher/list", true));
			}
		}
		return mav;
	}

5.頁面拿到錯誤資訊並展示:
<form action="${pageContext.request.contextPath }/user/login" method="post" id="login">
	<div class="loginTop">
		<div class="sysNameStyle">
			<div class="sysNameLocate"></div>
		</div>
	</div>
	<div class="loginBottom">
		<div class="userName">
			<div class="labelStyle">
				學號:
			</div>
			<div class="inputStyle">
				<input type="text" name="userNumber" id="userNumber" class="inputWidth"/>
			</div>
			<div class="errorMessage">
				${loginMessage }${fields['loginMessage'] }
			</div>
		</div>
		
		<div class="passWord">
			<div class="labelStyle">
				密碼:
			</div>
			<div class="inputStyle">
				<input type="password" name="password" id="passWord" class="inputWidth"/>
			</div>
		</div>
		
		<div class="submit">
			<div class="resetLocate">
				<input type="reset" value="取消" class="submitStyle"/>
			</div>
			<div class="submitLocate">
				<input type="submit" value="登陸" class="submitStyle"/>
			</div>
		</div>
	</div>
</form>