Skip to main content

How to: Write a file inside webapp directory of Tomcat with Struts2 or JSP & Servlet





Hi! This time its for struts break for database, ever felt you wanna store files temporarly inside your server directory? then this post is to help you out if you are new to java and you have interest in learning, this is good to know! trust me even big folks won’t know this I’m going to tell for Struts2 framework.

============================================

Using ServletContext & ServletActionContext in Struts2

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

============================================

public String execute() {

try {

String path = “/folder1/file1.txt” ;

System.out.println(“where it might write ”

+ System.getProperty(“user.dir”));

ServletContext context = ServletActionContext.getServletContext(); //Line No.6

path = context.getRealPath(path);

File file = new File(path);

// if file doesnt exists, then create it

if (!file.exists()) {

System.out.println(“trying to creat new file at ” + path);

// Getting parent directory then creating it

File parent = file.getParentFile();

parent.mkdirs();

// Creating file

file.createNewFile();

}


FileWriter fw = new FileWriter(file);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(“This is Written to file”);

System.out.println(“Where it wrote ” + file.getAbsolutePath());

bw.close();

System.out.println(“Done”);

return “success”;

} catch (IOException e) {

e.printStackTrace();

return “input”;

}

}

“String pathname = context.getRealPath(filename);” is the trick here. getRealPath(fielpath) return the exact path corresponding to the server. I said right even experienced folks dont know, cause this is not goot practice :oh!no: if the server is unpacket getRealPath() will return null!! so the best was is to return as String and handle it in JSP or whatever way to can. Anyway Server will be unpacked by default but if something screw up!  Ok TC keep thinking.


For Jsp & Servlet replace line no. 6 with *ServletContext context = this.getServletContext();* Class must extend HttpServlet and init(config) must have the call super.init(config) else context will be null.


Comments

Popular this month

Puththu kovilum Putho tilesum, as they are built

Its the grand Aadi season here in Tamil Nadu wherever you go you'd be followed by awful noise from no mercy speakers masqueraded as a devotional song. Yes, this is the first post dedicated to it. Hindu is not a religion but it's idealism, a way to unite people, that's perfectly constructed by assuming separate task to every God, no single God worship. Hindus moved from nature worship to idol worship, but that doesn't mean that we don't have nature worship we have created an idol for them and continued to worship them in a different form. Snake is a beautiful reptile, I have made friend with few too... Our ancestor found the natural law, 'every living creature on earth is important for the ecosystem to be balanced'. Maybe to make sure snakes are not killed fearing their venom they made them as God too! Not just idol snakes, they are worshipped as they are at their  conquered (from rats and termite)   nest or  puthu . Puthu...

Up and Close with Sudalai Madan: The Encounter

Night of 13th April all the preparations for the rituals were done in the temple, Sudalaimadan swamy was decorated with flowers, fruits and coconuts; the dedications reached above his chest. My cousin Sudalai Muthu, senior priest of the shrine reached home by late-night got blessings of his father Late Shanmugam Sundaram also previous head priest and blessed the family members in room dedicated for God, then started towards the temple. People have already gathered in huge numbers and were waiting for the Sudalaimada Swamy's arrival at Temple. Different rituals were offered by people to the Lord in order to get the blessings. As it is believed Sudaimada Swamy, the son of Lord Siva used to consume meat in Kailash for this reason he is sent to earth, where he can satisfy his earthy hunger thereby not polluting Kailash. Sree Aaladi Padmanabha Sudalaimada Swamy Temple, Kumarapuram Offering meat to Sudalaimadan is the most important and watchful event of the festival. Many devotees off...

Love is an overrated emotion

Nothing here is a fact, this is only opinion, no just rant of a young adult idiot. Turn around now, if you don't like rant or profanity or profanity-laced rant. When I say love, I strictly mean the romantic form of it; and I hate that I even have to say that, why do people have to add love to everything? parental love, baby love, candy love and so on... that's just plain stupid. Love is problematic not just because some people use it to manipulate others, but because it is a powerful emotion. So how it is problematic for everyone if only some use it to manipulate, the rest plain minded people will be bound by a strong feeling for each other, isn't it good? No, because even though love is strong emotion it starts to wear down after the purpose is fullfiled, and that brings me to the purpose of love. Purpose of love is to pro-create, you can decorate it, put a shiny gown, powder it with glitters, but the truth remains the same, love exists so that we don't become extinct....

Old is Gold: Vaitheeswaran Koil

My parent’s Shastiapthapoorthi just happened on 8th Oct at Thirukadaiyur, Amritaghateswarar – Abirami Temple , we were so glad that all poojai took place on Nandhi mandapam. My scheduled next stop was my uncle home for virunthu . But after getting boosted with abundant spiritual aura can’t stop myself from stopping for Vaitheeswaran koil on the way, that evening along with my wife experienced the glory of good old times.   Though Vaithyanatha swamy(Lord Shiva as Lingam) is the prime deity, Muthukumaraswamy stole the day, the panchaloga figurine of Lord Murugan in the shrine. Its Urchavar as its referred here since the figure is movable and comes out of the mandapam on special occasions. We went inside temple purified ourselves with holy water in temple pond, worshiped goddess Thaiyal Nayagi then stood in front of Lord Shiva for a very long time, but no poojari-iyer dropped by I’m not sure what special occasion it is on 08-Oct-13, as we saw many move towards closed doors of parti...