Specifya target parameter for a servlet application - java

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

Related

Transmit data to Java application(servlet) in body of GET request

How can I process data that is transferred in the body of a GET-request using a servlet?
I use a small, hosted vServer (netcup), running Ubuntu 18.04 Server as OS and Tomcat 9.
To simulate the http requests I use Postman. In the code example below(its only the doGET-method) i realized a little program, that processes the incoming data "value1" from the query-string of the incoming GET-request. When i try to transmit the same parameter in the body of the message, i get the following error:
HTTP Status 500 ? Internal Server Error
Type: Exception Report, Message: null
Description: The server encountered an unexpected condition that prevented
it from fulfilling it from fulfilling the request
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:542)
java.lang.Integer.parseInt(Integer.java:615)
myServlet1.doGet(myServlet1.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
How do I have to modify the code to allow transmission via the GET-body? If i transmit the data with the querystring (for example) "http://localhost:8080...?value1=10" then it works fine.
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("/myServlet1")
public class myServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public myServlet1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
String value1s= request.getParameter("value1");
int a=Integer.parseInt(value1s); //
a=a+10;
writer.println("<html>");
writer.println("<head><title>Hello World Servlet</title></head>");
writer.println("<body>");
writer.println(" <h1>Hello value from a Servlet!</h1>");
writer.println("<h1>transmitted value: " + a + "</h1>");
writer.println("<body>");
writer.println("</html>");
writer.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am very grateful for every tip and hint!

NetBeans/Java - breakpoint can't catch exception

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";
}
}
}

Storing data into ArrayList through through servlets

I am attempting to write an application that will make use of 3 different servlets.
One will display information, the other will allow users to enter data and display it, and the last servlet would allow users to edit existing data.
I am having trouble finding a way to store the data into an ArrayList from one servlet and displaying in a table on the servlet that displays the info.
Here is what I have so far:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
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("/DisplayItems")
public class DisplayItems extends HttpServlet {
private static final long serialVersionUID = 1L;
public static ArrayList list = new ArrayList();
public DisplayItems() {
super();
// TODO Auto-generated constructor stub
}
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<String> list = (List<String>) getServletContext().getAttribute("data_list");
list.add("1");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Department Library</title>");
//out.println("<style>h1,h2,form,p{text-align:center;color:white}body{background-color:black;}</style></head>");
out.println("<body>");
out.println("<h1>Welcome to the Department Library</h1>");
out.println("<table border='1' cellpadding='2' cellspacing='2'>");
out.println("<thead><tr><th>ID</th><th>Type</th><th>Name</th><th>Addition Info</th><th>Available</th><th>Operation</th></tr><thead>");
out.println("<tr><td>"+list.get(1)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td>"+list.get(0)+"</td><td><a href='./EditItem'>Edit</a></td></tr>");
out.println("<p><a href='./AddItem'>Add Item</a></p>");
out.println("<p><a href='./EditItem'>Edit Item</a></p>");
//out.println("<form method='post'><input id='inputtext' name='inputtext'></inputText><input type='submit' value='Translate' name='submit'></input></form>");
out.println("</body></html>");
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
public void row(String id, String type, String name, String info ){
}
}
AddItem
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Array;
import javax.servlet.RequestDispatcher;
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("/AddItem")
public class AddItem extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddItem() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>Add Items</title>");
out.println("<body>");
out.println("<h1>Add Items</h1>");
out.println("<form method='post'");
//name=type
//name=name
//name=info
//name=copies
out.println("<table><tbody><tr><td>Type:</td><td><select name='type'><option>Book</option><option>Tablet</option> </select></td><tr>");
out.println("<tr><td>Name:</td><td><input name='name' size='60'/></td></tr>");
out.println("<tr><td>Additional Info:</td><td><input name='info' size='60' /></td></tr>");
out.println("<tr><td># of Copies:</td><td><input name='copies' size='8' /></td></tr>");
out.println("<tr><td colspan='2' rowspan='1'><input name='add' type='submit' value='Add' /></td></tr></tbody></table>");
out.println("</form>");
out.println("<p><a href='./DisplayItems'>Display Items</a></p>");
//out.println("<p><a href='./EditItem'>Edit Item</a></p>");
//out.println("<form method='post'><input id='inputtext' name='inputtext'></inputText><input type='submit' value='Translate' name='submit'></input></form>");
out.println("</body></html>");
out.close(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
request.getParameter("type");
String name = request.getParameter("name");
String info = request.getParameter("info");
String copies = request.getParameter("copies");
//type.add(value);
out.println(name);
out.println(info);
out.println(copies);
}
}
Edit : add the cast from getAttribute() to List
You could use store your ArrayList in a servlet context attribute to share it between all your servlets. But you should considere using a class to store data if it is more complex than a single String.
You could try to put something like that in init method of your servlets :
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
}
}
and then in get or post methods, you simply access the shared list as :
List<String> list = (List<String>) getServletContext().getAttribute("data_list");
As suggested by Vighanesh Gursale you could also use a HashMap, if your data has a natural key.
Edit2 :
To be sure of what is happening, you should use the debugger to see what is null or add logs like following : one in each init method after creating the attribute
if (context.getAttribute("data_list") == null) {
context.setAttribute("data_list", new ArrayList<String>());
log("Creating attribute data_list");
}
else {
log("Attribute data_list already created");
}
then in doGet :
ServletContext context = getServletContext();
log ((context == null) ? "Context null!?" : "Context ok");
Object attribute = context.getAttribute("data_list");
log((attribute == null) ? "Attribute null", attribute.toString());

Does RESTEasy support tunneling?

As mentioned in Restlet docs it has feature called "tunneling". Does this feature exist in RESTEasy too?
Servlet below supports "tunneling" by delegating "method" parameter from request.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher;
public class TunnelingDispatcher extends HttpServletDispatcher {
#Override
protected void service(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) throws ServletException,
IOException {
String method = httpServletRequest.getParameter("method");
if (method == null) {
method = httpServletRequest.getMethod();
} else {
method = method.toUpperCase();
}
service(method, httpServletRequest, httpServletResponse);
}
}

How to set response header in JAX-RS so that user sees download popup for Excel?

I wrote code that generate Excel file using REST JAX-RS and I confirmed that the generated Excel file is in GlassFish server directory.
But my goal is when user click on the button (which generate Excel .xls), I want download popup to show up asking user whether to save or open the .xls file just like any other web services doing for downloading any type of files.
According to my search, the step is:
generate Excel .xls (DONE)
write the excel to stream
in JAX-RS file, set response header to something like,
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
My question is I'm doing all of this in JAX-RS file and I don't have HttpServletResponse object available.
According to the answer from
Add Response Header to JAX-RS Webservice
He says:
You can inject a reference to the
actual HttpServletResponse via the
#Context annotation in your webservice
and use addHeader() etc. to add your
header.
I can't really figure what exactly that means without sample code..
You don't need HttpServletResponse to set a header on the response. You can do it using
javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
#Path("/resource")
class MyResource {
// one way to get HttpServletResponse
#Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(#Context HttpServletResponse servletResponse) {
// ... code
}
}
#Context ServletContext ctx;
#Context private HttpServletResponse response;
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#Path("/download/{filename}")
public StreamingOutput download(#PathParam("filename") String fileName) throws Exception {
final File file = new File(ctx.getInitParameter("file_save_directory") + "/", fileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() + "\"");
return new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException,
WebApplicationException {
Utils.writeBuffer(new BufferedInputStream(new FileInputStream(file)), new BufferedOutputStream(output));
}
};
}
I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.
package local.test.servlet;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
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 local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;
#WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
// /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
System.out.println(templateFileUrl.getPath());
String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
String outputFileDir = "MasatoExcelHorizontalOutput";
ReportProcessor reportProcessor = new ReportProcessor();
ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);
ReportSheet outputSheet = new ReportSheet("MySheet");
outputBook.addReportSheet(outputSheet);
reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
System.out.println("wtf???");
reportProcessor.process(outputBook);
System.out.println("done!!");
}
catch(Exception e) {
System.out.println(e);
}
} //end doGet()
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}//end class
class OutputStreamExporter extends ReportBookExporter {
private HttpServletResponse response;
public OutputStreamExporter(HttpServletResponse response) {
this.response = response;
}
#Override
public String getExtention() {
return null;
}
#Override
public String getFormatType() {
return ExcelExporter.FORMAT_TYPE;
}
#Override
public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {
System.out.println(book.getFirstVisibleTab());
System.out.println(book.getSheetName(0));
//TODO write to stream
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
book.write(response.getOutputStream());
response.getOutputStream().close();
System.out.println("booya!!");
}
catch(Exception e) {
System.out.println(e);
}
}
}//end class

Categories

Resources