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...

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...

Good to know about Ancestry

Probably I would have been in shorts and ungodly shirt when I last visited my native, 12 years back. All these years it has been don't worry about native years, because I'm in great confusion on which is my native 😅 So how can I relate this place to me? My Grandfather Palaniappa Pillai's hometown. My  Father's Paternal Grandfather,  Mr.Chokalingam Pillai  got settled into Kumarapuram a village next to T isaiyanvilai, Thirunelveli. We were the affluent family from upper-caste Saiva Pillai, so we received a lot of respect, the family is referred to as 'Kanapillai kudumbam' and our home is referred to as 'Panna veedu'. More like 90's Tamil movies when elders from my family cross the street people used to remove slippers and keep their towel in the armpit or they tie it around the hip. It didn't last long just two generations,✌  a victory for equality! Even now the respect has not come down but idiotic 'remove chappal' rituals are skippe...

Sleeping to sickness

Insomnia is the most common sleep disorder that most people think of when someone says they have trouble sleeping, pop culture has put such spin on it. But there are other disorders too like sleep deprivation (not enough sleep), sleep apnea (snoring/breathing trouble while sleeping, caused by reduced oxygen level); there are also other terrors like acting out dreams in the physical world, awake but muscles are paralysed, teeth grinding and shouting out dreams. But, I'm suffering from the most common form of sleep disorder of the 21st century; I always wake up tired, no it is not hypersomnia. This post is going to be sort of self-shaming one, in order to change my habit. Confession: I'm a big YouTube consumer, I consume too much to even remember them all the next day even though I follow quality contents still they are useless if I forget them all. Almost all of the channels I follow hosts, education, science, history, general health, environment, computer and related stuff; my ...