处理在 JavaScript 中的自定义 Servlet 异常,并在 JSP 中显示错误页面。

huangapple go评论89阅读模式
英文:

handle servlet custom exception in javascript and showing error page in jsp

问题

以下是你要翻译的内容:

从我的servlet中抛出异常,在eclipse控制台中,每当异常发生时,都会打印异常日志。但是我尝试在JSP页面中显示该异常,但未成功。

请查看下面的代码。

用于传递请求的代码:

function sendRequest(functionCallback, servletLocation, queryString) {
    var asyncRequest = newXMLRequest();

    // 设置处理程序函数以接收来自请求对象的回调通知
    var handleResponse = getReadyStateHandler(asyncRequest, functionCallback);
    asyncRequest.onreadystatechange = handleResponse;

    // 向servlet发送POST请求以获取信息。第三个参数指定请求为异步。
    asyncRequest.open("POST", servletLocation, true);

    asyncRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    asyncRequest.send(queryString);

    if (document.getElementById("filterMessage") != null) {
        document.getElementById("filterMessage").innerHTML = "<span class='red'>Filtering...Please Wait</span>";
    }
}

处理响应的代码:

function getReadyStateHandler(req, responseXmlHandler) {

    // 返回一个监听XMLHttpRequest实例的匿名函数
    return function () {
        // 如果请求的状态是“完成”
        if (req.readyState == 4) {
            // 检查是否收到了成功的服务器响应
            if (req.status == 200) {
                // 将响应的XML数据传递给处理函数
                responseXmlHandler(req.responseXML);
            } else {
                // 发生了HTTP问题
                alert("HTTP error: " + req.status);
            }
        }
    }
}

function reloadPage() {
    window.location.reload(true);
}

从下面的代码调用servlet:

function updateProgramVersion(e) {
    var washoutIdStr = (e.target || e.srcElement).parentNode.parentNode.parentNode.children.sparWashoutId.children.washoutItem.value;
    var programVersionStr = (e.target || e.srcElement).parentNode.parentNode.parentNode.children.programVersionModify.children.programVersion.value;
    var sparNumber = (e.target || e.srcElement).parentNode.parentNode.parentNode.children.sparNumber.children.sparNumber.value;

    if ((e.target || e.srcElement).id == 'programVersionUpdatebtn') {
        query = 'actionId=updateProgramVersion&washoutIdStr=' + washoutIdStr + "&programVersion=" + programVersionStr + "&sparNumber=" + sparNumber;
        servlet = "<%=UrlBuilder.getServletRoot() + ApplicationConstants.SERVLET_REPORT_SPAR%>";
        method = "POST";
        sendRequest(reloadPage, servlet, query);   // servlet调用
        (e.target || e.srcElement).parentNode.parentNode.parentNode.children.programVersion.style.display = 'none';
        (e.target || e.srcElement).parentNode.parentNode.parentNode.children.programVersionTD.style.display = 'block';
    }
}

以下是你提供的servlet代码:

else if (actionId.equals("updateProgramVersion")) {
    updateProgramVersion(washoutId, sparNumber, programVersion);
    //nextPage = mappings.findForward("display");
}

private void updateProgramVersion(String washoutId, String sparNumber, String programVersion) throws ApplicationException {

    boolean isExist = sparwashoutService.getProgramVersion(washoutId, sparNumber, programVersion);

    if (isExist) {
        sparwashoutService.updateProgramVersion(washoutId, sparNumber, programVersion);
    } else {
        throw new InvalidInputException("Version number is not valid", "Version number is not valid", this.getClass().toString().substring(getClass().toString().lastIndexOf(".") + 1) + ".performTask()");
    }
}
英文:

Am throwing exception from my servlet and in the eclipse console its printing the exception logs whenever exception is occured. But am trying to show that exception in JSP pages that am not getting.

Please find my code below.

code to pass the request :

function sendRequest( functionCallback, servletLocation, queryString)
{
	var asyncRequest = newXMLRequest();

	// Set the handler function to receive callback notifications from the request object
	var handleResponse = getReadyStateHandler(asyncRequest, functionCallback);
	asyncRequest.onreadystatechange = handleResponse;
	
	// Send a POST to servlet for information.  Third parameter specifies request is asynchronous.
	asyncRequest.open(&quot;POST&quot;, servletLocation, true);

	asyncRequest.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;);	
	asyncRequest.send(queryString);
	
	if ( document.getElementById(&quot;filterMessage&quot;) != null )
	{
		document.getElementById(&quot;filterMessage&quot;).innerHTML = &quot;&lt;span class = &#39;red&#39;&gt;Filtering...Please Wait&lt;/span&gt;&quot;;	
	}
}

code to handle the respose :

function getReadyStateHandler(req, responseXmlHandler) 
{

	// Return an anonymous function that listens to the 
	// XMLHttpRequest instance
	return function () 
	{
		// If the request&#39;s status is &quot;complete&quot;
		if (req.readyState == 4)
		{			
			// Check that a successful server response was received
			if (req.status == 200) 
			{
				// Pass the XML payload of the response to the 
				// handler function
				responseXmlHandler(req.responseXML);
			}
			else 
			{
				// An HTTP problem has occurred
				alert(&quot;HTTP error: &quot; + req.status);
			}
		}
	}
}



function reloadPage() {
	window.location.reload(true);
}

invoking servlet call from the below code.

function updateProgramVersion(e) {
	var washoutIdStr = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.sparWashoutId.children.washoutItem.value;
	var programVersionStr = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersionModify.children.programVersion.value;
	var sparNumber = (e.target || e.srcElement ).parentNode.parentNode.parentNode.children.sparNumber.children.sparNumber.value
	
	if( (e.target || e.srcElement ).id == &#39;programVersionUpdatebtn&#39;) {
		query = &#39;actionId=updateProgramVersion&amp;washoutIdStr=&#39;+washoutIdStr+&quot;&amp;programVersion=&quot;+ programVersionStr+&quot;&amp;sparNumber=&quot;+sparNumber;
		servlet = &quot;&lt;%=UrlBuilder.getServletRoot() + ApplicationConstants.SERVLET_REPORT_SPAR%&gt;&quot;; method=&quot;POST&quot;;
		sendRequest(reloadPage, servlet, query);   // servlet call
		(e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersion.style.display = &#39;none&#39;;
		(e.target || e.srcElement ).parentNode.parentNode.parentNode.children.programVersionTD.style.display = &#39;block&#39;;
	}
	
}

Please find my below servlet code :

	else if(actionId.equals(&quot;updateProgramVersion&quot;)) {
		updateProgramVersion(washoutId, sparNumber,  programVersion);
		//nextPage = mappings.findForward(&quot;display&quot;);
	}

private void updateProgramVersion(String washoutId, String sparNumber,  String programVersion) throws ApplicationException{
	
	boolean isExist = sparwashoutService.getProgramVersion(washoutId, sparNumber, programVersion);
	
	if(isExist) {
		sparwashoutService.updateProgramVersion(washoutId, sparNumber, programVersion);
	} else {
		throw new InvalidInputException(&quot;Version number is not valid&quot;,&quot;Version number is not valid&quot;,this.getClass().toString().substring( getClass().toString().lastIndexOf(&quot;.&quot;) + 1 ) + &quot;.performTask()&quot;);
	}
	
}

答案1

得分: 1

以下是翻译好的内容:

Servlet 代码

try
{
  // 检查某些条件
  response.setContentType("text/xml");
  response.setCharacterEncoding("UTF-8");
  response.setStatus(200);	// 设置状态
  response.getWriter().write(yourxmldata);	// 发送消息
}
// 处理异常  
catch (Exception e)
{
  response.setContentType("text/plain");// 设置内容类型为文本
  response.setCharacterEncoding("UTF-8");
  response.setStatus(406);	// 设置状态
  response.getWriter().write(e.getMessage() + "我在异常中");	// 获取异常消息
}

而在 Ajax 中只需检查状态码:

if (req.status == 200)  {
  responseXmlHandler(req.responseXML);// 返回 XML
} else if(req.status == 406){
  alert(req.responseText);// 返回文本
}
英文:

You need to send back custom message which you need to show in jsp via servlet using response.getWriter().write().. also you can set status so that it will not enter inside if (req.status == 200) {... Here is example with try-catch block modify below code according to your requirement .

Servlet Code :

  try
  {
    //check some condition
    response.setContentType (&quot;text/xml&quot;);
    response.setCharacterEncoding (&quot;UTF-8&quot;);
    response.setStatus(200);	//set status
    response.getWriter().write(yourxmldata);	//send message
  }
  //handling the exception  
  catch (Exception e)
  {
    response.setContentType (&quot;text/plain&quot;);//set contenttype to text
    response.setCharacterEncoding (&quot;UTF-8&quot;);
    response.setStatus(406);	//set status
    response.getWriter().write (e.getMessage () + &quot;I AM IN EXECPETION&quot;);	//get your execption message

  }

and in Ajax just check the status code :

if (req.status == 200)  {
        responseXmlHandler(req.responseXML);//xml return
 } else if(req.status == 406){
       alert(req.responseText);//text return
 }

huangapple
  • 本文由 发表于 2020年10月3日 12:41:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/64180790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定