This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
I want to upload file in my doPost method in servlet which is extends HttpServlet. But I didn't find any example aboutn upload in override servlet method.
How can I do this?
#WebServlet("/uploadPage")
public class myServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String file = req.getParameter("fileUpload");
System.out.println(file);
byte[] myFile = // TODO????
}
}
Thank you for your help.
There are few steps need to follow for File Upload functionality
1. Declare form as MultiPartForm data
2. Have commons dependencies for simplicity
3. Have Servlet/Controller accept array with filename and data.
Each MVC has its own implementations for controller.
This example explains Spring MVC:
https://www.mkyong.com/spring-mvc/spring-mvc-file-upload-example/
Additionally you can consider security and access control to the directory where file upload is happening as well as Java API for antivirus to scan the uploaded files.
Happy file uploading :)
Related
This question already has answers here:
Deploying my application at the root in Tomcat
(10 answers)
Closed 2 years ago.
I created one java web project with the name first-web-application. then I created one servlet having doGet method.
#WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
------------------
-----------------
}
}
When I am running and accessing this application it is coming
http://localhost:8080/first-web-application/login.do
But the video I am following is not using application name. output is simply coming by using
http://localhost:8080/login.do
If I removed application name it gives 404 error. I mean how can we use or remove application name from URL.
Sorry to ask such basic question but I could not understand the same
That's because you're application is probably packaged as first-web-application.war and your root context name becomes hostname:port/first-web-application/.
Easiest way to resolve this is to package your web application as ROOT.war, and as ROOT is the default name mapped to the root / context path on the server, your application will be accessible at root of the Web Container.
I'm looking at a project with the following Java Configuration file:
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
}
}
The project has some static resources in the webapps/resources directory that are being served up. My question is I'm not sure why. It seems for this to work, the above call to addResourceHandlers(...) should be
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources");
}
I tried to look for something in the Spring documentation possibly indicating default values but could not, so I'm not sure why the project works.
The project can serve static resources thanks to DefaultServletHandlerConfigurer:
Configures a request handler for serving static resources by forwarding the request to the Servlet container's "default" Servlet.
I use Jetty in the following example, but other servlet containers (e.g. Tomcat) should behave similarly. Download the Jetty 9 distribution, then inside webapps, create these files:
example/
hello.txt
Start the Jetty server. We have deployed the simplest application imaginable. You should be able to access the file at:
http://localhost:8080/example/hello.txt
The servlet container can serve static resources without any extra configurations. This behavior is suppressed as soon as Spring MVC comes into play. Spring MVC will create a front controller, DispatcherServlet, and park it at "/". Every incoming request will go through this single servlet, and the servlet will find the appropriate component in the app to actually process the request (e.g. a #RequestMapping method in a #Controller class). If no handlers for the request can be found, we have 404s.
The handler DefaultServletHandlerConfigurer has the lowest precedence. If enabled, it allows the front controller to handle the request first. When that fails, it forwards the request to the servlet container, where the request is treated as a static resource read.
This is a quick and dirty way of serving static files. In practice, you don't want anything off the beaten path to be available via a GET. You want to allow only specific files and folders, and you would use WebMvcConfigurerAdapter.addResourceHandlers().
I am writing a simple web app with one servlet and my System.out.println statements (in my servlet) do not show up in the server.log file which for me is located at
C:\jboss-as-7.1.1.Final\jboss-as-7.1.1.Final\standalone\log
So, I'm thinking that maybe I need to set up some kind of logging or something. I am completely clueless on this.
I have tried to research log4j as an option but the more I research the more confused I get.
I need a step by step approach on this. If anyone could please help I would be so thankful.
The simplest to start is IMHO using java.util.logging framework. You don't need any special application dependency. It just works.
Example usage in a servlet:
import java.util.logging.Logger;
private final Logger LOGGER = Logger.getLogger(getClass().getName());
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/plain");
final PrintWriter writer = resp.getWriter();
writer.println("Logging message with SEVERE importance level");
LOGGER.severe("Test log message with level SEVERE");
writer.close();
}
Look on GitHub for a full example servlet.
To enable all log-levels for your application, you can use JBoss CLI (jboss-cli.sh / jboss-cli.bat). Here is example, assuming your application is under org.jboss.test package:
connect
/subsystem=logging/console-handler=CONSOLE:write-attribute(name=level,value=ALL)
/subsystem=logging/logger=org.jboss.test:add(level=ALL)
quit
I just created a Sling servlet through maven.packaging as - "bundle", then I installed it inside system console of CQ5.
My bundle shows me Active state and all the required packages ..exported successfully.
but I when I call this bundle to use the servlet... nothing happened.
It doesn't give me response.
Is there a better way..to create a sling servlet and create a OSGI bundle,so that I can install it as a bundle in CQ5 to call the servlet from the component.
You can create SlingSerlvet like this.
#SlingServlet(
paths={"/services/myapp/LoginController/validateUser","/services/myapp/LoginController/logout"})
#Properties({
#Property(name="service.pid", value="com.xxx.xxx.controller.LoginController",propertyPrivate=false),
#Property(name="service.description",value="Validates the user", propertyPrivate=false),
#Property(name="service.vendor",value="xxx Tech", propertyPrivate=false)
})
public class LoginController extends SlingAllMethodsServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doPost(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
}
#Override
protected void doGet(SlingHttpServletRequest request,
SlingHttpServletResponse response) throws ServletException,
IOException {
}
}
To Call this servlet in browser just type the URLS "/services/myapp/LoginController/validateUser"
And "/services/myapp/LoginController/logout" As you may already know that a serlvet can have multiple URLS.
This is a working piece of Code.
Make sure that your URL Mappings i.e paths(in Sling/CQ5) starts with /services
also you can also create bundle using a dedicated Eclipse for CQ5 CRXDE Eclipse instead of Maven bundle.
It's much easier to use but it is a bit slow. Download Here
Bingo.. finally I am able to call a sling sevlet bundled as OSGI bundle and deployed in CQ's system console.
later I called this OSGI bundle fire a post request and this time able to get the response.
here is a very nice and very explanatory tutorial from Scott that explain every and each steps of my problem.
http://scottsdigitalcommunity.blogspot.in/2013/06/posting-form-data-to-adobe-cq-using.html
and the sample code or sample application link can be found from here -
http://helpx.adobe.com/experience-manager/using/custom-sling-servlets.html
follow the above link step by step and you end up with the victory.
I followed each steps and successfully called OSGI bundle's servlet through component inside CRXDE.
and finally not to forget to thanks Scott.... thanks Scott for the explanation !!!
I'm getting the above mentioned error when trying to access a repository
using jackrabbit-standalone-2.4.2.jar from a servlet. I didn't use the
jackrabbit war because I already have a thick client app working and I want
to reuse as much code as possible. I just assumed doing this was possible.
To test I created a small web application. Since I cannot attach a zip file
I will just copy the doPost() method below:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Repository repository = new TransientRepository(
"repository.xml", //embedded within the war
"path/to/home/dir");
Session session = null;
try {
session = repository.login();
System.out.println("root node identifier: " +
session.getRootNode().getIdentifier());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.logout();
}
}
When I post to this servlet from an html form the exception has 2 parts:
java.lang.NoClassDefFoundError: javax/jcr/Repository
java.lang.ClassNotFoundException: javax.jcr.Repository
when I add jcr-2.0.jar in it then I get a different error:
java.lang.NoClassDefFoundError: org/apache/jackrabbit/core/TransientRepository
You originally got the ClassNotFoundException because that class wasn't in the classpath. You have fixed that. The NoClassDefFoundError means the class is in the classpath, but there was an problem initializing it. For details about this distinction, see also this question.
So the class TransientRepository is there, but most likely a class referenced by the TransientRepository isn't. That means most likely you didn't include other required jar files in the classpath. For a complete list of dependencies (required jar files), see the jackrabbit-standalone-2.4.2.jar, or see the Jackrabbit docs. It could also mean you have all jar files, but at least one of the jar files is the wrong version.
You originally got the ClassNotFoundException because that class wasn't in the classpath. You have fixed that.
The NoClassDefFoundError means the class is in the classpath, but there was an problem initializing it.