Cannot call getWriter(), getOutputStream() already called [duplicate] - java

This question already has answers here:
getOutputStream() has already been called for this response
(15 answers)
Servlets in java - both getWriter() and getOutputStream()
(3 answers)
getting error "getOutputStream() has already been called for this response"
(1 answer)
JSP : getOutputStream() has already been called for this response
(2 answers)
Closed 2 years ago.
I have a program which uses spring mvc. I wrote two controllers which first one is for importing data and second one is for generating reports. I have a problem with generating controller. When user clicks generate button I want to generate report, save report on server hard disk and send report to user. When I am trying to save report on hard disk I've got Illegal state exception: Cannot call getWriter(), getOutputStream() already called. I searched for solution but I cannot find matched answer. This is my generator controller code:
#RequestMapping(value = "/generate", method = RequestMethod.POST)
public String generateReport(
Model model,
#Valid #ModelAttribute("reportProperties") ReportProperties reportProperties,
BindingResult result, HttpServletResponse response) {
if (result.hasErrors()) {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
return "import";
}
//Walidacja dat. Mozna przeniesc na validator
if(reportProperties.getEndDate().compareTo(reportProperties.getStartDate()) < 0){
model.addAttribute("logMessage", "Data końcowa jest wcześniejsza od poprzedniej");
return "import";
}
XSSFWorkbook report = null;
if (reportProperties.getReportType().equalsIgnoreCase("tv")) {
report = tvReportGenerator.generate(reportProperties);
} else if (reportProperties.getReportType().equalsIgnoreCase("prod")) {
report = prodReportGenerator.generate(reportProperties);
} else {
report = totalReportGenerator.generate(reportProperties);
}
if (report != null) {
saveReportOnHardDrive(report);
sendReportToUser(report, response);
} else {
model.addAttribute("logMessage",
"Generowanie Raportu nie powiodlo sie.");
}
return "import";
}
private void saveReportOnHardDrive(XSSFWorkbook report) {
try {
Resource resource = new ClassPathResource("/general.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String path = props.getProperty("saveFilePath");
FileOutputStream out = new FileOutputStream(new File(path
+ new Date() + ".xlsx"));
report.write(out);
out.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void sendReportToUser(XSSFWorkbook report,
HttpServletResponse response) {
try {
response.setContentType("application/xlsx");
response.setHeader("Content-Disposition",
"attachment; filename=generate.xlsx");
report.write(response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I tried some solution with closing and flushing response OutputStream but it did not work.
This is my import.jsp file:
<body>
<div id="Container">
<h1>Mediaplany GigaShopping instrukcja</h1>
<h2>Import Mediaplanu pobierz szablon</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importMediaplan">
<input type="file" name="mediaplanFile"/>
<input type="submit" value="Prześlij plik"/>
</form>
<h2>Import cennika aktualny cennik</h2>
<form method="POST" enctype="multipart/form-data"
action="/GigaShopping/importPriceList">
<input type="file" name="pricelistFile">
<input type="submit" value="Prześlij plik">
</form>
<h2>Generowanie raportów</h2>
<form:form method="POST" action="/GigaShopping/generate" commandName="reportProperties">
<table>
<tr>
<td>Typ raportu:</td>
<td>
<label><form:radiobutton path="reportType" value="tv"/> M/S TV</label>
<label><form:radiobutton path="reportType" value="prod"/> M/S PROD</label>
<label><form:radiobutton path="reportType" value="total"/> M/S TOTAL</label>
</td>
</tr>
<tr>
<td>Stacja</td>
<td>
<form:select path="tvName">
<form:options items="${televisionsList}"/>
</form:select>
</td>
</tr>
<tr>
<td>Od</td>
<td><form:input type="date" path="startDate" id="startDatePicker"/></td>
</tr>
<tr>
<td>Do</td>
<td><form:input type="date" path="endDate" id="endDatePicker"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Generuj"></td>
</tr>
</table>
</form:form>
<form:form method="POST" action="/GigaShopping/requestDBContent" commandName="requestProperties">
<form:input type="date" id="requestDatePicker" path="date"/>
<form:select path="tvName">
<form:option value="wszystkie">--wszystkie--</form:option>
<form:options items="${televisionsList}"/>
</form:select>
<input value="zobacz mediaplan" type="submit" name="requestMediaplanButton" />
<input value="zobacz zamówienia" type="submit" name="requestOrdersButton"/>
</form:form>
<span class="logMessage">${logMessage}</span>
<footer>
CNS 2015
</footer>
</div>
Thanks for any help.
Regards,
Sebatian

As #M. Deinum said
you have to return null instead of the name of page your are trying to forward..

Related

How to insert data into DB table using restful-webservices?

I have been now trying for many days to insert data into database using restful webservices but with no luck. I have a Service.java controller and three model classes (Candidate.java, Kysymykset.java, Vastaukset.java and VastauksetPK(the primary key class for vastaukset table)) "Candidate" and "Kysymykset" have a one to many relation with "Vastaukset".
In the controller I have one function that reads all the question from the Kysymykset table and print them for the user using a jsp form (candQues.jsp) and this function works fine. However, when I try to answer the question that are in the same form the "/addAnswer" function just doesn't add them to the database table "vastaukset".
keep in mind that I am trying to retrieve the "candidate_id" and "kysymykset_id" from the "candidate" table and the "kysymykset" table respectively.
I tried to use request. getParameter and also formparams.getFirst in different ways but apparently I have yet to understand the proper way to implement it. Any help and suggestion would be much appreciated.
Below I added the "addAnswer" function along with the jsp form and the vastaukset table class.
Below is the service.java:
..code
#POST
#Path("/addAnswer")
// #Produces(MediaType.TEXT_HTML)
#Consumes("application/x-www-form-urlencoded")
public void addAnswer(MultivaluedMap <String, String> formparams, #Context HttpServletRequest request, #Context HttpServletResponse response)
throws IOException, ServletException {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("electionMachine");
EntityManager em = emf.createEntityManager();
// int kysymykset = Integer.parseInt(request.getParameter("kysymykset_id"));
try {
int candidate_id = Integer.parseInt(formparams.getFirst("candidate_id"));
int kysymys_ID = Integer.parseInt(formparams.getFirst("kysymys_ID"));
int vastaus = Integer.parseInt(formparams.getFirst("kysymys"));
String kommentti = formparams.getFirst("kommentti");
// System.out.println(" "+kommentti+" "+vastaus+" "+candidate_id+" ");
Vastaukset vas = new Vastaukset();
vas = new Vastaukset(candidate_id, kysymys_ID, vastaus, kommentti);
Kysymykset k = new Kysymykset();
k.setKysymys_ID(kysymys_ID);
vas.setKysymykset(k);
em.getTransaction().begin();
em.persist(vas);
em.getTransaction().commit();
em.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
..code
Vastaukset.java:
..code
#NamedQuery(name="Vastaukset.findAll", query="SELECT v FROM Vastaukset v")
public class Vastaukset implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private VastauksetPK id;
private String kommentti;
private int vastaus;
//bi-directional many-to-one association to Candidate
#ManyToOne
#JoinColumn(name="candidate_id")
private Candidate candidate;
//bi-directional many-to-one association to Kysymykset
#ManyToOne
#JoinColumn(name="kysymys_ID")
private Kysymykset kysymykset;
public Vastaukset() {
}
public Vastaukset(int candidate_id, int kysymys_ID, int vastaus, String kommentti) {
// TODO Auto-generated constructor stub
try {
this.candidate.setCandidate_id(candidate_id);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
this.kysymykset.setKysymys_ID(kysymys_ID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.vastaus=vastaus;
this.kommentti=kommentti;
}
public Vastaukset(int candidate_id, int vastaus, String kommentti) {
// TODO Auto-generated constructor stub
this.candidate.setCandidate_id(candidate_id);
this.vastaus=vastaus;
this.kommentti=kommentti;
}
//getters and setters..
candQues.jsp:
..code
<h1>Candidate Questions Form</h1>
<br>
<form action='/rest/service/addAnswer' method='post'>
<input type="text" name="candidate_id"
value="${sessionScope.LoggedUser.candidate_id}">
<table>
<tr>
<td>CandidateID</td>
<td>QuestionsID</td>
<td>Questions</td>
</tr>
<c:forEach var="Kysymys" items="${requestScope.Kysymyslista}">
<tr>
<td>${sessionScope.LoggedUser.candidate_id}</td>
<td>${Kysymys.kysymys_ID}</td>
<td>${Kysymys.kysymys}</td>
<td><input type="radio" id="q1${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="1"> <label
for="q1${Kysymys.kysymys_ID}">1</label><br></td>
<td><input type="radio" id="q2${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="2"> <label
for="q2${Kysymys.kysymys_ID}">2</label><br></td>
<td><input type="radio" id="q3${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="3"> <label
for="q3${Kysymys.kysymys_ID}">3</label><br></td>
<td><input type="radio" id="q4${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="4"> <label
for="q4${Kysymys.kysymys_ID}">4</label><br></td>
<td><input type="radio" id="q5${Kysymys.kysymys_ID}"
name="kysymys${Kysymys.kysymys_ID}" value="5"> <label
for="q5${Kysymys.kysymys_ID}">5</label><br></td>
<td><input type="text"
name="kommentti${Kysymys.kysymys_ID}"
value="Add an Explanation">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<table>
<tr>
<td><input type='submit' name='ok' value='Answer'
style="font-size: 30px"></td>
..code
I noticed too that I am not getting the "Kysymys_ID" from any where and I don't know whether I should be getting it since it is part of the "vastaukset" table, and if so, I don't know how. I am a beginner in IT and I know that this code is very messy. I hope you can bare with me and I am sorry in advance if this is not clear enough but I would be happy to clarify more in the comment section if needed.

Spring Web App - Refreshing data routinely

I'm currently developing an online banking application where you can buy stocks. It is being built with spring boot and the front-end is html/css.
I am using the YahooFinance API to get stock quotes but I need to refresh my page to get the live stock quotes, how can I automatically update the page every 30 seconds to get the new prices for each stock?
Also, is there a way I could implement this using Threads?
Banking Controller
#GetMapping("/banking/stocks")
public String stocks(Model model) {
model.addAttribute("stock", new StockDto());
try {
List<Stock> stocks = stockService.getDefaultStocks();
model.addAttribute("stocks", stocks);
} catch (IOException e) {
e.printStackTrace();
}
return "stocks.html";
}
StockServiceImpl:
#Service
public class StockServiceImpl implements StockService {
private String[] startingStocks = { "AAPL", "BABA", "MSFT", "AXP", "BA", "AMD", "TSLA", "MA", "SHOP", "GOOGL",
"KL" };
#Override
public Stock getStock(String stockName) throws IOException {
Stock stock = YahooFinance.get(stockName);
return stock;
}
#Override
public Map<String, Stock> getStock(String[] s) throws IOException {
Map<String, Stock> stocks = YahooFinance.get(s);
return stocks;
}
#Override
public List<Stock> getDefaultStocks() throws IOException {
Map<String, Stock> stocks = YahooFinance.get(startingStocks);
List<Stock> stockList = new ArrayList<Stock>();
for(String s : startingStocks) {
stockList.add(stocks.get(s));
}
return stockList;
}
}
HTML Page For Displaying Stocks:
<main class='main-content bgc-grey-100'>
<div id='mainContent'>
<div class="container-fluid">
<br>
<h4 class="c-grey-900 mT-10 mB-30">Stock Table</h4>
<form action="#" th:object="${stock}" th:action="#{/banking/stock-search}"
method="POST" class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search"
th:field="*{name}" placeholder="Search Stock"
aria-label="Search">
<button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button>
</form>
<br>
<div class="row">
<div class="col-md-12">
<div class="bgc-white bd bdrs-3 p-20 mB-20">
<table id="dataTable" class="table table-striped table-bordered"
cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Ticker</th>
<th>Trade</th>
<th>Name</th>
<th>Price</th>
<th>(%) Change</th>
<th>Div Yield (%)</th>
</tr>
</tfoot>
<tbody>
<tr th:each="stock : ${stocks}">
<td th:text="${stock.getSymbol()}"></td>
<td>
<form action="#" th:action="#{/banking/stocks/} + ${stock.symbol}" method="get">
<button class="btn btn-outline-success my-2 my-sm-0" th:id="'table_entry_childs_button_' + ${stock.symbol}" type="submit">
<i>Trade</i>
</button>
</form>
</td>
<td th:text="${stock.getName()}"></td>
<td th:text="${stock.getQuote().getPrice()}"></td>
<td th:class="${stock.getQuote().getChangeInPercent() > 0 ? 'text-success' : 'text-danger'}" th:text="${stock.getQuote().getChangeInPercent() + '%'} "></td>
<td th:if="${stock.getDividend().getAnnualYield() != null}" th:text="${stock.getDividend().getAnnualYield() + '%'}">0.00%</td>
<td th:if="${stock.getDividend().getAnnualYield() == null}" >0.00%</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</main>
You can exploit STOMP protocol and web sockets using spring boot.
For reference:
https://www.baeldung.com/spring-websockets-send-message-to-user
on back end side you can use
#Autowired
SimpMessagingTemplate messagetemplate;
public void somemethod(String strParam){
while (true){
// build string or json whatever you need to send
messagetemplate.convertAndSend("/blabla/blabla",strParam);
Thread.sleep(30*1000);
}
}
on front end side you have to use stomp.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.js">
<script type="text/javascript">
function load(){
var stompClient = Stomp.client("ws://localhost:8080/ws");
stompClient.connect({}, function (frame) {
stompClient.subscribe('/blabla/blabla', function (message) {
// do something here
});
});
}
lastly, part of html where you want to call on load
<html>
<body onload="load()">
</body>
</html>
You can create an #Scheduled method that can call this API request every 30 seconds to get data and update your Front-End.
#Scheduled(fixedRate = 30000)
public void updateStocksElement() {
//Call your /banking/stocks rest endpoint
}
https://spring.io/guides/gs/scheduling-tasks/

Can not insert data into two tables spring mvc

Im using Spring mvc and facing the problem about inserting data into two tables, my target is inserting data into 2 tables from 1 jsp (1 form)
I have two 2 tables:
1.Cars
Id
Name
CityId(FK)
2.City
Id
Name
this is my controller:
#RequestMapping(value="/CreateCar", method = RequestMethod.GET)
public ModelAndView getCreateCarPage(ModelMap model) throws ServletException, IOException {
try {
Car myCar = new Car();
City city = new City();
myCar.setCity(city);
model.addAttribute("city", city);
model.addAttribute("createCar", myCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("testForm");
}
#RequestMapping(value="/CreateCar", method = RequestMethod.POST)
public ModelAndView setCreateCarPage(ModelMap model,
#ModelAttribute("createCar") Car createCar) throws SQLException, Exception {
try {
carService.createCar(createCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("successProcess");
}
}
JSP:
<form:form modelAttribute="createCar" method="POST" commandName="createCar" action="/CreateCar" enctype="multipart/form-data">
<fieldset style="width:300px">
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td>
<label>Name of car</label>
<form:input path="name" id="name"/>
</td>
<td>
<label>Name of city</label>
<form:input path="city.name" />
</td>
</tr>
<tr>
<td><input class="btn btn-danger" type="submit" value="Inser New" style="width:100px;" /></td>
</tr>
</table>
</fieldset>
With above source, it just insert name of car success but can not insert name of city
Log massages:
SqlExceptionHelper - Column 'city_id' cannot be null
How can I fix this problem ? thank so much !

text field in file upload servlet, Java

In my java application i am uploading multiple files using java servlet.
All things works fine until i added extra text field in my form.
I am getting null document when i add text field.
Here is my code:-
JSP Form:-
<form action="upload/servlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Upload File: </td>
<td><input type="file" name="file" multiple/>
</td>
<td style="color: red; font-style: italic;"><form:errors
path="file" />
</td>
</tr>
<tr>
<td>Generate Key</td><td> </td>
<td><input type="button" value="Change Key"/>
</td>
<td>${key}</td>
</tr>
<tr>
<td>Zip Code</td><td> </td>
<td><input type="text" value="100001" name="zipcode"/>
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Upload" />
</td>
<td> </td>
</tr>
</table>
</form>
Here is my servlet:-
#Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(req)) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST,"Multipart content expected!");
}
ModelMap model = new ModelMap();
try {
#SuppressWarnings("unchecked")
List<FileItem> files = this.upload.parseRequest(req);
String userName=req.getSession().getAttribute("username").toString();
String fileName;
String contentType;
byte[] content;
System.out.print("Zipcode is "+req.getParameter("zipcode"));
for(FileItem item : files) {
if(item.isFormField()){
fileName = item.getName();
contentType = item.getContentType();
content = item.get();
String id=this.indexDocument(fileName, contentType, content,userName,req);
model.put(id, fileName);
System.out.println("Done for "+fileName+ " id "+id);
}
}
} catch (FileUploadException e) {
System.out.println("Error FileUploadException: "+e.getMessage());
throw new ServletException(e);
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error "+e.getMessage());
}
req.setAttribute("message", model);
req.getSession().setAttribute("tmpRetMessage", model);
// RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/success.do");
//dispatcher.forward(req, resp);
resp.sendRedirect("../success.do");
}
If i add two text fields then getting null document error two times. If i add three times then getting error three times.
Here form enctype type multipart (enctype="multipart/form-data"). So request.getParameter() value will be null. So you need to process file field and regular fields means other than file like text, radio, etc separately.
see for more how to get request parameters

Cannot pass multipart data to servlet when using jsp el

I am passing checkbox values, username , file as parameter to a servlet that uses MultipartRequest class from com.orielly.servlet package. I am using the jsp el in my jsp.
my jsp is
<c:set var="currentUser" value="${currentUser}" />
<div class="container">
<div class="panel panel-default" >
<div class="panel-body">
<div class="panel panel-default">
<div class="panel-body">
<form action="ProcessShareFileReq?username="${currentUser}" method="post" enctype="multipart/form-data">
<h4>Upload file here</h4>
<input type="file" class="form-control" required="required" name="file" value=""/>
<h4 class="page header">Share with</h4>
<ul class="list-group">
<c:forEach var="request" items="${requestList}">
<li class="list-group-item title">
<input type="checkbox" name="usersList" value="${request.senderFullName}" /><strong> ${request.senderFullName} </strong>
</li>
</c:forEach>
</ul>
<label class="label" for ="description">Description(Helps other users understand the content of file)</label>
<textarea id="description" name="fileDescription" rows="10" cols="5"></textarea>
<div class="break"></div>
<input type="submit" class="btn btn-default pull-left" value="Upload">
<input type="reset" class="btn btn-default pull-left" value="Reset">
</form>
</div>
</div>
</div>
</div>
</div>
my servlet
#WebServlet("/ProcessShareFileReq")
#MultipartConfig
public class ProcessShareFileReq extends HttpServlet {
private static final long serialVersionUID = 1L;
private String webTempPath;
public void init( ) {
webTempPath= "C://BEProject/Shared";
//webTempPath = getServletContext( ).getRealPath("/") + "data";
}
//Generates current time suitable for oracle timestamp
private static java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection currentCon =null;
PreparedStatement ps = null;
int result;
//list of users to share with
String[] UserList = request.getParameterValues("usersList");
//logged-in-user's username
String loggedInUser = request.getParameter("username");
//Shared file's description
String fileDescription = request.getParameter("fileDescription");
//adding path according to sharer's user-name
String userPath = webTempPath + "/" + loggedInUser;
//generate directory
boolean success =( new File(userPath)).mkdirs();
//make directory
if(success) {
System.out.println("Directory: " + webTempPath + " created");
}
//Renames file to the 'sharer_receipent_timestamp' pattern
//Get the uploaded file with multipartRequest
//file limit size of 50 MB
MultipartRequest mpr = new MultipartRequest(request,userPath,50 * 1024 * 1024);
//Database create operations.
Enumeration enum1 = null;
try {
currentCon = ConnectionManager.getConnection();
currentCon.setAutoCommit(true);
for(int i=0;i<UserList.length;i++)
{
String shareFileQuery = "insert into sharedfiles values(share_seq.NEXTVAL,?,?,?,?,?)";
ps = currentCon.prepareStatement(shareFileQuery);
//set the values to put in the query
ps.setString(1, loggedInUser);
ps.setString(2, UserList[i]);
enum1 = mpr.getFileNames( );
String filename = mpr.getFilesystemName((String) enum1.nextElement());
ps.setString(3, filename);
ps.setString(4, fileDescription);
ps.setTimestamp(5, getCurrentTimeStamp());
result=ps.executeUpdate();
if(result>0)
{
System.out.println("Database updated \n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
response.setContentType("text/html");
request.setAttribute("username", loggedInUser);
RequestDispatcher rd = request.getRequestDispatcher("/SharedFilesHistory");
rd.forward(request, response);
}
I have annotated the servlet with #MultipartConfig so that it can handle the file parameter.
But after adding this it goes upto to the last line and gives error as
java.io.IOException: Corrupt form data: premature ending
com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:207)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:223)
com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:110)
servlet.share.ProcessShareFileReq.doPost(ProcessShareFileReq.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
filter.authentication.AuthenticationFilter.doFilter(AuthenticationFilter.java:40)
When remvoving the MultipartConfig it gives a NullPointerException at the for loop since 'UserList' is null since no value is received in servlet from jsp.
Please help
I remember having some little issues when working with MultipartRequest (seems related to some bugs), which made me drop its usage in favor of the native Servelt 3.x Part and which may be a good alternative for you:
Inside your doPost method you can retrieve your file as a Part of the request using its name:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//...
Part filePart = request.getPart("file"); // Retrieves <input type="file" class="form-control" required="required" name="file" value=""/>
InputStream fileContent = filePart.getInputStream(); // Get an InputStream then let the file make its way to your storage location
}

Categories