I'm trying to get the output from a servlet on an Android phone.
This is my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package main;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Bert Verhelst <verhelst_bert#hotmail.com>
*/
public class servlet1 extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet servlet1</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>processing...</h1>");
out.println("</body>");
out.println("</html>");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>doget...</h1>\n"
+ "</body></html>");
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\">\n"
+ "<html>\n"
+ "<head><title>Hello WWW</title></head>\n"
+ "<body>\n"
+ "<h1>dopost...</h1>\n"
+ "</body></html>");
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is my Android main page:
package be.smarttelecom.MyTest;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView output = (TextView) findViewById(R.id.output);
try {
output.append("starting\n");
RestClient client = new RestClient("http://10.0.0.188:8084/Servlet_1/servlet1");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
output.append("after execute\n");
String response = client.getResponse();
output.append("class - " + response + "\n" );
output.append(response);
output.append("done\n");
}
catch (Exception ex) {
output.append("error: " + ex.getMessage() + "\n" + ex.toString() + "\n");
}
}
}
And finally we have the RestClient:
package be.smarttelecom.MyTest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + p.getValue();
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
}
catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Unfortunately this doesn't work. Here is what I get for output (null),
What am I doing wrong?
I request the DoGet method of my servlet and convert the output to a string, but it appears to be empty.
I allowed the Internet connection in the manifest file just after the closing bracket of application,
<uses-permission android:name="android.permission.INTERNET" />
Romain Hippeau wrote in a comment:
Does the call ever get to the servlet? What does the server see is being sent? What is the server sending back?
That was the problem! I disabled my firewall and now it works :)
Related
This question already has answers here:
How to use a servlet filter in Java to change an incoming servlet request url?
(4 answers)
Closed 5 years ago.
I have created a webapp and I am modifying the parameters from the url to decrypt one of the parameters. After decrypting I want to append the parameters to a new URL so that I can get expected response. I have created a HTML which collects input and the landing page is a Java page inbetween I am intercepting the request. I do not want the request to go to the landing page instead I want to send it to a new url.
below is my filter code.
package com.test.secondServlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Servlet Filter implementation class SecondFilter
*/
#WebFilter("/SecondFilter")
public class SecondFilter implements Filter {
public String decryptedString;
private static final String characterEncoding = "UTF-8";
Properties prop = new Properties();
InputStream input = null;
public String globalKey;
public String RedirectURL;
public String DN;
public String TYPE;
public String NAME;
public String NUMBER;
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//chain.doFilter(req, res);
HttpServletRequest request = (HttpServletRequest) req;
//String requestURI = request.getRequestURI();
//System.out.println(requestURI);
String url = ((HttpServletRequest)request).getRequestURL().toString() +"?"+request.getQueryString();
System.out.println(url);
String queryString = ((HttpServletRequest)request).getQueryString();
DN = ((HttpServletRequest) request).getParameter("DN");
TYPE = ((HttpServletRequest) request).getParameter("TYPE");
NAME = ((HttpServletRequest) request).getParameter("NAME");
NUMBER = ((HttpServletRequest) request).getParameter("encryptedssn");
// String key = ((HttpServletRequest) request).getParameter("aeskey");
//Code to load key from property file
try {
String filename = "Secretkey.properties";
input = SecondFilter.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
System.out.println("Sorry, unable to find " + filename);
return;
}
//load a properties file from class path, inside static method
prop.load(input);
//get the property value and print it out
globalKey=prop.getProperty("Secretkey");
System.out.println("Global Key : "+globalKey);
} catch (IOException ex) {
ex.printStackTrace();
}
//code ends
if (queryString!=null) {
//decryptingssnhere
byte[] clearText;
try {
clearText = AesEncryption.decryptBase64EncodedWithManagedIV(NUMBER, globalKey);
decryptedString = new String(clearText,characterEncoding);
System.out.println("ClearText:" +decryptedString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println("ClearText:" + new String(clearText,characterEncoding));
//if(url.startsWith("/SSNdecrypt/SSNdecrypt")){
System.out.println("queryString :"+queryString);
System.out.println("DN : "+DN);
System.out.println("TYPE : "+TYPE);
System.out.println("NAME : "+NAME);
System.out.println("S1/ NUMBER : "+NUMBER);
//System.out.println("key : "+key);
System.out.println("decrypted S1/ Number : "+decryptedString);
//String toReplace = url.substring(38);
System.out.println("input : "+input);
//String Redirect = "SSNdecrypt?"+queryString.substring(0,13)+decryptedString;
//System.out.println("redirect : "+Redirect);
//String newURI = url.replace(queryString, Redirect);
//System.out.println("new URL"+newURI);
//String newURI = url.concat("?"+newquerystring);
RedirectURL = "http://differentservername.com/contentexplorer/servlet/VipDms?";
String Redirect =RedirectURL+"DN="+DN+"&TYPE="+TYPE+"&NAME="+NAME+"&-NUMBER="+decryptedString;
System.out.println("redircting new URL for DOCVIEW : "+Redirect);
final HttpServletRequestWrapper wrapped = new HttpServletRequestWrapper(request) {
#Override
public StringBuffer getRequestURL() {
final StringBuffer originalUrl = ((HttpServletRequest) getRequest()).getRequestURL();
return new StringBuffer(Redirect);
}
};
//chain.doFilter(wrapped, res);
wrapped.getRequestDispatcher(Redirect).forward(wrapped, res);
} else {
chain.doFilter(req, res);
}
//SSNdecrypt/SSNdecrypt?encryptedssn=1234
//res.getWriter().println(requestURI.toString());
/**if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}**/
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
}
I do not want to use the urlrewriter and would like to do it in the same filter. how do I change the requested URL?
I am using HttpServletResponse resp = (HttpServletResponse) res; resp.sendRedirect(Redirect); instead of forwarding the request which is wrapped.getRequestDispatcher(Redirect).forward(wrapped, res);. Instead of using the request qrapper I am using the HTTP response wrapper and I was able to modify the complete URL from the request url.
I made a JSP that is supposed to upload a file into a directory and it shows me an error when trying to connect:
Here you can see my codes:
If anyone can help me i would appriciate it.
package src;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
public class Controller extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
String saveFile="c:\\uploaddir\\";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String actiune="afiseaza";
PrintWriter out=response.getWriter();
if (request.getParameter("actiune")!=null)
{
actiune = request.getParameter("actiune");
}
if (actiune.equals("afiseaza"))
{
doAfiseaza(request, response);
}
if (actiune.equals("sterge"))
{
doDeleteFile(request, response);
}
try{
boolean ismultipart=ServletFileUpload.isMultipartContent(request);
if(!ismultipart)
{
}
else
{
FileItemFactory factory= new DiskFileItemFactory();
ServletFileUpload upload= new ServletFileUpload(factory);
List items=null;
try{
items=upload.parseRequest(request);
}catch(Exception e)
{
}
Iterator itr=items.iterator();
while(itr.hasNext())
{
FileItem item= (FileItem)itr.next();
if(item.isFormField())
{
}
else
{
String itemname=item.getName();
if((itemname==null)||itemname.equals(""))
{
continue;
}
String filename=FilenameUtils.getName(itemname);
File f=checkExist(filename);
item.write(f);
}
}
}
}catch(Exception e)
{
}
finally{
out.close();
}
}
private void doDeleteFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String fName=URLDecoder.decode(request.getParameter("fis"));
File f = new File("c:\\uploaddir\\"+fName);
f.delete();
doAfiseaza(request, response);
}
private void doAfiseaza(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String dir = "c:\\uploaddir";
int er = 0;
File[] lista = null;
try
{
File f = new File(dir);
lista = f.listFiles();
}
catch(Exception ex)
{
er=-1;
}
request.setAttribute("eroare", new Integer(er));
request.setAttribute("lista", lista);
RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/lista.jsp");
rd.forward(request, response);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Prima aplicatie";
}// </editor-fold>
private File checkExist(String fileName) {
File f=new File(saveFile+"/"+fileName);
if(f.exists())
{
StringBuffer sb=new StringBuffer(fileName);
sb.insert(sb.lastIndexOf("."), "-"+new Date().getTime());
f=new File(saveFile+"/"+sb.toString());
}
return f;
}
}
so now i have no errors but it doesnt upload my folder so i dont know what to do.
Since your original question was about JSP, here is some demonstration code.
<%# page import="java.util.*,
java.io.*,
org.apache.commons.fileupload.*,
org.apache.commons.fileupload.servlet.*,
org.apache.commons.fileupload.disk.*,
org.apache.commons.fileupload.util.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
out.print("Request content length is " + request.getContentLength() + "<br/>");
if(isMultipart){
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
FileItemStream item = null;
String name = "";
InputStream stream = null;
while (iter.hasNext()){
item = iter.next();
name = item.getFieldName();
stream = item.openStream();
if(item.isFormField()){out.println("Form field " + name + " with value "
+ Streams.asString(stream) + "<br/>");}
else {
name = item.getName();
if(name != null && !"".equals(name)){
String fileName = new File(item.getName()).getName();
out.println("Client file " + item.getName() + " <br/>with file name "
+ fileName + " uploaded.<br/>");
File file = new File("C:/uploaddir/" + fileName);
FileOutputStream fos = new FileOutputStream(file);
long fileSize = Streams.copy(stream, fos, true);
out.print(fileName
+ " was uploaded to the fileUploads folder. Size was " +
fileSize + "<br/>");
}
}
}
} else out.print("Wrong request type!");
%>
call that JSP with
<html><body>
<form enctype="multipart/form-data" action="fileUpload3.jsp" method="post">
<input type='file' name='file1'/><br/>
<input type='file' name='file2'/><br/>
<input type='file' name='file3'/><br/>
Type message:<input type="text" name="message" /><br/>
<input Type='submit' value='Submit'/>
</form>
</body></html>
Put both files in your web app's root folder.
I'm running a page trying to export an Excel file through a Java Servlet. A rundown of the structure:
downloadreports.jsp is where the button is that is supposed to call the file. The button calls ReportsServlet.java, which is just the download and that in turn calls ExcelCreatorBanned.java, which calls the database and creates the Excel file.
The problem is that 1) when I try to click on downloadreports.jsp when running the full site, it automatically goes to the ReportsServlet instead of displaying the page (turning up a 404 error for /Reports) and 2) I've been messing with this for days and it's just not working. Not sure what I'm doing wrong, but any help would be very appreciated!
downloadreports.jsp
<div align="center">
<form id="downloadBanned" action="../Reports" method="post">`
<input class="btn btn-lg btn-red" type="submit" value="Download Banned Student List"><br> `
</form>`
ReportsServlet.java
package controllers;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import helpers.ExcelCreatorBanned;
/**
* Servlet implementation class ReportsServlet
*/
#WebServlet({ "/ReportsServlet", "/Reports" })
public class ReportsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private HttpSession session;
private String url;
/**
* #see HttpServlet#HttpServlet()
*/
public ReportsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.session = request.getSession(false);
ExcelCreatorBanned ecb = new ExcelCreatorBanned();
ecb.downloadExcel();
url = "admin/downloadreports.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
private Object getOutputStream() {
// TODO Auto-generated method stub
return null;
}
}
ExcelCreatorBanned.java (The reference to DbConnect.java is the credentials to the server, and it definitely works because it works on the other pages)
package helpers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletOutputStream;
import model.DbConnect;
import java.sql.Statement;
public class ExcelCreatorBanned {
public String downloadExcel( ) { //ServletOutputStream out){
String outFileName = "BannedStudents.csv";
int nRow = 1;
String strQuery = null;
Connection con = null;
try {
// Getting connection here for mySQL database
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DbConnect.devCredentials();
System.out.println(con);
if(con==null)
return "Connection Failed";
// Database Query
strQuery = "select * from banned";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(strQuery);
File file = new File(outFileName);
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//Get Titles
String titleLine = "BannedID" + "," + "UserID" + "," + "AdminID"
+ "," + "Ban Start Date" + "," +
"Ban End Date" + "," + "Penalty Count" + "," +
"Description" + "," + "Status" + "\n";
out.write(titleLine);
//stmt = conn.createStatement();
while (rs.next()) {
int BannedId = rs.getInt(1);
int UserID = rs.getInt(2);
int AdminID = rs.getInt(3);
String BanStartDate = rs.getString(4);
String BanEndDate = rs.getString(5);
int PenaltyCount = rs.getInt(6);
String Description = rs.getString(7);
String Status = rs.getString(8);
String outline = BannedId + "," + UserID + "," + AdminID +
"," + BanStartDate + "," +
BanEndDate + "," + PenaltyCount + "," + Description +
"," + Status + "\n";
out.write(outline);
} //end of while
out.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return outFileName;
}
}
I don't like the look of the action="../Reports" attribute in the line
<form id="downloadBanned" action="../Reports" method="post">
Try the following instead:
<form id="downloadBanned" action="${pageContext.request.contextPath}/Reports" method="post">
See this question for a discussion about what ${pageContext.request.contextPath} is.
I'm trying to build a simple gateway in Tomcat, which would do authorization checks and redirect the request to different endpoint, which gets the response and sends it back to the browser.
In Tomcat I have have a simple Servlet, which uses HttpURLConnection to connect to the endpoint, which gets the response and send it back to browser.
However in Chrome my URL always gets redirected to the endpoint domain. I don't see this behavior in IE or Firefox.
For example, this is deployed to hostname test.gateway.com.
If I make a http request test.gateway.com:9500/test/index.html from browser, Servlet should make a http request to test.endpoint.com/test/index.html and return the response. Client browser should remain on test.gateway.com:9500/test/index.html
However on Chrome my URL changes to http://test.endpoint.com/test/index.html
In my web.xml I have URL Mapping which calls this servlet.
Here is the Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AppProxyServlet
*/
#WebServlet("/AppProxyServlet")
public class AppProxyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String proxy = "http://test.endpoint.com";
/**
* #see HttpServlet#HttpServlet()
*/
public AppProxyServlet() {
super();
// TODO Auto-generated constructor stub
}
private String callEndpoint(HttpServletRequest request, String plexURL)
throws Exception {
// make
String queryString = request.getQueryString();
if (queryString != null && queryString.length() > 0) {
plexURL += "?" + queryString;
}
URL obj = new URL(plexURL);
Cookie[] cookies = request.getCookies();
StringBuffer allCookies = new StringBuffer();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
// if( cookies[ i ].getName() == "SSO")
{
allCookies.append(cookies[i].getName());
allCookies.append("=");
if ("SSO".equals(cookies[i].getName())) {
String ssostr = cookies[i].getValue();
allCookies.append(ssostr);
} else {
allCookies.append(cookies[i].getValue());
}
if (i < cookies.length)
allCookies.append(";");
// con.setRequestProperty("Cookie", cookies[ i
// ].getName()+"="+cookies[i].getValue());
}
}
}
System.out.println("All Cookies:" + allCookies.toString());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Accept-Charset", "ISO-8859-1");
con.setRequestProperty("Cookie", allCookies.toString());
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("\nSending Get request to URL:" + plexURL);
System.out.println("Response code:" + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream(), "ISO-8859-1")); // iso-8859-1
int value;
StringBuffer response = new StringBuffer();
while ((value = in.read()) != -1) {
char c = (char) value;
response.append(c);
}
con.disconnect();
return (response.toString());
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// ServletContext sc = getServletContext();
StringBuilder URL = new StringBuilder("");
String URI = request.getRequestURI();
System.out.println("Full URL:" + URI);
// Form the URL
URL.append(proxy);
URL.append(URI);
String sspResponse = "";
if (URI.endsWith("css")) {
response.setContentType("text/css");
} else {
response.setContentType("text/html;charset=ISO-8859-1");
}
PrintWriter printWriter = response.getWriter();
try {
sspResponse = callEndPoint(request, URL.toString());
} catch (Exception e) {
System.out.println(e.getStackTrace());
System.out.println("Some exception occured...");
}
printWriter.println(sspResponse);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.