NetBeans/Java - breakpoint can't catch exception - java

In NetBeans / Java - exception breakpoint (for Throwable) does not catch exceptions (RuntimeException in code of library for servlet). If you search tediously, you can find a purple stop line but without looking into the state of variables, etc. VS.NET does not have such ailments - it stops where you need it and everything is clear.
Is this a NetBeans problem or Java? How to get rid of breakpoint problems?

In here example would give you basic understanding of Exception Handling in Servlet
Actually putting a break point you can not catch a servlet exception because of it is happening before reaching the end point then you have to do something like this
When a servlet generates an error developers can handle those exceptions in various ways
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/SampleExceptionHandler")
public class SampleExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
exceptionProcessor(request, response);
}
private void exceptionProcessor(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
}
}

Related

Return ModelAndView from Spring when handling exceptions

Dealing with exceptionhandling in spring project.
I had followed this approach to handle the exceptions.
Everything is going good, but I want to return a ModelAndView instead of writing a text/html using PrintWriter object.
Following is the approach I followed.
ExceptionHandler.java
package com.test.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
/**
* Servlet implementation class ExceptionHandler
*/
#WebServlet("/ExceptionHandler")
public class ExceptionHandler extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
//processError(request,response);
handleException(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//processError(request,response);
handleException(request,response);
}
//I want this ModelAndView to be returned and should display the page that was set in ModelANdView object.
private ModelAndView handleException(HttpServletRequest request,HttpServletResponse response) throws IOException {
ModelAndView model = new ModelAndView("ErrorPage");
model.addObject("errMsg", "this is Exception.class");
return model;
}
//I don't want this approach.
/*private void processError(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// Analyze the servlet exception
Throwable throwable = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Integer statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request
.getAttribute("javax.servlet.error.servlet_name");
if (servletName == null) {
servletName = "Unknown";
}
String requestUri = (String) request
.getAttribute("javax.servlet.error.request_uri");
if (requestUri == null) {
requestUri = "Unknown";
}
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head><title>Exception/Error Details</title></head> <body>");
if(statusCode != 500){
out.write("<h3>Error Details</h3>");
out.write("<strong>Status Code</strong>:"+statusCode+"<br>");
out.write("<strong>Requested URI</strong>:"+requestUri);
}else{
out.write("<h3>Exception Details</h3>");
out.write("<ul><li>Servlet Name:"+servletName+"</li>");
out.write("<li>Exception Name:"+throwable.getClass().getName()+"</li>");
out.write("<li>Requested URI:"+requestUri+"</li>");
out.write("<li>Exception Message:"+throwable.getMessage()+"</li>");
out.write("</ul>");
}
out.write("<br><br>");
out.write("Home Page");
out.write("</body></html>");
}*/
}
And in web.xml I had added following tag to set location for error.
<error-page>
<error-code>404</error-code>
<location>/ExceptionHandler</location>
</error-page>
EDIT: I know that void cannot return ModelAndView Object , but looking for an approach to load the ErrorPage in case of invalid URL

ValidateLogin Internal Error 500

I'm attempting to create a login process using JSPs and linking them to my MySQL database. The issue I have encountered is an internal error (500) in my browser after I click "login".
I have setup my web.xml for the servlet ValidateLogin.java and I know that is not the issue. Can someone please help me here? I'll place down my code below that involves my HtmlServlet Request and Response.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidateLogin extends HttpServlet {
Connection connect;
ResultSet result;
String username, password, query;
DatabaseConnection database_connection;
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UF-8");
PrintWriter out = response.getWriter();
try {
// Code Here...
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
Nevermind, I worked out the issue...
Change code from to...
//FROM
response.setContentType("text/html;charset=UF-8");
//TO
response.setContentType("text/html");

Java servlet and a entity manager factory method for communicating mysql

I have a Java servlet and entity manager factory
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
this.setLevels(request);
if i use the line, then servlet does not work
//this.emf = Persistence.createEntityManagerFactory("projectPU");
servlet method continue...
out.println("this is a html content ....");
}
}
how to use Persistence.createEntityManagerFactory("projectPU") in servlet? Thanks.
Hej,
if you do not want to use any frameworks, as suggested above, you can do it for example like that:
I created a class called DataBroker, this is the class which contains the EntityManager and can persist entities or send queries againt the database.
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
public class DataBroker<T> {
private EntityManager em;
public DataBroker() {
if(em == null) {
em = Persistence.createEntityManagerFactory("ProjectPU").createEntityManager();
}
}
public void saveInput(T t) {
em.merge(t);
}
}
And now, for example a PersonServlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import de.professional_webworkx.database.DataBroker;
import de.professional_webworkx.model.Person;
#WebServlet(urlPatterns = {"/personServlet"})
public class PersonServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 318982491390578805L;
private DataBroker<Person> dataBroker = new DataBroker<>();
public PersonServlet() {
super();
}
protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// do something with the user input from the jsp file
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req, resp);
}
}
But it's right, these frameworks handle all this for you and you can be focused on your business logic or what else ;)
Patrick

Specifya target parameter for a servlet application

I just starting learning about servlets yersterday so I'm a newbie. I read a tutorial and made the following program to track the use of a link:
package red;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Redirection")
public class Redirection extends HttpServlet {
private static final long serialVersionUID = 1L;
private String referrer;
private String target;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
getURLs(request);
}
catch(Exception e)
{
response.sendError(500, "Target parameter not specified");
return;
}
response.sendRedirect(target);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
public void getURLs(HttpServletRequest request)
{
referrer = request.getParameter("referrer");
if(referrer == null || 0 == referrer.length())
{
referrer = new String("");
}
target = request.getParameter("target");
if(target == null || target.equals(""))
{
throw new IllegalArgumentException();
}
}
}
But when I teste it(Eclipse with Tomcat) i get this:
HTTP Status 500 - Target parameter not specified
How do I specify a target parameter in eclipse so I can run this program ?
Sorry for the beginner question.
Well you don't really know what's going on here. Maybe you're getting a different exception - you're giving that error message whatever goes wrong. You should log exactly what's being thrown. You also shouldn't generally catch Exception yourself - catch more specific exceptions.
Anyway, normally to include that sort of parameter, you'd just put it in the URL:
/Redirect?target=x&referrer=y

HTTP Status 405 - HTTP method POST is not supported by this URL

I am getting the error HTTP Status 405 - HTTP method POST is not supported by this URL when I use the following code(below) ... the line causing the trouble (apparently) is getServletContext().getRequestDispatcher("/EditObject?id="+objId).forward(request, response);
package web.objects;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.ObjDetailsDao;
#SuppressWarnings("serial")
public class EditObjectText extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int objId = Integer.parseInt(request.getParameter("objId"));
String text = (String)request.getParameter("description");
ObjDetailsDao oddao = new ObjDetailsDao();
try {
oddao.modifyText(text, objId);
/////////////
getServletContext().getRequestDispatcher("/EditObject?id="+objId).forward(request, response);
////////////
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT: I added the throws ServletException, IOException as suggested, but this did not change the error.
EDIT: the EditObject servlet looks like this
#SuppressWarnings("serial")
public class EditObject extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
int objId = Integer.parseInt(request.getParameter("id"));
dispPage(objId, request, response);
}
private void dispPage(int objId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// ... lots of code in here
getServletContext().getRequestDispatcher("/jsp/objectPageEdit.jsp").forward(request, response);
}
}
ANOTHER EDIT: So basically I can't do what I am doing. What I need is this, the user submits a post request and then I refer him/her back to a servlet which uses the Get method instead of Post. How can I do this referral without getting the error? Thanks in advance.
(sorry about the wrong answer I posted before, I deleted it).
Apparently the URL /EditObject is mapped on another servlet which doesn't have doPost() method overriden. It would be called on RequestDispatcher#forward() as well because the method of currently running HTTP request is POST. The default HttpServlet#doPost() implementation will return HTTP 405. If your actual intent is to fire a GET request on it so that the doGet() method will be invoked, then you should rather use HttpServletResponse#sendRedirect() instead.
response.sendRedirect("/EditObject?id="+objId);
Add a doPost() to your EditObject class:
#SuppressWarnings("serial")
public class EditObject extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
process(request, response);
}
public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
int objId = Integer.parseInt(request.getParameter("id"));
dispPage(objId, request, response);
}
private void dispPage(int objId, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
// ... lots of code in here
getServletContext().getRequestDispatcher("/jsp/objectPageEdit.jsp").forward(request, response);
}
}

Categories

Resources