Search This Blog

Showing posts with label #java. Show all posts
Showing posts with label #java. Show all posts

Tuesday, 15 July 2014

File Upload Example in Struts

 

 

Required JAR file

Before we start, we need to make sure commons-io.jar file is present in the classpath. Following are the list of required Jar files.
struts2-file-upload-jar-files

Getting Started

In order to add file upload functionality we will add an action class FileUploadAction to our project. Create file FileUploadAction.java in package com.blogspot.rajvishwakarma15.struts2.
FileUploadAction.java
package com.blogspot.rajvishwakarma15.struts2;
 
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
 
public class FileUploadAction extends ActionSupport implements
        ServletRequestAware {
    private File userImage;
    private String userImageContentType;
    private String userImageFileName;
 
    private HttpServletRequest servletRequest;
 
    public String execute() {
        try {
            String filePath = servletRequest.getSession().getServletContext().getRealPath(“/”);
            System.out.println("Server path:" + filePath);
            File fileToCreate = new File(filePath, this.userImageFileName);
 
            FileUtils.copyFile(this.userImage, fileToCreate);
        } catch (Exception e) {
            e.printStackTrace();
            addActionError(e.getMessage());
 
            return INPUT;
        }
        return SUCCESS;
    }
 
    public File getUserImage() {
        return userImage;
    }
 
    public void setUserImage(File userImage) {
        this.userImage = userImage;
    }
 
    public String getUserImageContentType() {
        return userImageContentType;
    }
 
    public void setUserImageContentType(String userImageContentType) {
        this.userImageContentType = userImageContentType;
    }
 
    public String getUserImageFileName() {
        return userImageFileName;
    }
 
    public void setUserImageFileName(String userImageFileName) {
        this.userImageFileName = userImageFileName;
    }
 
    @Override
    public void setServletRequest(HttpServletRequest servletRequest) {
        this.servletRequest = servletRequest;
 
    }
}
In above class file we have declared few attributes:
  • private File userImage; -> This will store actual uploaded File
  • private String userImageContentType; -> This string will contain the Content Type of uploaded file.
  • private String userImageFileName; -> This string will contain the file name of uploaded file.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName. For example if the file attribute in action file is private File uploadedFile, the content type will be uploadedFileContentType and file name uploadedFileFileName.
Also note in above action class, we have implemented interface org.apache.struts2.interceptor.ServletRequestAware. This is to get servletRequest object. We are using this path to save the uploaded file in execute() method. We have used FileUtil.copyFile() method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.

The JSPs

Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it.
UserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Upload User Image</title>
</head>
 
<body>
<h2>Struts2 File Upload & Save Example</h2>
<s:actionerror />
<s:form action="userImage" method="post" enctype="multipart/form-data">
    <s:file name="userImage" label="User Image" />
    <s:submit value="Upload" align="center" />
</s:form>
</body>
</html>
SuccessUserImage.jsp
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Success: Upload User Image</title>
</head>
<body>
    <h2>Struts2 File Upload Example</h2>
    User Image: <s:property value="userImage"/>
    <br/>
    Content Type: <s:property value="userImageContentType"/>
    <br/>
    File Name: <s:property value="userImageFileName"/>
    <br/>
    Uploaded Image:
    <br/>
    <img src="<s:property value="userImageFileName"/>"/>
</body>
</html>

Struts.xml entry

Add following entry for FileUploadAction class to struts.xml file.
<action name="userImage"
    class="com.blogspot.rajvishwakarma15.struts2.FileUploadAction">
    <interceptor-ref name="fileUpload">
        <param name="maximumSize">2097152</param>
        <param name="allowedTypes">
            image/png,image/gif,image/jpeg,image/pjpeg
        </param>
    </interceptor-ref>
    <interceptor-ref name="defaultStack"></interceptor-ref>
    <result name="success">SuccessUserImage.jsp</result>
    <result name="input">UserImage.jsp</result>
</action>
Note that in above entry we have specified two parameter to fileUpload interceptor, maximumSize and allowedTypes. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg).
The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:
  • struts.messages.error.uploading – error when uploading of file fails
  • struts.messages.error.file.too.large – error occurs when file size is large
  • struts.messages.error.content.type.not.allowed – when the content type is not allowed

That’s All Folks

Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp
Image Upload Screen
struts2-file-upload-example
Image Upload Screen in case of error
struts2-file-upload-error
Image Upload Screen on success
struts2-file-upload-success

Download Source Code

Click here to download Source Code without JAR files (20KB)


Monday, 10 September 2012

How To Declare Keyword as Variable ?




Contact :  https://www.facebook.com/rajvishwakarma15

How To Declare Keyword as Variable ?



A Simple Example:
using System;
class A
{
    public static void Main(string[] a)
   {
         int @for=20;
         Console.WriteLine(@for);
Console.Readkey();
   }
}

Similarly This You can declare any Keyword As Variable.
Thanks.

Tuesday, 26 June 2012

KEY words in JAVA


 KEY words in JAVA
try Java Keyword
try Java Keyword       The try is a keyword defined in the java programming language. Keywords... : -- The try keyword in java programming language is used to wrap the code in a block
 
The finally Keyword
; The finally is a Java keyword that is used to define a block that is always executed in a try-catch-finally statement. In java... or not. This is a Java keyword therefore it may not be used as identifiers i.e. you
 
throws Java Keyword
throws Java Keyword       throws " is a keyword defined in the java programming language. Keywords... in java programming language likewise the throw keyword indicates the following
 

Java keyword
Java keyword  Is sizeof a keyword
 
java try catch
java try catch  try{ return 1; }catch(exception e){ return 2; } finally{ Return 3; } What is the out put if any exception occurred
 

Keyword - this
Keyword - this       A keyword is a word having a particular meaning to the programming language. Similarly, this keyword is used to represent an object constructed from a class
 
The if Keyword
is executed. The if is a java keyword that may not be used as identifiers i.e. you... The if Keyword         The if is a keyword, which is used to perform the selection
 
try and finally block
try and finally block  hello, If I write System.exit (0); at the end of the try block, will the finally block still execute?   hii, if we use System.exit (0); statement any where in our java program
 
The for Keyword
The for Keyword       The for is Java keyword that is used to execute a block of code... Java program. You can also use this keyword for nested loop i.e. loop within loop
 
final keyword
final keyword  why is final keyword used in java
 
Nested Try-Catch Blocks
Nested Try-Catch Blocks       In Java we can have nested try and catch blocks. It means that, a try statement can be inside the block of another try. If an inner try
 
Java try, catch, and finally
Java try, catch, and finally         The try, catch, and finally keywords are Java keywords... exceptions in Java is achieved through the use of the try and catch blocks. Catch
 
Return keyword
Return keyword  how do we use return in methods?   Java use of return keyword import java.util.*; public class ReverseString{ public... at Return Keyword
 
this java keyword
this java keyword       "this" is a keyword defined in the java programming language. Keywords... in java programming language likewise the this keyword indicates the following
 
Dynamic keyword
Dynamic keyword  hi....... What is the dynamic keyword used for in flex? give me the answer ASAP Thanks  Ans: Dynamic keyword... at run time. For example: In Java, if you?ve created an object from a particular
 
transient keyword - Java Beginners
transient keyword  what is transient keyword in java.? plz explain with example
 
The throw keyword example in java
Code: class MyMadeException extends Exception{} class ExceptionExample { public static void main(String[] args) { String test = args[0]; try { System.out.println ("First"); doriskyJob(test); System.out.println ("
 
Using throw keyword in exception handling in Core Java
Description: Core Java Throw Function is used for throwing the exception. The throw keyword tells the compiler that it will be handled by calling a method... exception need to be thrown from the calling method. Code for Java Throw Exception
 
static keyword
static keyword  Hii, In which portion of memory static variables stored in java. Is it take memory at compile time? thanks deepak mishra
 
The final Keyword
The final Keyword       The final is a keyword. This is similar to const keyword in other languages. This keyword may not be used as identifiers i.e. you cannot declare
 
Java: Final keyword
Java NotesFinal keyword The Final word on the final keyword. How often do you use final?
 
Try catch in JSP
Try catch in JSP          In try block we write those code which can... it is caught inside the catch block. The try catch block in jsp just work as try catch
 
The While keyword
The While keyword       While is a keyword defined in the java programming language. Keywords... : The while keyword in java programming language specifies a loop  The loop
 
The try-with-resource Statement
The try-with-resource Statement In this section, you will learn about newly added try-with-resource statement in Java SE 7. The try-with-resource... or work is finished. After the release of Java SE 7, the try-with-resource
 
The void keyword
The void keyword       The void is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java
 
The volatile keyword
The volatile keyword       The volatile is a keyword defined in the java programming language. Keywords... keyword is not implemented in many Java Virtual Machines. The volatile
 
can u plz try this program - Java Beginners
can u plz try this program  Write a small record management application for a school. Tasks will be Add Record, Edit Record, Delete Record, List.... --------------------- <%@ page language="java
 
while Java Keyword
while Java Keyword       The while is a keyword defined in the java programming language... to a compiler in java programming language likewise the while keyword indicates
 
volatile Java Keyword
volatile Java Keyword       The volatile is a keyword defined in the java programming language... to a compiler in java programming language likewise the volatile keyword indicates
 
true Java Keyword
true Java Keyword       The true is a keyword defined in the java programming language. Keywords... in java programming language likewise the true keyword indicates the following
 
void Java Keyword
void Java Keyword       The void is a keyword defined in the java programming language. Keywords... in java programming language likewise the void keyword indicates the following
 
The extends Keyword
The extends Keyword       The extends is a Java keyword, which is used in inheritance process of Java. It specifies the superclass in a class declaration using extends keyword
 
transient Java Keyword
transient Java Keyword       The transient is a keyword defined in the java programming language... to a compiler in java programming language likewise the transient keyword indicates
 
super Java Keyword
super Java Keyword       The super is a keyword defined in the java programming language... to a compiler in java programming language likewise the super keyword indicates
 
The byte Keyword
; The byte Java Keyword defines the 8-bit integer primitive type.  The keyword byte in Java is a primitive type that designates with eight bit signed integer  in java primitive type. In java keyword byte will be stored as an integer
 
Super - keyword
Super - keyword       super keyword super is a keyword in java that plays an important role in case of inheritance. Super keyword is used to access the members of the super class. Java
 
Return Java Keyword
Return Java Keyword       The return is a keyword defined in the java programming language. Keywords... in java programming language likewise the return keyword indicates the following
 
throw Java Keyword
throw Java Keyword       "throw " is a keyword defined in the java programming... to a compiler in java programming language likewise the throw keyword indicates
 
synchronized Java Keyword
synchronized Java Keyword       The synchronized is a keyword defined in the java programming... relevant to a compiler in java programming language likewise the synchronized keyword
 
The boolean Keyword
The boolean Keyword       The boolean Keyword in java avails one of the two values that are true and false. Java have the boolean type so literal values true and false.
 
Private Java Keyword
Private Java Keyword       private is a keyword defined in the java programming language. Keywords... in java programming language likewise the private keyword indicates the following
 
Public Java Keyword
Public Java Keyword       public is a keyword defined in the java programming language. Keywords are basically reserved words which have specific meaning relevant to a compiler in java
 
static Java Keyword
static Java Keyword       The static is a keyword defined in the java programming language. Keywords... in java programming language likewise the static keyword indicates the following
 
The implement keyword
The implement keyword       In java programming language, the keyword implement specifies... for using the implement keyword in a class. public class DominoPizza
 
Protected Java Keyword
Protected Java Keyword       protected is a keyword defined in the java programming language. Keywords... in java programming language likewise the protected keyword indicates
 
short Java Keyword
short Java Keyword       The short is a keyword defined in the java programming language. Keywords... in java programming language likewise the short keyword indicates the following
 
The interface keyword
The interface keyword       In java programming language the keyword interface in java is used... have specific meaning relevant to a compiler. The keyword implement is used
 
The null keyword
The null keyword       The null keyword in java programming language is a reserved word that is used... how to declare and define null values in java programming language
 
How to use this keyword in java
How to use "this" keyword in java       The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name
 
switch Java Keyword
switch Java Keyword       The switch is a keyword defined in the java programming language.

Saturday, 23 June 2012

Free Ebooks Download

Want Free Download Ebooks of Advanced JAVA, Network secuirity , Software Testing , C# ,ASP.NET using C#, Assignments Answer of TYBScIT .


                                 Complete Reference Visit Here........



                                  Click Here to Download Ebooks

Thursday, 21 June 2012

The 5 Most Common Problems New Programmers Face--And How You Can Solve Them

The 5 Most Common Problems New Programmers Face--And How You Can Solve Them


When you're just starting out with programming, it's easy to run into problems that make you wonder how anyone has ever managed to write a computer program. But the fact is, just about everyone else who's learned to code has had that experience and wondered the same thing, when they were starting out. I've helped teach several introductory programming classes, and there are some problems that trip up nearly every student--everything from getting started to dealing with program design.
I'll prepare you to get past these challenges--none of them are insurmountable.

Getting set up


Learning to program is hard enough, but it's easy to get tripped up before you even begin. First you need to chose a programming language (I recommend C++), then You need a compiler and a programming tutorial that covers the language you chose and that works with the compiler that you set up. This is all very complicated, and all before you even start to get to the fun parts.
If you're still struggling with getting the initial setup, then check out our page on setting up a compiler and development environment (Code::Blocks and MINGW) which walks you through setting up a compiler with a lot of screenshots, and gets you up to the point of having an actual running program.

Thinking Like a Programmer


Have you seen the State Farm commercials where the car wash company returns the cars to customers with the soap suds still on the car? The company washes the car, but it didn't rinse it. This is a perfect metaphor for computer programs. Computers, like that car wash company, are very very literal. They do exactly, and only, what you tell them to do; they do not understand implicit intentions. The level of detail required can be daunting at first because it requires thinking through every single step of the process, making sure that no steps are missing.
This can make programming seem to be a tough slog at first, but don't despair. Not everything must be specified--only what is not something the computer can already do. The header files and libraries that come with your compiler (for example, the iostream header file that allows you to interact with the user) provide a lot of pre-existing functionality. You can use websites like http://www.cppreference.com or our own function reference to find information on these pre-existing libraries of functionality. By using these, you can focus on precisely specifying only what is unique about your program. And even once you do that, you will begin to see patterns that can be turned into functions that wrap up a bunch of steps into a single function that you can call from everywhere. Suddenly complex problems will begin to look simple. It's the difference between:
Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
Walk forward ten feet
Move your hand to the wall
Move your hand to the right until you hit an obstacle
...
Press upward on indentation

and

Walk to door
Find light switch
Turn on light

The magic thing about programming is that you can box up a complex behavior into a simple subroutine (often, into a function) that you can reuse. Sometimes it's hard to get the subroutine done up just right at first, but once you've got it, you no longer need to worry about it.
You can go here to read more about how to think about programming, written for beginners.

Compiler Error Messages


This may seem like a small thing, but because most beginners aren't familiar with the strictness of the format of the program (the syntax), beginners tend to run into lots of complaints generated by the compiler. Compiler errors are notoriously cryptic and verbose, and by no means were written with newbies in mind.
That said, there are a few basic principles you can use to navigate the thicket of messages. First, often times a single error causes the compiler to get so confused that it generates dozens of messages--always start with the first error message. Second, the line number is a lie. Well, maybe not a lie, but you can't trust it completely. The compiler complains when it first realizes there is a problem, not at the point where the problem actually occurred. However, the line number does indicate the last possible line where the error could have occurred--the real error may be earlier, but it will never be later.
Finally, have hope! You'll eventually get really really good at figuring out what the compiler actually means. There will be a few error messages that today seem completely cryptic, even once you know what the real problem was, that in a few months time you will know like an old (if confused) friend. I've actually written more about this in the past; if you want more detailed help, check out my article on deciphering compiler and linker errors.

Debugging


Debugging is a critical skill, but most people aren't born with a mastery of it. Debugging is hard for a few reasons; first, it's frustrating. You just wrote a bunch of code, and it doesn't work even though you're pretty sure it should. Damn! Second, it can be tedious; debugging often requires a lot of effort to narrow in on the problem, and until you have some practice, it can be hard to efficiently narrow it down. One type of problem, segmentation faults, are a particularly good example of this--many programmers try to narrow in on the problem by adding in print statements to show how far the program gets before crashing, even though the debugger can tell them exactly where the problem occurred. Which actually leads to the last problem--debuggers are yet another confused, difficult to set up tool, just like the compiler. If all you want is your program to work, the last thing you want to do is go set up ANOTHER tool just to find out why.
To learn more about debugging techniques, check out this article on debugging strategies.

Designing a Program


When you're just starting to program, design is a real challenge. Knowing how to think about programming is one piece, but the other piece is knowing how to put programs together in a way that makes it easy to modify them later. Ideas like "commenting your code", "encapsulation and data hiding" and "inheritance" don't really mean anything when you haven't felt the pain of not having them. The problem is that program design is all about making things easier for your future self--sort of like eating your vegetables. Bad designs make your program inflexible to future changes, or impossible to understand after you've written. Frequently, bad design exposes too many details of how something is implemented, so that every part of the program has to know all the details of each other section of the program.
One great example is writing a checkers game. You need some way to represent the board--so you pick one. A fixed-sized global array: int checkers_board[8][8]. Your accesses to the board all go directly through the array: checkers_board[x][y] = ....; Is there anything wrong with this approach? You betcha. Notice that I wrote your accesses to the board all go directly through the array. The board is the conceptual entity--the thing you care about. The array happens to be, at this particular moment, how you implement the board. Again, two things: the thing you represent, and the way you represent it. By making all accesses to the board use the array directly, you entangle the two concepts. What happens when you decide to change the way you represent the board? You have an awful lot of code to change. But what's the solution?
If you create a function that performs the types of basic operations you perform on the checkers board (perhaps a get_piece_on_square() method and a set_piece_to_square() method), every access to the board can go through this interface. If you change the implementation, the interface is the same. And that's what people mean when they talk about "encapsulation" and "data hiding". Many aspects of program design, such as inheritance, are there to allow you to hide the details of an implementation (the array) of a particular interface or concept (the board).
Now go eat your spinach! :)
A good follow-up to learn more about these issues is to read about programming design and style.