We need to apply version control for our API, when the user send a request to our API endpoint i.e."http://mycompany/item?version=1", it will forwarded the request to itemServer_V1.java.
To achieve this goal, we have configured our web.xml as follows.
<servlet>
<servlet-name>item</servlet-name>
<servlet-class>com.mycompany.Servlet.ItemRequestHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>item</servlet-name>
<url-pattern>/item</url-pattern>
</servlet-mapping>
We create a table in MySQL database.
database table
ItemRequestHandler is a class which extends HttpServlet, and it supposed to forward the request to ItemServiceV1 or ItemServiceV2 according to the version parameter in the request.
I have finish the ItemService class but I don't know how to forward the request from ItemRequestHandler to ItemService class. Could someone let me know how to do that please?
ItemRequestHandler class is as follows
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException , IOException
{
String version = req.getParameter("version");
String fcd = req.getParameter("fcd");
String client = req.getParameter("client");
//Find the targetClass from database using the above information.
targetClass.doGet(req, res);
}
I find out a solution.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("LoginRequestHandler doPost");
String className = "";
String version = "";
String fcd = "login";
String compid = "";
RequestWrapper currentReq = new RequestWrapper(req);
version = currentReq.getParameter("Version");
compid = currentReq.getParameter("Compid ");
try {
className = findServletByVersion(compid, version, fcd);
Class<?> serviceClass = Class.forName(className);
Method method = serviceClass.getDeclaredMethod(MethodName.doPost.toString(), HttpServletRequest.class, HttpServletResponse.class);
method.invoke(serviceClass.newInstance(), currentReq, res);
return;
}catch(Exception e) {
System.out.println(e.toString());
} catch (DataNotFound e) {
System.out.println(e.toString());
}
}
}
Code of RequestWrapper
public class RequestWrapper extends HttpServletRequestWrapper {
private String _body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
_body = "";
BufferedReader bufferedReader = request.getReader();
String line;
while ((line = bufferedReader.readLine()) != null){
_body += line;
}
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(_body.getBytes());
return new ServletInputStream() {
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
}
Code of findServletByVersion
public String findServletByVersion(String compid, String version, String fcd) throws SQLException, ClassNotFoundException, DataNotFound {
String clsName = "";
Connection con = null;
Statement stmt = null;
User user = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://YourIpAddress:PortNum/"+schemaName,"account","password");
String query = "SELECT * FROM "+compid+".restfcd "
+ "WHERE 1=1 "
+ "AND compid = '"+compid+"'"
+ "AND version = '"+version+"'"
+ "AND fcd = '"+fcd+"'"
+ "ORDER BY compid desc";
System.out.println(query);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs!=null) {
while (rs.next()) {
clsName = rs.getString("fcdcls");
}
}
if(Func.isEmpty(clsName)) {
throw new DataNotFound("findServletByVersion : no match result!");
}
return clsName;
} catch (SQLException e) {
throw new SQLException("findServletByVersion : SQLException!");
} catch (ClassNotFoundException e) {
throw new ClassNotFoundException("findServletByVersion : ClassNotFoundException!");
} finally {
try {
con.close();
stmt.close();
} catch (SQLException sqlee) {
throw new SQLException("Cannot close conection/statement!");
}
}
}
Related
I have one application in which i am restricting the user for multiple loggin from different devices. For that i took two column in my table status and ip. If user already logged in from one computer then he is able to login again from same machine but when he try to logged in from another then the ip of new machine will be assigned. but he is able to access from previous computer. Why? how to logged out him? And also if i logged out from one browser he is able to access from another browser if he logged in from both browser. How to logged out him from all browsers?
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LoginServlet..........");
InetAddress address;
//String hostname;
byte[] ip = new byte[0];
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
LoginDTO loginDTO = (LoginDTO) session.getAttribute("loginDTO");
int noOfCartItems = 0;
session.setAttribute("noOfCartItems", noOfCartItems);
Connection con = null;
try {
String operation = request.getParameter("operation");
if (operation.equalsIgnoreCase("signin")) {
String mobile_email = request.getParameter("mobile_email");
String password = request.getParameter("password");
address = InetAddress.getLocalHost();
ip = address.getAddress();
String ipAddress = com.oeuvretc.util.RawIPToString.getIpAddress(ip);
System.out.println(ipAddress);
con = ConnectionManager.getConnection();
PreparedStatement ps=con.prepareStatement("SELECT * FROM view_user_details WHERE (mobile=? OR email_id=?) AND user_password=?");
ps.setString(1, mobile_email);
ps.setString(2, mobile_email);
ps.setString(3, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
HttpSession s=request.getSession();
s.setAttribute("mob", mobile_email);
out.print(1);
String ipadd=rs.getString("ip");
String stat=rs.getString("status");
if(ipadd.equals("")||ipadd.equals(ipAddress))
{
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"ONLINE");
ps3.setString(2, ipAddress);
ps3.setString(3,mobile_email);
ps3.setString(4,mobile_email);
int count=ps3.executeUpdate();
if (loginDTO == null) {
loginDTO = new LoginDTO();
loginDTO.setLoginID(mobile_email);
loginDTO.setPassword(password);
session.setAttribute("loginDTO", loginDTO);
session.setAttribute("loginStatus", "logged-in");
}
PersonalInfoDTO personalInfoDTO = new PersonalInfoDTO();
if (rs.getString("fname") != null) {
personalInfoDTO.setFirstName(rs.getString("fname"));
}
if (rs.getString("lname") != null) {
personalInfoDTO.setLastName(rs.getString("lname"));
}
String name = null;
if (rs.getString("fname") != null) {
name = rs.getString("fname");
}
if (rs.getString("lname") != null) {
name = name + " " + rs.getString("lname");
}
if (name != null) {
personalInfoDTO.setName(name);
}
if (rs.getString("email_id") != null) {
personalInfoDTO.setEmail(rs.getString("email_id"));
}
if (rs.getString("mobile") != null) {
personalInfoDTO.setMobile(rs.getString("mobile"));
}
if (rs.getString("gender") != null) {
personalInfoDTO.setGender(rs.getString("gender"));
}
if (rs.getString("blood_group") != null) {
personalInfoDTO.setBloodGroup(rs.getString("blood_group"));
}
if (rs.getString("dob") != null) {
personalInfoDTO.setDOB(rs.getString("dob"));
}
if (rs.getString("height_feet") != null) {
personalInfoDTO.setHeightFeet(rs.getString("height_feet"));
}
if (rs.getString("height_inch") != null) {
personalInfoDTO.setHeightInch(rs.getString("height_inch"));
}
if (rs.getString("height_cm") != null) {
personalInfoDTO.setHeightCentiMeter(rs.getString("height_cm"));
}
if (rs.getString("weight_hg") != null) {
personalInfoDTO.setWeightKG(rs.getString("weight_hg"));
}
if (rs.getString("weight_lbs") != null) {
personalInfoDTO.setWeightLBS(rs.getString("weight_lbs"));
}
loginDTO.setPersonalInfoDTO(personalInfoDTO);
AddressDTO addressDTO = new AddressDTO();
if (rs.getString("locality") != null) {
addressDTO.setLocality(rs.getString("locality"));
}
if (rs.getString("pincode") != null) {
addressDTO.setPincode(rs.getString("pincode"));
}
if (rs.getString("addr") != null) {
addressDTO.setAddr(rs.getString("addr"));
}
if (rs.getString("landmark") != null) {
addressDTO.setLandmark(rs.getString("landmark"));
}
if (rs.getString("Cityname") != null) {
addressDTO.setCity(rs.getString("Cityname"));
}
if (rs.getString("Statename") != null) {
addressDTO.setState(rs.getString("Statename"));
}
if (rs.getString("Countryname") != null) {
addressDTO.setCountry(rs.getString("Countryname"));
}
loginDTO.setAddressDTO(addressDTO);
//loginDTO.setImage(rs.getBinaryStream("image"));
loginDTO.setProfilePic(rs.getString("image"));
//System.out.println(rs.getString("image"));
// fetch if any item is available in the user cart or not
PreparedStatement ps1 = con.prepareStatement("SELECT test_kit FROM user_registration WHERE mobile=? OR email_id=?");
ps1.setString(1, loginDTO.getLoginID());
ps1.setString(2, loginDTO.getLoginID());
ResultSet rs1 = ps1.executeQuery();
if (rs1.next()) {
InputStream is = rs1.getBinaryStream(1);
if (is != null) {
ObjectInputStream ois = new ObjectInputStream(is);
HashMap<String, CartDTO> mapOfCartDTO = (HashMap<String, CartDTO>) ois.readObject();
session.setAttribute("mapOfCartDTO", mapOfCartDTO);
noOfCartItems = mapOfCartDTO.size();
session.setAttribute("noOfCartItems", noOfCartItems);
}
}
}
else{
out.print(2);
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"OFFLINE");
ps3.setString(2, "");
ps3.setString(3,mobile_email);
ps3.setString(4,mobile_email);
int count=ps3.executeUpdate();
System.out.println("Already Logged In. from another device.");
}
}
else{
out.print(0);
System.out.println("Invalid Username or Password");
}
}
}}
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LogoutServlet..........");
Connection con = null;
HttpSession session = request.getSession(false);
HttpSession s=request.getSession();
String mob=(String) s.getAttribute("mob");
String siginThrough = (String) session.getAttribute("siginThrough");
try{
con = ConnectionManager.getConnection();
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"OFFLINE");
ps3.setString(2, "");
ps3.setString(3,mob);
ps3.setString(4,mob);
int count=ps3.executeUpdate();
session.invalidate();
}
catch(Exception e)
{
e.printStackTrace();
}
//response.sendRedirect(getServletContext().getInitParameter("baseURL_USER"));
//response.sendRedirect("/scylla/");
if (siginThrough != null) {
if (siginThrough.equals("facebook")) {
response.getWriter().print(siginThrough);
} else if (siginThrough.equals("google")) {
response.getWriter().print(siginThrough);
}
} else {
response.getWriter().print(1);
}
}
}
You should add a parameter to achieve this.
One to contain the sessionvalidation, which should be a combination of IP and a boolean. eg (127.0.0.1-true)
you set the boolean as true when he logins from a browser and set as false once he logs out. Add a check in all pages to check this parameter to be true, and also on the IP of the accessing system and the IP in this variable. so that when he logs out, he will not be able to access from other browsers / computers.
I have working code as follows
public class receive_meter_to_store extends HttpServlet {
WSEMAMSTS EMAMService = new WSEMAMSTS();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
reuse_func gc_reuse_func = new reuse_func();
curr_time gs_current_datetime = new curr_time("");
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
I want to make it thread safe, as in to make it run faster. First I am to remove all the global variables, but when i do so, I get error
"An unhandled program error has occured. Please contact the Support services and report the issue"
I have moved them so they can be local as follows
public class receive_meter_to_store extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String retdata = "Failure";
reuse_func lc_reuse_func = new reuse_func();
try {
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
}
catch (Exception ex)
{
String ErrorMsg = ex.getMessage();
out.println("Error" + ErrorMsg);
}
finally {
out.close();
}
try {
retdata = add_meter_to_store(request, response);
}
finally {
out.println(retdata);
out.close();
}
}
Am I doing something wrong here?
the class i am calling add_meter
public String add_meter_to_store(HttpServletRequest request, HttpServletResponse response)
{
reuse_func lc_reuse_func = new reuse_func();
try
{
WSECMPublic EMAMService = lc_reuse_func.getMeterWebService();
ItronEMAMStsBinding itronEMAM = EMAMService.getItronEMAMStsBinding();
ItronAuthCredit lItronAuthCredit = new ItronAuthCredit();
EANDeviceID lTerminalID = new EANDeviceID();
EANDeviceID lClientID = new EANDeviceID();
SimpleDateFormat itronDF = new SimpleDateFormat("yyyyMMddHHmmss");
Date current_datetime = new Date();
String s_current_datetime = itronDF.format(current_datetime);
MsgID lMsgID = new MsgID();
curr_time ls_current_datetime = new curr_time("");
// Declare MeterImportResponse Variable
ItronMeterStsImportResp stsImportResp = new ItronMeterStsImportResp();
// Call meterStsImport WebMethod
stsImportResp = itronEMAM.meterStsImport(stsImportReq);
}
catch (Exception ex) {
// TODO handle custom exceptions here
String ErrorMsg = ex.getMessage();
retdata = "Error : " + ErrorMsg;
}
return retdata;
}
Note: i have removed the global variables in first part and put them in the class
The problem (or one problem, at least) is that in the first finally block, you close out, but then try to use it again later.
This means that your out.println(retdata) statement is always operating on a closed stream.
I want to call a method based on JSON-RPC request from a servlet I have code like this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
String json_request = this.readStream(in);
Object id = null;
try {
JSONRPC2Request reqIn = JSONRPC2Request.parse(json_request);
id = reqIn.getID();
Object params = reqIn.getPositionalParams().toArray();
String method_name = reqIn.getMethod();
Service service = new Service();
Method[] methods = service.getClass().getMethods();
Method method = null;
// getMethod need class as second argument
for (int i=0; i<methods.length; ++i) {
if (methods[i].getName().equals(method_name)) {
method = methods[i];
break;
}
}
if (method != null) {
Object result = method.invoke(service, params);
JSONRPC2Response respOut = new JSONRPC2Response(result, id);
out.println(respOut);
} else {
out.println(JSONRPC2Error.METHOD_NOT_FOUND);
}
} catch (IllegalArgumentException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, id));
} catch (IllegalAccessException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (InvocationTargetException e) {
out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
} catch (JSONRPC2ParseException e) {
out.println("{\"error\": \"Parse Error: " + e.getMessage() + "\"}");
}
}
I try to call method login from service class:
public class Service {
public String login(String username, String password) {
return "token";
}
}
I call it from javascript using jQuery:
var request = JSON.stringify({
method: "login",
params: ["foo", "Bar"],
id: 1,
jsonrpc: "2.0"
});
$.post('/app/rpc', request, function(res) { console.log(res); });
But I keep getting runtime IllegalArgumentException. What's wrong with my code? I also try to cast params to object with the same result.
We are students.
In our project,we want to send xml block,basically saml assertion,from one server to another server via http post method.
Can anyone help us out in sending the XML object from one servlet to another servlet where each servlet resides on two different computers in java.
/* here we are trying to send xml object(root) from one servlet to another servlet which resides on different pc... but dispatcher method isnt working in this case.*/
public class sp1serv extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,java.io.IOException
{
Connection c=null;
Statement s= null;
ResultSet rs = null;
String d=null;
int flag=0;
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Response response=null;
XMLObject root=null;
HttpSession session1=req.getSession();
System.out.println(session1.getAttribute("sAccessLevel"));
System.out.println(session1.getAttribute("sUserId"));
String eid=session1.getAttribute("sUserId").toString();
String[] str1 = {"response","attr",session1.getAttribute("sAccessLevel").toString(), session1.getAttribute("sUserId").toString() };
String filename= eid.concat(".xml");
try {
response=SAMLProtocol.passResponse(str1);
root=SAMLSignature.passSignature(response,filename);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.setAttribute("SP1",root);
String abc="http://169.254.229.232:8080/sp_response_handler";
RequestDispatcher rd=getServletContext().getRequestDispatcher(abc);
rd.forward(req, resp);
break;
}
}
}
}}
/* this servlet is used for retrieving xml object(root) and parsing it..on another server.*/
public class sp1_response_handler extends HttpServlet {
private static final long serialVersionUID = 1L;
public sp1_response_handler() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Response resp=null;
//XMLObject resp=null;
resp=(Response) request.getAttribute("SP1");
int result=0;
//SAMLSignature verification=null;
try {
result=SAMLSignature.verify(resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(result==1){
List attributeStatements = resp.getAssertions().get(0).getAttributeStatements();
for (int i = 0; i < attributeStatements.size(); i++)
{
List attributes = ((AttributeStatement) attributeStatements.get(i)).getAttributes();
for (int x = 0; x < attributes.size(); x++)
{
String strAttributeName = ((XMLObject) attributes.get(x)).getDOM().getAttribute("Name");
List<XMLObject> attributeValues = ((Attribute) attributes.get(x)).getAttributeValues();
for (int y = 0; y < attributeValues.size(); y++)
{
String strAttributeValue = attributeValues.get(y).getDOM().getTextContent();
System.out.println(strAttributeName + ": " + strAttributeValue);
}
}
}
response.sendRedirect("SP1.jsp");
}
else
{
System.out.println("NOT a Valid Signature");
}
}}
If you are using spring, you can use RestTemplate. From the docs:
String uri = "http://example.com/hotels/1/bookings";
PostMethod post = new PostMethod(uri);
// create booking request content
String request = post.setRequestEntity(new StringRequestEntity(request));
httpClient.executeMethod(post);
if (HttpStatus.SC_CREATED == post.getStatusCode()) {
Header location = post.getRequestHeader("Location");
if (location != null) {
System.out.println("Created new booking at :" + location.getValue());
}
}
Something like that should work (with the parameters being a Map<String,String>):
StringBuffer data = new StringBuffer();
if (parameters != null && parameters.size() > 0) {
for (Entry<String, String> e : parameters.entrySet()) {
if (data.length() > 0) {
data.append('&');
}
data.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(e.getValue(), "UTF-8"));
}
}
String parametersAsString = data.toString();
// Send data
URL local_url = new URL(url);
URLConnection conn = local_url.openConnection();
conn.addRequestProperty("Content-Type", "text/xml; charset=utf-8");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(parametersAsString);
wr.flush();
break;
I have this action class, this class takes care of my response
Update now passing response from DownloadStatus class, but it looks like it is null
public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware
{
static Logger logger = Logger.getLogger(DownloadStatus.class);
private HttpServletRequest request;
private HttpServletResponse response;
private File cfile;
private String cfileFileName;
#Override
public String execute()
{
logger.debug("Inside DownloadStatus.execute method")
try {
ChainsInvoker invoker = new ChainsInvoker()
def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName)
if(executionResponse == null || ErrorHandler.checkIfError(executionResponse))
{
return ERROR
}
response.setContentType("APPLICATION/xml")
logger.debug("filename: $cfileFileName")
response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"")
response.getWriter().print(executionResponse)
logger.debug("executionResponse :" + executionResponse)
invoker.invoke(MYChains.clean)
}catch (Exception exp) {
logger.error("Exception while Creating Status ")
logger.error(exp.printStackTrace())
}
return NONE
}
#Override
public void setServletRequest(HttpServletRequest request) { this.request = request; }
#Override
public void setServletResponse(HttpServletResponse response) { this.response = response; }
public File getcfile() { cfile }
public void setcfile(File cfile) { this.cfile = cfile }
public String getcfileFileName() { cfileFileName }
public void setcfileFileName(String cfileFileName){ this.cfileFileName = cfileFileName }
}
and below class to write stream into response
class DownloadStatusResponse implements Command {
static Logger logger = Logger.getLogger(DownloadStatusResponse.class);
#Override
public boolean execute(Context ctx) throws Exception
{
logger.debug("Inside DownloadStatusResponse.execute() method")
OutputStream response = null;
if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0 )
{
HttpServletResponse resp = ctx.get(ContextParams.response)
/*I am trying to get Response here*/
response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp)
}
logger.debug("Response: " + response)
ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/
return false;
}
private OutputStream downloadStatusFile(String filename,HttpServletResponse resp)
{
logger.info("Inside downloadStatusFile() method")
File fname = new File(filename)
if(!fname.exists())
{
logger.info("$filename does not exists")
return null
}
else
{
resp.setContentType("APPLICATION/xml")
/*Exception: cannot setContentType on null object*/
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"")
FileInputStream istr = new FileInputStream(fname)
OutputStream ostr = resp.getOutputStream()
/*I need to use resp.getOutputStream() for ostr*/
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte)
ostr.flush();
}
return ostr
}
}
My question is how can ostr be returned to the response in DownloadStatus class?
Update (working test servlet)
I have this below servlet which does the job of getting file content into a stream and giving it back to the HttpServletResponse, but i want to use it in above code
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String fileName = req.getParameter("zipFile");
if(fileName == null) return;
File fname = new File(fileName);
System.out.println("filename");
if(!fname.exists()) {System.out.println("Does not exists"); return;}
FileInputStream istr = null;
OutputStream ostr = null;
//resp.setContentType("application/x-download");
resp.setContentType("APPLICATION/ZIP");
resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"");
System.out.println(fname.getName());
try {
istr = new FileInputStream(fname);
ostr = resp.getOutputStream();
int curByte=-1;
while( (curByte=istr.read()) !=-1)
ostr.write(curByte);
ostr.flush();
} catch(Exception ex){
ex.printStackTrace(System.out);
} finally{
try {
if(istr!=null) istr.close();
if(ostr!=null) ostr.close();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
try {
resp.flushBuffer();
} catch(Exception ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
As far as I understand all you require is how to download a file using Struts2.
You need something like this is your struts.xml file
<action name="downloadfile" class="DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="document.pdf"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Code:
public class DownloadAction extends ActionSupport {
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() throws FileNotFoundException {
String filePath = ServletActionContext.getServletContext().getRealPath("/uploads");
File f = new File(filePath + "/nn.pdf");
System.out.println(f.exists());
inputStream = new FileInputStream(f);
return SUCCESS;
}
}