Retrieving values from a hash map in my JSP - java

Some background information of what I'm trying to achieve is a user hits the submit button on my JSP page it needs to send the message submitted to a text file and then I need to access the file and retrieve all the messages in the file in my JSP page. Please help me out, I have spent too long and I'm not sure what I need to do to be able to iterate over the hash map to show all the messages.
This is what my code looks like right now:
Controller:
public class TwitServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String twits = "";
String path = getServletContext().getRealPath("/WEB-INF/twit.txt");
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
System.out.print(tweet);
String usern = (String) session.getAttribute("user");
String alias = (String) session.getAttribute("uname");
twitDB.insert(tweet, usern, alias, path);
Map test = twitDB.getTwit("/Users/emilio/Desktop/twit.txt");
session.setAttribute("test",test);
getServletContext()
.getRequestDispatcher("/home.jsp").forward(request, response);
}
}
Database(using txtfile for now):
ublic class twitDB {
public static void insert (String twit, String user, String uname, String path) throws IOException {
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy/MM/dd");
String dateString = ft.format(date);
File file = new File ("/Users/emilio/Desktop/twit.txt");
try ( PrintWriter out = new PrintWriter(new FileWriter(file, true))){
out.println("[#"+uname+"]:" + " " + dateString);
out.println(user);
out.println(twit);
out.println(".");
out.close();
}
catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
public static Map<String,Tweet> getTwit(String filename) throws IOException {
Map<String,Tweet> tweets = new HashMap<String,Tweet>();
File file = new File ("/Users/emilio/Desktop/twit.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String uname = in.nextLine();
String name = in.nextLine();
String twit = in.nextLine();
String filler = in.nextLine();
Tweet tweet = new Tweet(uname, name, twit);
tweets.put(uname, tweet);
tweets.put(name, tweet);
tweets.put(twit,tweet );
}
in.close();
return tweets;
}
}
Part of my JSP:
<button type="submit" method="post" class="btn btn-twitter">
<span class="glyphicon glyphicon-pencil"/>Tweet
</button>
</div>
</form>
</div>
</div>
<div class = "row feed">
<p>
<c:forEach items="${test}" var="test">
</c:forEach>
</p>

You are missing tag to do print if you are really getting data from the server.
<c:forEach items="${test}" var="test">
<c:out value="${test}"/>
</c:forEach>

Related

unable to upload image in image folder using servlet [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 1 year ago.
I can able to upload image in database but unable to upload into "files" folder. web
#WebServlet(name="AdminServlet",urlPatterns="/AdminServlet")
#MultipartConfig
public class AdminSevlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, SQLException {
try (PrintWriter out = response.getWriter()) {
UserDAO UserDAO = new UserDAO();
User User = new User();
String sid = request.getParameter("aid");
int id = Integer.parseInt(sid);
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String fname = request.getParameter("fname");
String ic = request.getParameter("ic");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String addr = request.getParameter("addr");
String email = request.getParameter("email");
String phoneNo = request.getParameter("phoneNo");
String dept = request.getParameter("dept");
String position = request.getParameter("position");
String eduqual = request.getParameter("eduqual");
String role = request.getParameter("role");
Part part = request.getPart("file"); // Retrieves <input type="file" name="file">
String image = part.getSubmittedFileName();
String path = getServletContext().getRealPath("./"+"web"+File.separator+"files"+File.separator+image);
InputStream is = part.getInputStream();
boolean succs = uploadFile(is, path);//
User.setadmin_id(id);
User.setuser_id(userid);
User.setpassword(password);
User.setuser_name(fname);
User.setIC(ic);
User.setGender(gender);
User.setdob(dob);
User.setAddress(addr);
User.setemail(email);
User.setphoneNo(phoneNo);
User.setDepartment(dept);
User.setPosition(position);
User.setEducationbackground(eduqual);
User.setRole(role);
User.setimage(image);
int result = UserDAO.addUser(User);
RequestDispatcher dispatcher = request.getRequestDispatcher("/view-user");
dispatcher.forward(request, response);
}
}
public boolean uploadFile(InputStream is, String path){
boolean test = false;
try{
byte[] byt = new byte[is.available()];
is.read();
FileOutputStream fops = new FileOutputStream(path);
fops.write(byt);
fops.flush();
fops.close();
test = true;
}catch (Exception e){
e.printStackTrace();
}
return test;
}
This is the image upload servlet. Once the image has been uploaded it should be inserted in the files folder. I don't know what mistake I have done. Could anyone let me know what is the problem? Do I need to add upload directory or the file path C: inside?
Updated answer and changed it
public boolean uploadFile(InputStream is, String path) {
boolean test = false;
try {
File targetFile = new File(path);
Files.copy(is, targetFile.toPath());
test = true;
} catch (Exception e) {
e.printStackTrace();
}
return test;
}

Getting HTML input value and using that value as a Java variable

Sorry for the long post and janky question.
I'm trying to figure out how to use an input textbox inside a form as a way to get the name of a city. With the city name, I'll then use it inside a method (getCitybyId) inside the MainController.
I'll then use it as the city name inside my api URL
Example:"http://api.openweathermap.org/data/2.5/weather?q=citynamevariable&appid=APIKey&units=imperial"
Is there any way I could do this? I'm pretty new to using spring boot and API's, and I have been trying to figure this out for a while.
Here's my code
MainController:
#RestController
public class MainController extends HttpServlet {
DataRepo dataRepo;
#RequestMapping(value = "/get", method = RequestMethod.GET)
public ModelAndView get(#RequestParam("name") String id) {
ModelAndView mv = new ModelAndView ("redirect:/");
String city = getCitybyId(id);
try{
JSONObject json = new JSONObject(city);
mv.addObject("Name", json.getString("name"));
mv.addObject("Temperature", json.getJSONObject("main").get("temp").toString());
mv.addObject("feels_like", json.getJSONObject("main").get("feels_like").toString());
mv.addObject("humidity", json.getJSONObject("main").get("humidity").toString());
mv.addObject("Wind", json.getJSONObject("wind").get("speed").toString());
}
catch (Exception e){
System.out.println(e.toString());
}
return mv;
}
private String getCitybyId(String name) {
try {
String apiKey = "key";
URL urlForGetRequest = new URL("http://api.openweathermap.org/data/2.5/weather?q=PUTCITYNAMEHERE&appid=key&units=imperial");
// These two are test to see if the method is actually getting data.
//String apiKey = "key";
// URL urlForGetRequest = new URL("https://superheroapi.com/api/" + apiKey + "/" + id);
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int status = connection.getResponseCode();
System.out.println(status);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
else {
return "Unexpected HTTP response";
}
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
}
class City
{
private String name;
public String getName()
{
return name;
}
public City()
{
name = "DEFAULT";
}
public City(String n)
{
name = n;
}
}
HTML code
<!DOCTYPE html>
<html>
<head>
<title> Homework 4 application</title>
<style><%#include file ="../css/style.css"%></style>
</head>
<body>
<h1>Please Select A City</h1>
<form method="get" action="/get/">
<input type="text" id = "name" name="name" />
<input type="submit" value="Submit">
</form>
<div>
<h2>City</h2> <h3><%=request.getParameter("Name")%></h3>
<h2>Temperature</h2> <h3><%=request.getParameter("Temperature")%> Fahrenheit</h3>
<h2>Feels Like</h2> <h3><%=request.getParameter("feels_like")%> Fahrenheit</h3>
<h2>Humidity</h2> <h3><%=request.getParameter("humidity")%>%</h3>
<h2>Wind Speed</h2> <h3><%=request.getParameter("Wind")%> Mph</h3>
</div>
<hr>
<div>
<h2>Previously Requested Cities</h2>
<table class = "lemun">
<tr>
<td>City</td>
<td>Temperature</td>
<td>Feels Like</td>
<td>Humidity</td>
<td>Wind Speed</td>
</tr>
<c:forEach var = "Data" items = "${dataList}">
<tr>
<td>${Data.getName}</td>
<td>${Data.getTemperature}</td>
<td>${Data.getFeels_Like}</td>
<td>${Data.getHumidity}</td>
<td>${Data.getWind}</td>
</tr>
</c:forEach>
</table>
</div>
</hr>
</body>
</html>
Basically, I'm trying to use the User input from the textbox as a value for the cityname inside the openweathermap URL. Is this possible? If so may you show a way to do it?

How to sent data from form to backend? [Java]

how to send data from the form view to the backend? I want to use the collected data to create a JSON request.
#Controller
public class ControllerClass {
Connect connect = new Connect();
#RequestMapping(value = "/Search", method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView("Forms", "FlightDTO", new FlightDTO());
}
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect();
}
}
View class collecting data.
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handling Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/connect}" th:object="${FlightDTO}" method="post">
<p>Orgin: <input type="text" th:field="*{Origin}" /></p>
<p>Departure: <input type="text" th:field="*{Departure}" /></p>
<p>DateFrom: <input type="text" th:field="*{DateFrom}" /></p>
<p>DateTo: <input type="text" th:field="*{DateTo}" /></p>
<p>Currency: <input type="text" th:field="*{Currency}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
Class responsible for consume data JSON.
public class Connect {
public String connect() {
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
URL url = new URL(urlBuilder.ulr());
HttpURLConnection conn = (HttpURLConnection) url.openConnection() ;
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
output = response.toString();
} catch (Exception e) {
System.out.println("Exception Flight:- " + e);
}
return output;
}
}
Class that is responsible for collecting data from the view
public class FlightDTO {
private String dateFrom;
private String dateTo;
#Size(min = 2, max = 10)
private String origin;
#Size(min = 2, max = 10)
private String departure;
#Size(min = 2, max = 4)
private String currency;
My URL builder Class responsible for build request.
public class UrlBuilder extends FlightDTO {
private String key = "47c5ebee552ce27c902e7521b6ef3858";
public String ulr( ) {
String connectUrlString =
"http://api.travelpayouts.com/v1/prices/cheap?origin="
+ getOrigin() + "&destination=" + getDeparture() +
"&depart_date=" + getDateFrom() +
"&currency=" + getCurrency() +
"&return_date=" + getDateTo() +
"&token=" + key;
return connectUrlString ;
}
}
I tried to solve my problem in many ways. Unfortunately to no avail, that's why I decided to create a thread. I could not find a similar problem. I was probably looking for a bad one. However, I do not know how to google
I get null response :
http://api.travelpayouts.com/v1/prices/cheap?origin=null&destination=null&depart_date=null&currency=null&return_date=null&token=47c5ebee552ce27c902e7521b6ef3858
Above code will not work as you are creating new UrlBuilder object which will not have any values instead of passing flightDTO object from the controller.
Controller
#RequestMapping(value = "/connect", method = RequestMethod.POST)
public String submit(#Valid #ModelAttribute("FlightDTO") FlightDTO flightDTO,
BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return "error.jsp";
}
return connect.connect(flightDTO); //passing flightDTO object received from form
}
Connect
public String connect(FlightDTO flightDTO) { //Added new parameter to recevice flightDTO
String output = null;
try {
UrlBuilder urlBuilder = new UrlBuilder();
urlBuilder.setOrigin(flightDTO.getOrigin());
urlBuilder.setDestination(flightDTO.getDestination());
urlBuilder.setDateFrom(flightDTO.getDateFrom());
urlBuilder.setDateTo(flightDTO.getDateTo());
......//Set other required values
urlBuilder.ulr();
System.out.println("URL String : " + urlBuilder.ulr());
......//other code
}
}

How to receive info to put in HTML/JSP from post servlet

Basically my goal for this page I'm working on is for users to type in a stock symbol and this information goes to a post method and send back the data to put on the same html/jsp page. I have been able to get this to work where the form leads to another JSP page, but that has to be a separate page, I'd like to be able to stay on the same page and have the info come up. If you have a resource that could teach me how to deal with this problem, I would appreciate that just as much as a solution. I have been using the Gradle Build Tool.
Here is the form(in index.jsp):
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
Here is the functioning JSP code(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
Here is the servlet I tried writing(DataServlet.java), I have very little experience with servlets, I scavenged this from different sources and questions on stackoverflow:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
#javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
If you want to use only one page and with a servlet, I think you can use session and response.sendRedirect() to do it.
This is index.jsp page
<h1>Search Stock</h1>
<form method="POST" action="DataServlet" onsubmit="dataCheck()">
<input type="text" name="Symbol">
<input type="submit" value="getData">
</form>
<%
if(session.getAttribute("data") != null) {
out.print("<p>" + session.getAttribute("data"));
session.removeAttribute("data");
}
%>
<script>
function dataCheck() {
if(document.getElementsByName[0].value == ""){
alert("Symbol is null!");
return false;
}
return true;
}
</script>
This is DataServlet class
public class DataServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Ticker = request.getParameter("Symbol");
Company object = Serializing.getCompany(Ticker);
if (object != null) {
object.updateData();
request.getSession().setAttribute("data", object.getSentiment() +
"updated last" + object.getLastUpdate());
} else {
request.getSession().setAttribute("data", "We do not have info on this stock");
}
response.sendRedirect("index.jsp");
}
}

Uploading multiple files using jsp & servlets [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 2 years ago.
I am currently working on a dynamic web application that I want the user to be able to upload multiple files at once for the application to use. I don't know how many files the user may upload at once; it could be 2 or it could 100+ files. I am new to JSP dynamic web applications and I have started with a single upload file but I am not really sure where to go from here. I've looked at few examples searching but I haven't been able to find exactly what I was looking for. This is what I have so far:
Servlet:
package Servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
if (isMultipart)
{
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext())
{
FileItem item = (FileItem) iterator.next();
if (!item.isFormField())
{
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root + "/uploads");
if (!path.exists())
{
boolean status = path.mkdirs();
}
File uploadedFile = new File(path + "/" + fileName);
System.out.println(uploadedFile.getAbsolutePath());
if(fileName!="")
item.write(uploadedFile);
else
out.println("file not found");
out.println("<h1>File Uploaded Successfully....:-)</h1>");
}
else
{
String abc = item.getString();
out.println("<br><br><h1>"+abc+"</h1><br><br>");
}
}
}
catch (FileUploadException e)
{
out.println(e);
}
catch (Exception e)
{
out.println(e);
}
}
else
{
out.println("Not Multipart");
}
}
}
.JSP File:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Select file to upload:
<p><input type="file" name="dataFile" id="fileChooser" />
<input type="submit" value="Upload" multiple="multiple" /></p>
</form>
I am looking for a way to upload multiple files instead of just one and show them in a list.
Check the FileUPload Using Servlet 3.0
It has a working code for uploading Single File Using Servlet3.0 As you can see code is now much simplified . And there is no dependancy on apache Library.
just use below index.html
<html>
<head></head>
<body>
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Select File to Upload:<input type="file" name="fileName" multiple/>
<br>
<input type="submit" value="Upload"/>
</form>
</body>
</html>
Only change here is I have used multiple attribute for input type File
Oh... At the first glance, looks like a simple mistake. multiple is an attribute of file input, not of the submit button.
i have upload multiple files using jsp /servlet.
following is the code that i have used.
<form action="UploadFileServlet" method="post">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
on the other hand server side. use following code.
package com.abc..servlet;
import java.io.File;
---------
--------
/**
* Servlet implementation class UploadFileServlet
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UploadFileServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.sendRedirect("../jsp/ErrorPage.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession httpSession = request.getSession();
String filePathUpload = (String) httpSession.getAttribute("path")!=null ? httpSession.getAttribute("path").toString() : "" ;
String path1 = filePathUpload;
String filename = null;
File path = null;
FileItem item=null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String FieldName = "";
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
item = (FileItem) iterator.next();
if (fieldname.equals("description")) {
description = item.getString();
}
}
if (!item.isFormField()) {
filename = item.getName();
path = new File(path1 + File.separator);
if (!path.exists()) {
boolean status = path.mkdirs();
}
/* START OF CODE FRO PRIVILEDGE*/
File uploadedFile = new File(path + Filename); // for copy file
item.write(uploadedFile);
}
} else {
f1 = item.getName();
}
} // END OF WHILE
response.sendRedirect("welcome.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
images.jsp
choose files:
storeimages.java servlet
public class storeimages extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String sav_dir=""; //this will be a folder inside
//directory
PrintWriter out =response.getWriter();
//if you want u can give this at run time
sav_dir="6022"; //in my case folder name is 6022
//you can alse set this at dynamic
int flag = 0;
//now set the path
//this is the path where my images are stored
//now u can see the code
String savepath="K:/imageupload"+File.separator +sav_dir;
File file = new File(savepath);
if(!file.exists()){
file.mkdir();
}
String filename="";
List<Part> fileParts = request.getParts().stream().
filter(part->"file".equals(part.getName())).collect(Collectors.
toList());
for(Part filePart: fileParts){
filename=Paths.get(filePart.getSubmittedFileName()).
getFileName().toString();
filePart.write(savepath+File.separator+filename);
flag=1;
}
if(flag==1){
out.println("success");
}
else{
out.println("try again");
}
//now save this and run the project
}
}
You only have to write multiple, because multiple is a boolean var and only defining it, it will be true to your tag. Example below:
<input type="file" name="file" id="file" multiple/>
This will let you choose multiple files at once. Good luck
This is how I did. It will dynamically add and remove the field (multiple files). Validates it and on validation calls the action method i.e the servlet and store in the DB.
** html/jsp **
.jsp file
<div class="recent-work-pic">
<form id="upload_form" method="post" action="uploadFile" enctype="multipart/form-data" >
<input type="hidden" id="counter" value="1" >
Add
<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_0" class="upload_input"></div>
<div id="add_field_div"></div>
<button type="submit" class="btn btn-read">Submit</button>
</form>
<p>${message}</p>
</div>
jquery validation
<script>
$(document).ready(function(){
$('#add_fields').click( function(){
add_inputs()
});
$(document).on('click', '.remove_fields', function() {
$(this).closest('.record').remove();
});
function add_inputs(){
var counter = parseInt($('#counter').val());
var html = '<div class="record"><input type="file" placeholder="Upload File" name="uploadFile_' + counter + '" class="upload_input">Remove</div>';
$('#add_field_div').append(html);
$('#counter').val( counter + 1 );
}
$('form#upload_form').on('submit', function(event) {
//Add validation rule for dynamically generated name fields
$('.upload_input').each(function() {
$(this).rules("add",
{
required: true,
messages: {
required: "File is required",
}
});
});
});
$("#upload_form").validate();
});
</script>
servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// KeycloakPrincipal principal = (KeycloakPrincipal) request.getUserPrincipal();
PrintWriter writer = response.getWriter();
Properties properties = new Properties();
properties.load(this.getClass().getClassLoader().getResourceAsStream("/resources/datenBank.properties"));
if (!ServletFileUpload.isMultipartContent(request)) {
writer.println("Fehler: Form must has enctype=multipart/form-data.");
writer.flush();
return;
}
String message = null;
InputStream inputStream = null;
Connection dbConnection = null;
String page = "";
try {
for (Part filePart : request.getParts()) {
System.out.println("filePart" + filePart.getName() + "-----" + filePart.getSize());
if (filePart != null && filePart.getSize() != 0) {
inputStream = filePart.getInputStream();
System.out.println("inputStream" + inputStream);
HttpSession session=request.getSession();
session.setAttribute("username",request.getRemoteUser());
Class.forName(properties.getProperty("driverClassName"));
dbConnection = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"));
if (dbConnection != null) {
String sql = "INSERT INTO skl_lieferung (file_name, file_size, file_content,file_content_type, entry_time, user) values (?,?,?,?,?, ?)";
PreparedStatement statement = dbConnection.prepareStatement(sql);
if (inputStream != null) {
statement.setString(1, getFileName(filePart));
statement.setLong(2, filePart.getSize());
statement.setBlob(3, inputStream);
statement.setString(4, filePart.getContentType());
}
Calendar calendar = Calendar.getInstance();
java.sql.Date entryDate = new java.sql.Date(calendar.getTime().getTime());
statement.setDate(5, entryDate);
statement.setString(6, request.getRemoteUser());
//statement.setString(6, username);
int row = statement.executeUpdate();
if (row > 0) {
message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
message = "Fehler: Connection Problem";
}
} message = "Datei hochgeladen und in der Datenbank gespeichert";
}else {
page = "index.jsp";
System.out.println("cannot execute if condition");
message = "Das Upload-Feld darf nicht leer sein ";
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
return;
}
}
}catch (Exception exc) {
page = "index.jsp";
message = "Fehler: " + exc.getMessage();
exc.printStackTrace();
} finally {
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
page = "index.jsp";
request.setAttribute("message", message);
RequestDispatcher dd = request.getRequestDispatcher(page);
dd.forward(request, response);
}
}
}
private String getFileName(Part part) {
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
I hope people find it useful!!
To upload a single file you should use a single tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
That is, use the below line multiple times:
<input type="file" name="dataFile" id="fileChooser" /><br><br>
Refer this link for details
I hope this helps.

Categories

Resources