I am working on a project using Struts2. In that, there is a dynamic dropdown. Whenever I select values and submit the page I'm getting below exception. I tried a few alternatives but nothing worked for me. Below is the exception stack trace.
SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'locname': The requested list key 'requestListLocationInfo' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:260)
at org.apache.struts2.components.Component.findValue(Component.java:356)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:84)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:104)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:886)
at org.apache.struts2.components.UIBean.end(UIBean.java:535)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fselect_005f0(AddReader_jsp.java:592)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fform_005f0(AddReader_jsp.java:426)
at org.apache.jsp.AddReader_jsp._jspService(AddReader_jsp.java:332)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.result.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:173)
at org.apache.struts2.result.StrutsResultSupport.execute(StrutsResultSupport.java:208)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:52)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:199)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:157)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:201)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:53)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:577)
at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
JSP Code
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage />
</div>
</s:if>
<s:elseif test="hasActionErrors()">
<div class="errors">
<s:actionerror />
</div>
</s:elseif>
<div id="myDIV" style="margin-top: 8%; margin-left: 25%;">
<label>Reader IP:</label>  <input type="text" name="readerIp" id="readerIp" required>      <br>
<label>Antenna ID:</label>  <input type="text" name="antennaId" id="antennaId" required> 
    <br> <label>Select Gate:</label> 
<s:select id="locname" name="locname" list = "requestListLocationInfo" listKey = "locId" listValue = "locname" headerKey = "-1" headerValue = "Select Gate" />
<br>
<button class="btn" id="newBtn"
style="margin-top: 2%; margin-left: 17%; width: 17%; text-decoration: none;"
onclick="clickedMe(this.id)">Add</button>
</div>
</s:form>
Method in Action class:
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String addReaderConfig() {
HttpServletRequest req = ServletActionContext.getRequest();
try {
String locName = req.getParameter("newButton");
int locationid = Integer.parseInt(locName);
String readerIp = req.getParameter("readerIp");
String antenaID = req.getParameter("antennaId");
int antennaId = Integer.parseInt(antenaID);
String created_by = req.getParameter("created_by");
String company_id = (String) ActionContext.getContext().getSession().get("company_id");
int companyId = Integer.parseInt(company_id);
int i = ChartDAO.addReader(readerIp, antennaId, locationid, companyId, created_by);
if (i > 0) {
msg = Constants.READER_ADDED_SUCCESSFULLY;
addActionMessage(msg);
} else {
msg = Constants.READER_ADDING_FAILED;
addActionError(msg);
return Constants.ERROR;
}
} catch (Exception e) {
e.printStackTrace();
return Constants.ERROR;
}
return Constants.SUCCESS;
}
POJO
private int locId;
private String locname;
private List < ChartPOJO > requestListLocationInfo = null;
public String getLocname() {
return locname;
}
public void setLocname(String locname) {
this.locname = locname;
}
public int getLocId() {
return locId;
}
public void setLocId(int locId) {
this.locId = locId;
}
public List < ChartPOJO > getRequestListLocationInfo() {
return requestListLocationInfo;
}
public void setRequestListLocationInfo(List < ChartPOJO > requestListLocationInfo) {
this.requestListLocationInfo = requestListLocationInfo;
}
Method in DAO class
public static int addReader(String readerIp, int antennaId, int locId, int company_id, String created_by) {
int status = 0;
String driverClass = Constants.DB_Driver;
Class.forName(driverClass);
String url = Constants.DB_Address;
String username = Constants.DB_Username;
String password = Constants.DB_Password;
try (Connection conn = DriverManager.getConnection(url, username, password);) {
try (PreparedStatement ps1 = conn.prepareStatement("select locationid,loc_name from locations where locationid=?");) {
ps1.setInt(1, locId);
try (ResultSet rs2 = ps1.executeQuery();) {
if (!rs2.next()) {
String query = "INSERT INTO reader(ipaddress,antenaid,companyid,locationid,status,created_by,created_date) values(?,?,?,?,?,?,?)";
try(PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, readerIp);
ps.setInt(2, antennaId);
ps.setInt(3, company_id);
ps.setInt(4, locId);
ps.setInt(5, 1);
ps.setString(6, created_by);
LocalDateTime now = LocalDateTime.now();
System.out.println("Before : " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
System.out.println("After : " + formatDateTime);
ps.setString(7, formatDateTime);
status = ps.executeUpdate();
System.out.println("after adding reader successfully");
}
} else {
System.out.println("location already exists");
}
}
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
return status;
}
return status;
}
May I know the reason for this exception and how to fix it. Thanks in advance.
You have to remove listKey or resolve it in select field somewhere in you project.
Your logs complain about requestListLocationInfo list probably without properly listKey value or with null value
Related
So I need a unix command to be executed by clicking a button in a jsp.
Here's the jsp:
<body>
<div align="center">
<h2>Welcome to ETL Automation Testing Tool</h2>
<h3>Please select Graph:</h3>
<table border="1">
<th>Graph</th>
<tr>
<td>Graph 1</td>
<td><INPUT TYPE="radio" NAME="graph" VALUE="radio1"></td>
</tr>
</table>
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>
All pretty straightforward there.
Here's the servlet:
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UnixPrompt unixprompt = new UnixPrompt();
unixprompt.connect();
}
}
Here's the code to connect to ssh and execute a command:
import com.jcraft.jsch.*;
import java.io.*;
public class UnixPrompt{
public static void connect(){
try{
JSch jsch=new JSch();
String host=null;
String user="******";
host="*******";
String config =
"Port 22\n"+
"\n"+
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n"+
"Host *\n"+
" ConnectTime 30000\n"+
" PreferredAuthentications keyboard-interactive,password,publickey\n"+
" #ForwardAgent yes\n"+
" #StrictHostKeyChecking no\n"+
" #IdentityFile ~/.ssh/id_rsa\n"+
" #UserKnownHostsFile ~/.ssh/known_hosts";
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
jsch.setConfigRepository(configRepository);
Session session=jsch.getSession("foo");
String passwd ="*****";
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public boolean promptYesNo(String message){
int foo = 0;
return foo==0;
}
};
session.setUserInfo(ui);
session.connect();
String command="pwd";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String arg[]){
connect();
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
}
I am able to connect to the SSH and execute commands through the standalone UnixPrompt class but am not able to do so through the jsp.
This is the error I am getting:
SEVERE: Servlet.service() for servlet [unix.MyServlet] in context with
path [/Scratchpad] threw exception [Servlet execution threw an
exception] with root cause java.lang.ClassNotFoundException:
com.jcraft.jsch.ConfigRepository at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at unix.MyServlet.doPost(MyServlet.java:17) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
The class the error refers to is present in the newer JSch jar having version 0.1.54 which I have included in the build path so I'm not sure what the problem is.
Any help would be appreciated
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Working on a Spring MVC based project, I am getting the following code while I try to save review (Bean). I am able to get the data into controller successfully but for some reason getting a NULL pointer exception while saving.
Here is the code
-- JSP--
<div class="col-md-12">
<div class="p-b">
<cf:form action="${pageContext.request.contextPath}/reviews/add" id="reviewAction" modelAttribute="review" method="post" accept-charset="utf-8">
<div style="display:none">
<cf:input path="tutorId" type="hidden" name="tutorId" id="tutorId" value="" />
<cf:input path="studentId" type="hidden" name="studentId" id="studentId" value="${sessionScope.user.userId}" />
</div>
<label>Your Comment / Review</label>
<cf:textarea path="reviewMessage" name="reviewMessage" required="required"/>
<p class="text-right"><input type="submit" class="btn btn-default btn-sm" name="submit" value="Post"> </p>
</cf:form>
</div>
</div>
<cf:hidden path="userId" id="userId"/>
<script type="text/javascript">
$(document).ready(function () {
console.log("Calling getTutorId()");
getTutorId();
});
function getTutorId()
{
$('#tutorId').attr('value',$('#userId').val());
}
</script>
-- Controller --
#RequestMapping (value = "/add" , method = RequestMethod.POST)
public String addReview(#Valid #ModelAttribute Review review , BindingResult bindingResult, Model model) {
try {
if (bindingResult.hasErrors()) {
System.out.println(bindingResult.getAllErrors().iterator().next().toString());
return "FindTutor";
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
String newDate = dateFormat.format(date); //06/08/2016 15:59:48
review.setDate(newDate);
review.setReviewStatus("Disapproved");
//Just for testing purposes
System.out.println(review.getStudentId());
System.out.println(review.getTutorId());
System.out.println(review.getDate());
System.out.println(review.getReviewMessage());
System.out.println(review.getReviewStatus());
//Just for testing purposes
reviewBL.saveReview(review);
List<Subject> subjectList = subjectBL.getAllSubjects();
List<User> userList = manageUserBL.getAllUsers();
model.addAttribute("subjectList", subjectList);
model.addAttribute("userList", userList);
} catch (Exception e) {
e.printStackTrace();
}
return "FindTutor";
}
-- Business Logic Class --
#Service
public class ReviewBL {
private ReviewsMongoRepository reviewsMongoRepository;
public void saveReview(Review review)
{
if (StringUtils.isEmpty(review.getId())) {
review.setId(null);
}
reviewsMongoRepository.save(review);
}
}
-- Bean Class --
#Document (collection = "reviews")
public class Review {
#Id
private String Id;
private String tutorId;
private String studentId;
private String date;
private String reviewMessage;
private String reviewStatus;
// plus constructors also all of the getters and setters
}
I am getting the following error message, and as you can see the data (Model Attribute is successfully been captured in the controller but is not being saved in the database due to a NULL pointer exception error that I can't seem to find out why
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /reviews/add
java.lang.NullPointerException
at edu.bnu.fyp.stp.bl.ReviewBL.saveReview(ReviewBL.java:23)
at edu.bnu.fyp.stp.web.controller.student.ReviewController.addReview(ReviewControll er.java:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at edu.bnu.fyp.stp.web.filter.SessionFilter.doFilter(SessionFilter.java:59)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
574939f19fcf9da523b63f8b // ID 1 (String)
57493a3e9fcf9da523b63f8c // ID 2 (String)
28/05/2016 13:16:59 //Date (String)
Great Tutor // Message (String)
Disapproved //Status (String)
2016-05-28 13:16:59 [http-bio-8080-exec-6] INFO e.b.fyp.stp.web.filter.SessionFilter - Filtering: /WEB-INF/jsp/FindTutor.jsp
I was able to resolve this issue. It was because I didn't apply #Autowired on reviewsMongoRepository so it wasn't linked with the review bean. I corrected this and now it is working. Thank you
Inside ReviewBL.saveReview you are calling reviewsMongoRepository.save(review)
But I can see you havent initialized reviewsMongoRepository, this is just a reference type reffering to "nothhing." It might be the cause of your Null Pointer exception
I try to create a restful service that uploads a file. I followed the steps of:
http://examples.javacodegeeks.com/enterprise-java/rest/jersey/jersey-file-upload-example/
http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
But, when I upload a file (for example, a .pdf), the input FormDataMultiPart is always NULL and I don´t understand why. I use the libs "jersey-multipart" and "jersey-core". My code:
Restful service:
#Path("/reservation")
public class ReservationWs {
/** The Constant log. */
private static final Logger LOGGER = LoggerFactory.getLogger(ReservationWs.class.getName());
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://opt/share/reservation/";
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER
+ fileDetail.getFileName();
// save it
saveFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
#POST
#Path("/upload2")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile2(FormDataMultiPart form) {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition headerOfFilePart = filePart.getContentDisposition();
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + headerOfFilePart.getFileName();
// save the file to the server
saveFile(fileInputStream, filePath);
String output = "File saved to server location using FormDataMultiPart : " + filePath;
System.out.println(output);
return Response.status(200).entity(output).build();
}
}
My client:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form Page</title>
</head>
<body>
<h1>Upload a File</h1>
<form action="reservation/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="55" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
When I try to call to "upload", the input is null and the error logs:
GRAVE: El Servlet.service() para el servlet [rest_1288520529] en el
contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile(ReservationWs.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
When I try to call to "upload2", the input is null and the error logs:
sep 11, 2015 9:12:21 AM org.apache.catalina.core.StandardWrapperValve
invoke GRAVE: El Servlet.service() para el servlet [rest_348842263] en
el contexto con ruta [/checking] lanzó la excepción [Error processing
webservice request] con causa raíz java.lang.NullPointerException at
com.checking.reservation.ws.ReservationWs.uploadFile2(ReservationWs.java:90)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497) at
org.apache.openejb.server.cxf.rs.PojoInvoker.performInvocation(PojoInvoker.java:43)
at
org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:165)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:89) at
org.apache.openejb.server.cxf.rs.AutoJAXRSInvoker.invoke(AutoJAXRSInvoker.java:68)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:57)
at
org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:93)
at
org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:263)
at
org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121)
at
org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:240)
at
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.onMessage(CxfRsHttpListener.java:187)
at
org.apache.openejb.server.rest.RsServlet.service(RsServlet.java:53)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:198)
at
net.bull.javamelody.MonitoringFilter.doFilter(MonitoringFilter.java:176)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Any idea?
I found a not good solution for now.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file") InputStream file, #FormDataParam("file") FormDataContentDisposition fileDetail, #QueryParam("fileName") String fileName){
...
...
String uploadedFileLocation = SERVER_UPLOAD_LOCATION_FOLDER+ fileName;//fileDetail.getFileName();
// save it
saveFile(file, uploadedFileLocation);
...
//Logic of the service.
...
//Delete file from local.
}
private void saveFile(InputStream uploadedInputStream, String serverLocation) throws IOException {
OutputStream outpuStream=null;
try {
outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch( IOException e){
LOGGER.debug("[UploadWs - saveFile] - error: "+e);
} finally{
if(outpuStream!=null){
outpuStream.close();
}
}
}
"fileDetail" is always null and I don´t know why (if anyone knows the solution, say it) so I add the parameter "fileName" (name of the file) that the client send me. I build the location, I save the file in local, the logic of the service is executed (in my case, I send an email with this file) and I delete the file from local.
It's not a good solution because I add an unnecesarry parameter and I save the file in local.
I'm using struts 2 and tomcat together.
The problem I'm facing is: whenever I submit data whether is wrong or not (username and password) it ALLWAYS makes following field error appear:
.Error setting expression 'userBean.password' with value ['XXX', ]
.Error setting expression 'userBean.username' with value ['YYY', ]
where 'XXX' is the password and 'YYY' is the username.
My action class is:
package direstruts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import direstruts.model.UserBean;
public class LoginAction extends GenericAction {
#Override
public void validate() {
UserBean uB = getUserBean();
if(uB.getUsername().isEmpty()) {
addFieldError("userBean.username", "Por favor Insira o Username de Utilizador");
}
if(uB.getPassword().isEmpty()) {
addFieldError("userBean.password", "Por favor Insira a Password de Utilizador");
}
}
public String getAuthentication() throws Exception {
if(getUserBean().getAuthentication()) {
addActionMessage("Log in bem Sucedido!");
return SUCCESS;
}
addActionError("Utilizador e/ou Password errados e/ou Utilizador já está logado");
return ERROR;
}
public String setNewUser() throws Exception {
if(getUserBean().setNewUser()) {
addActionMessage("User registado!");
return SUCCESS;
}
addActionError("Utilizador Já Existe! Tente Outro Username!");
return ERROR;
}
public String setQuitUser() throws Exception {
if(getUserBean().setQuitUser()) {
addActionMessage("User LoggedOut!");
return SUCCESS;
}
return ERROR;
}
public UserBean getUserBean() {
if(!session.containsKey("userBean"))
this.setUserBean(new UserBean());
return (UserBean) session.get("userBean");
}
public void setUserBean(UserBean userBean) {
session.put("userBean", userBean);
}
}
My jsp is:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>MeeTO</title>
</head>
<body>
<s:form action="loginAction" method="post" >
<s:label cssClass="login" value="Please fill in the form below in order to Register or Log in:" /> <br>
<s:label for="userBean.username" value="Username:"/>
<s:textfield name="userBean.username" /> <br>
<s:label for="userBean.password" value="Password:"/>
<s:password name="userBean.password" /> <br>
<s:submit value="LogIn" action="loginAction" /> <br>
<s:submit value="Register" action="registerAction" /> <br>
</s:form>
<s:fielderror/>
<s:actionerror/>
<s:actionmessage/>
</body>
</
My bean is:
package direstruts.model;
import cliente.replies.ReplyLogin;
import cliente.replies.ReplyObj;
import cliente.requests.lookup.GetAuthentication;
import cliente.requests.modify.SetNewUser;
import cliente.requests.modify.SetQuitUser;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Properties;
import servidorRMI.ExecuteCommands;
public class UserBean {
ExecuteCommands eC;
private static String ip_RMI = "127.0.0.1";
private static int serverRMI = 1099;
private static InputStream in;
private String username;
private String password;
private int idUser;
public UserBean() {
readProperties();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getIdUser() {
return this.idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public boolean getAuthentication() {
GetAuthentication gA = new GetAuthentication(getUsername(), getPassword(), 0);
ReplyLogin rL = null;
boolean cond = false;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rL = eC.getAuthentication(gA);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
setIdUser(rL.getIdUser()); // Faz set ao idUser para poder ser usado nos pedidos subsequentes
return rL.isHasRegister();
}
public boolean setNewUser() {
SetNewUser sNU = new SetNewUser(getUsername(), getPassword(), 0);
boolean cond = false;
ReplyObj rO = null;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rO = eC.setNewUser(sNU);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
return rO.getSuccess();
}
public boolean setQuitUser() {
SetQuitUser sQU = new SetQuitUser(idUser, 0);
boolean cond = false;
ReplyObj rO = null;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rO = eC.setQuitUser(sQU);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
return rO.getSuccess();
}
static public void readProperties() {
try {
Properties properties = new Properties();
in = UserBean.class.getClassLoader().getResourceAsStream("app.properties");
properties.load(in);
ip_RMI = properties.getProperty("serverRMI.address");
serverRMI = Integer.parseInt (properties.getProperty("serverRMI.port"));
} catch(IOException e) {
System.err.println("Erro a ler o ficheiro .properties!");
} finally {
if(in != null) {
try {
in.close();
} catch(IOException e) {System.out.println("Erro a fechar!"); }
}
}
}
}
Here is Tomcat Log:
19-Nov-2014 14:21:04.618 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Parameter [action:loginAction] is on the excludeParams list of patterns!
19-Nov-2014 14:21:05.086 SEVERE [http-apr-8080-exec-109] null.null Notificação para o Desenvolvedor (altere o paramêtro struts.devMode para false para desabilitar esta mensagem):
Unexpected Exception caught setting 'userBean.password' on 'class direstruts.action.LoginAction: Error setting expression 'userBean.password' with value ['YYY', ]
19-Nov-2014 14:21:05.101 SEVERE [http-apr-8080-exec-109] null.null Notificação para o Desenvolvedor (altere o paramêtro struts.devMode para false para desabilitar esta mensagem):
Unexpected Exception caught setting 'userBean.username' on 'class direstruts.action.LoginAction: Error setting expression 'userBean.username' with value ['XXX', ]
19-Nov-2014 14:21:05.210 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Caught an exception while evaluating expression 'userBean.username' against value stack
Caught an Ognl exception while getting property userBean - Class: ognl.OgnlRuntime
File: OgnlRuntime.java
Method: getMethodValue
Line: 1456 - ognl/OgnlRuntime.java:1456:-1
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:143)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:494)
at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:255)
at com.opensymphony.xwork2.ognl.OgnlValueStack.getValue(OgnlValueStack.java:358)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValue(OgnlValueStack.java:347)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValueWhenExpressionIsNotNull(OgnlValueStack.java:322)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:308)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:366)
at com.opensymphony.xwork2.util.TextParseUtil$1.evaluate(TextParseUtil.java:157)
at com.opensymphony.xwork2.util.OgnlTextParser.evaluate(OgnlTextParser.java:49)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:167)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:112)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:85)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:813)
at org.apache.struts2.components.UIBean.end(UIBean.java:544)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005ftextfield_005f0(loginPage_jsp.java:273)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fform_005f0(loginPage_jsp.java:182)
at org.apache.jsp.loginPage_jsp._jspService(loginPage_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: ognl.OgnlException: userBean [java.lang.NullPointerException]
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1456)
at ognl.ObjectPropertyAccessor.getPossibleProperty(ObjectPropertyAccessor.java:60)
at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:147)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.getProperty(ObjectAccessor.java:17)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:138)
... 68 more
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at direstruts.model.UserBean.readProperties(UserBean.java:128)
at direstruts.model.UserBean.<init>(UserBean.java:27)
at direstruts.action.LoginAction.getUserBean(LoginAction.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:891)
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1454)
... 73 more
19-Nov-2014 14:21:05.288 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn NOTE: Previous warning message was issued due to devMode set to true.
19-Nov-2014 14:21:05.429 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Caught an exception while evaluating expression 'userBean.password' against value stack
Caught an Ognl exception while getting property userBean - Class: ognl.OgnlRuntime
File: OgnlRuntime.java
Method: getMethodValue
Line: 1456 - ognl/OgnlRuntime.java:1456:-1
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:143)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:494)
at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:255)
at com.opensymphony.xwork2.ognl.OgnlValueStack.getValue(OgnlValueStack.java:358)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValue(OgnlValueStack.java:347)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValueWhenExpressionIsNotNull(OgnlValueStack.java:322)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:308)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:366)
at com.opensymphony.xwork2.util.TextParseUtil$1.evaluate(TextParseUtil.java:157)
at com.opensymphony.xwork2.util.OgnlTextParser.evaluate(OgnlTextParser.java:49)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:167)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:112)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:85)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:813)
at org.apache.struts2.components.UIBean.end(UIBean.java:544)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fpassword_005f0(loginPage_jsp.java:313)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fform_005f0(loginPage_jsp.java:191)
at org.apache.jsp.loginPage_jsp._jspService(loginPage_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: ognl.OgnlException: userBean [java.lang.NullPointerException]
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1456)
at ognl.ObjectPropertyAccessor.getPossibleProperty(ObjectPropertyAccessor.java:60)
at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:147)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.getProperty(ObjectAccessor.java:17)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:138)
... 68 more
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at direstruts.model.UserBean.readProperties(UserBean.java:128)
at direstruts.model.UserBean.<init>(UserBean.java:27)
at direstruts.action.LoginAction.getUserBean(LoginAction.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:891)
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1454)
... 73 more
19-Nov-2014 14:21:05.507 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn NOTE: Previous warning message was issued due to devMode set to true.
[EDIT]
I forgot to mention I have an action in which all other actions extend.
Here it is:
package direstruts.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class GenericAction extends ActionSupport implements SessionAware{
protected static final long serialVersionUID = 4L;
protected Map<String, Object> session;
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
}
To preserve action memory, the GenericAction implements SessionAware. Is that ok?
As reported in Parameters Interceptor documentation (and also explained in this answer), the exception:
.Error setting expression 'userBean.password' with value ['XXX', ]
means you are missin a Setter.
JavaBeans convention establishes that you should have a property, with a getter and a setter with the same name, and Struts2 works following those principles, performing introspection through reflection to outline your Action's objects.
What do you have in your code instead ?
public UserBean getUserBean() {
if(!session.containsKey("userBean"))
this.setUserBean(new UserBean());
return (UserBean) session.get("userBean");
}
public void setUserBean(UserBean userBean) {
session.put("userBean", userBean);
}
A little un-standard, uh !
The property private UserBean userBean; does not even exists, and getters and setters are doing strange session things (while they should not even have any business).
Change it to
private UserBean userBean;
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
And it will work.
Then IF needed, find another way to deal with the session and your object (like prepare() method, or even execute()).
I'm trying to upload some Image file to my database. When I run my code It produces the error java.lang.IndexOutOfBoundsException:. But the same code works well in another form.
My code is :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String uname = (String) request.getSession().getAttribute("uname");
//set content type
response.setContentType("text/html");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
if (! ServletFileUpload.isMultipartContent(request)) {
System.out.println("sorry. No file uploaded");
return;
}
// parse request
List<?> items = uploadHandler.parseRequest(request); //getting error
System.out.println(items.size());
// get uploaded file
FileItem file = (FileItem) items.get(0);
Connection con=prepareConnection();
con.setAutoCommit(false);
//Part photo=request.getPart("photo");
BufferedImage originalImage=ImageIO.read(file.getInputStream());
int type = originalImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(resizeImageJpg, "png", baos);
baos.flush();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
StringBuilder sb=new StringBuilder(1024);
sb.append("insert into ").append(uname).append("PROFILEPICTURE values(?,?)");
String query = sb.toString();
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
ps.setBinaryStream(2, is);
int i=ps.executeUpdate();
con.commit();
con.close();
if(i==1)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("/sp/profile");
if(dispatcher != null) {
dispatcher.forward(request, response);
}
}
else
{
out.println("Error ocuured");
}
out.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
console output :
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at skypark.AddProfilePict.doPost(AddProfilePict.java:79)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
And my form is:
<form id="form" method="post" action="AddProfilePict" enctype="multipart/form-data">
<input type="file" accept="image/*" style="width: 450px; border:0px; background:none; margin-top:5px; width:245px;" value="">
<input class="upld" type="submit" value="Upload">
</form>
Can anyone help me figure out what is causing the error?
items should indeed be empty. You should first check it's length and then try to fetch the items using
if(! items.isEmpty()) {
FileItem file = (FileItem) items.get(0);
}
or
if(items.size() > 0) {
FileItem file = (FileItem) items.get(0);
}