Displaying panel using ajax in apache wicket - java

I am learning wicket framework and while working with ajax I tried one example in which I want to display a panel with selected radio button's company name. But while doing this I am getting some error. Here I mentioned all details from my coding:
Test.java
public class Test extends WebPage {
private static final List<String> companies = Arrays.asList(new String[] {"Google","Microsoft","Yahoo"});
private ArrayList<String> compSelected = new ArrayList<String>();
private Panel panel;
public Test(final PageParameters parameters) {
final RadioChoice<String> companyList =
new RadioChoice<String>("companyNames",new Model(compSelected),companies);
companyList.add(new AjaxFormChoiceComponentUpdatingBehavior() {
#Override
protected void onUpdate(AjaxRequestTarget target) {
if("Google".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Google");
}
else if("Microsoft".equals(companyList.getModelObject())){
panel = new Panel1("panel1","Microsoft");
}
else{
panel = new Panel1("panel1","Yahoo");
}
panel.setOutputMarkupId(true);
target.addComponent(panel);
}});
Form<?> form = new Form<Void>("form");
add(form);
form.add(companyList);
form.add(panel);
this.add(form);
}
}
Test.html
<form wicket:id="form">
<label><b>Company List:</b></label><br>
<span wicket:id="companyNames">radio button list will goes here</span><br>
<span wicket:id = "panel1" class="panel">panel goes here</span>
</form>
Panel1.java
#SuppressWarnings("serial")
public class Panel1 extends Panel{
public Panel1(String id,String cName) {
super(id);
add(new Label("msg", "selected company is:"+ cName));
}
}
Panel1.html
<body>
<wicket:panel>
<span wicket:id="msg">message goes here</span>
</wicket:panel>
</body>
WicketMessage: Can't instantiate page using constructor public demo.wicket.ajax.Test(org.apache.wicket.PageParameters) and argument Root cause:java.lang.IllegalArgumentException: argument child may not be null at org.apache.wicket.MarkupContainer.add(MarkupContainer.java:131) at demo.wicket.ajax.Test.(Test.java:46) at java.lang.reflect.Constructor.newInstance(Unknown Source) at org.apache.wicket.session.DefaultPageFactory.createPage(DefaultPageFactory.java:188) at org.apache.wicket.session.DefaultPageFactory.newPage(DefaultPageFactory.java:65) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.newPage(BookmarkablePageRequestTarget.java:299) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.getPage(BookmarkablePageRequestTarget.java:321) at org.apache.wicket.request.target.component.BookmarkablePageRequestTarget.processEvents(BookmarkablePageRequestTarget.java:234) at org.apache.wicket.request.AbstractRequestCycleProcessor.processEvents(AbstractRequestCycleProcessor.java:92) at org.apache.wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:1250) at org.apache.wicket.RequestCycle.step(RequestCycle.java:1329) at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1428) at org.apache.wicket.RequestCycle.request(RequestCycle.java:545) at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:468) at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:301) 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:503) 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:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) 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:314) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(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)
I am not sure what I did wrong here. can someone please help me to figure it out?

The problem is form.add(panel);. panel is null at that time. You initialize it in #onUpdate() but it is executed only after a click(?) on the radio buttons.
Solution:
Change panel type to WebMarkupContainer and initialize it in the page's constructor. Call panel.setOutputMarkupId(true) also in the constructor so the <span wicket:id="panel1"...> has an id in the rendered HTML and being able to be referenced later with JS to replace/update it. In #onUpdate() use something like panel = panel.replaceWith(new Panel1(panel.getId(), choice.getModelObject())); target.add(panel);

Related

Getting Null Pointer exception while saving ModelAttribute [Spring MVC] [duplicate]

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

Primefaces Export from Java causes IllegalStateException

I am currently trying to export content to a csv/xls file using primefaces exporter classes. I am generating a datatable component from javacode and pass it to the exporter class. It works fine, but I get very often a the following exception:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
I understand the exception, but not why it is thrown. The following message is called as an actionlistener by a primefaces command button:
public void export(MyBeanBeanClass bean, MyTable myTable, String format) {
FacesContext context = FacesContext.getCurrentInstance();
Exporter exporter = ExporterFactory.getExporterForType(format);
DataTable table = new DataTable();
String beanName = this.lookupManagedBeanName(bean);
List<Object[]> exportList = new ArrayList<Object[]>();
String outputFileName = "export";
boolean isPageOnly = false;
boolean isSelectionOnly = false;
String encodingType = "iso-8859-1";
MethodExpression preProcessor = null;
MethodExpression postProcessor = null;
// creating <p:datatable> component from java code -> see balusc's blog
// http://balusc.blogspot.de/2006/06/using-datatables.html#PopulateDynamicDatatable
// prepare datasource for export
for (MyRow row : myTable) {
Object[] rowContent = new Object[row.columnCount()];
for (int i = 0; i < rowContent.length; i++) {
rowContent[i] = row.get(i);
}
exportList.add(rowContent);
}
bean.setExportList(exportList);
// create primefaces datatable <p:datatable>
table.setValueExpression("value", createValueExpression("#{" + beanName + ".exportList}", List.class));
table.setVar("row");
// create columns and rows
for (int i = 0; i < myTable.getColumnCount(); i++) {
// Create <p:column>.
Column column = new Column();
table.getChildren().add(column);
// Create <h:outputText value="dynamicHeaders[i]"> for <f:facet name="header"> of column.
HtmlOutputText header = new HtmlOutputText();
header.setValue(this.getColumnTitle(this.getRenderedColumnNames().get(i)));
column.setHeader(header);
// Create <h:outputText value="#{dynamicItem[" + i + "]}"> for the body of column.
HtmlOutputText output = new HtmlOutputText();
output.setValueExpression("value", createValueExpression("#{row[" + i + "]}", String.class));
column.getChildren().add(output);
}
// export
try {
exporter.export(context, table, outputFileName, isPageOnly, isSelectionOnly, encodingType, preProcessor, postProcessor);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here's the xhtml of the command button:
<h:form>
<p:commandButton value="#{cc.attrs.exportXLS}" style="margin-top: 5px; width: 100%"
actionListener="#{cc.attrs.view.export(cc.attrs.bean, cc.attrs.view.tableOfData, "xls")}"
ajax="false" />
</h:form>
some information: bean is a simple viewscoped bean which stores the generated list (in function) for exporting it.
myTable contains the data which should be exported (will be transfered into an list of object array in function)
format contains "csv" or "xls".
here is the stacktrace:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:678)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:837)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.createResponseWriter(FaceletViewHandlingStrategy.java:1197)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:408)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
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.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:612)
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:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
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)
anybody got an idea why I get this excpetion?
kind regards
Alex
I solved the problem by adding the following line after the export call:
context.responseComplete();

How to fetch data from Servlet using canvas js

I am working with canvas.js charts.I need to populate date from servlet into the chart.I have tried a process but data is not coming to the Chart.I am posting the code i have tried..
In the Jsp end
<html>
<head>
<title>Chart JS Library Demo</title>
<style>
</style>
</head>
<body>
<canvas id="canvas" height="500" width="500"></canvas>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="Chart.min.js"></script>
<script type="text/javascript" src="ts-chart-script.js"></script>
</body>
</html>
The js i am using for fetching the servlet
var TUTORIAL_SAVVY ={
/*Makes the AJAX calll (synchronous) to load a Student Data*/
loadStudentData : function(){
var formattedstudentListArray =[];
$.ajax({
async: false,
url: "StudentJsonDataServlet",
dataType:"json",
success: function(studentJsonData) {
console.log(studentJsonData);
$.each(studentJsonData,function(index,aStudent){
formattedstudentListArray.push([aStudent.mathematicsMark,aStudent.computerMark,aStudent.historyMark,aStudent.litratureMark,aStudent.geographyMark]);
});
}
});
return formattedstudentListArray;
},
/*Crate the custom Object with the data*/
createChartData : function(jsonData){
console.log(jsonData);
return {
labels : ["Mathematics", "Computers", "History","Literature", "Geography"],
datasets : [
{
fillColor : "rgba(255,0,0,0.3)",
strokeColor : "rgba(0,255,0,1)",
pointColor : "rgba(0,0,255,1)",
pointStrokeColor : "rgba(0,0,255,1)",
/*As Ajax response data is a multidimensional array, we have 'student' data in 0th position*/
data : jsonData[0]
}
]
};
},
/*Renders the Chart on a canvas and returns the reference to chart*/
renderStudenrRadarChart:function(radarChartData){
var context2D = document.getElementById("canvas").getContext("2d"),
myRadar = new Chart(context2D).
Radar(radarChartData,{
scaleShowLabels : false,
pointLabelFontSize : 10
});
return myRadar;
},
/*Initalization Student render chart*/
initRadarChart : function(){
var studentData = TUTORIAL_SAVVY.loadStudentData();
chartData = TUTORIAL_SAVVY.createChartData(studentData);
radarChartObj = TUTORIAL_SAVVY.renderStudenrRadarChart(chartData);
}
};
$(document).ready(function(){
TUTORIAL_SAVVY.initRadarChart();
});
Servlet i am using
package com.servlet;
#WebServlet("/StudentJsonDataServlet")
public class StudentJsonDataServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentJsonDataServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<Student> listOfStudent = getStudentData();
Gson gson = new Gson();
String jsonString = gson.toJson(listOfStudent);
response.setContentType("application/json");
response.getWriter().write(jsonString);
}
private List<Student> getStudentData() {
List<Student> listOfStudent = new ArrayList<Student>();
Student s1 = new Student();
s1.setName("Sandeep");
s1.setComputerMark(75);
s1.setMathematicsMark(26);
s1.setGeographyMark(91);
s1.setHistoryMark(55);
s1.setLitratureMark(36);
listOfStudent.add(s1);
return listOfStudent;
}
}
Student Class
public class Student {
private String name;
private int ComputerMark;
private int MathematicsMark;
private int GeographyMark;
private int HistoryMark;
private int LitratureMark;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getComputerMark() {
return ComputerMark;
}
public void setComputerMark(int computerMark) {
ComputerMark = computerMark;
}
public int getMathematicsMark() {
return MathematicsMark;
}
public void setMathematicsMark(int mathematicsMark) {
MathematicsMark = mathematicsMark;
}
public int getGeographyMark() {
return GeographyMark;
}
public void setGeographyMark(int geographyMark) {
GeographyMark = geographyMark;
}
public int getHistoryMark() {
return HistoryMark;
}
public void setHistoryMark(int historyMark) {
HistoryMark = historyMark;
}
public int getLitratureMark() {
return LitratureMark;
}
public void setLitratureMark(int litratureMark) {
LitratureMark = litratureMark;
}
}
This codes i am using as my chart and servlet interaction but getting error in the log that ,it is not finding the Gson.But i have included the jar .I am using gson-2.2.4.jar for it.
SEVERE: Servlet.service() for servlet [com.servlet.StudentJsonDataServlet] in context with path [/jQueryMenu] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.google.gson.Gson
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at com.servlet.StudentJsonDataServlet.doGet(StudentJsonDataServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
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 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: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:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
Put the Gson jar where Tomcat will find it and load it.
From the Apache Tomcat documentation:
A class loader is created for each web application that is deployed in
a single Tomcat instance. All unpacked classes and resources in the
/WEB-INF/classes directory of your web application, plus classes and
resources in JAR files under the /WEB-INF/lib directory of your web
application, are made visible to this web application, but not to
other ones.

JPAContainer add component in table?

I'm looking for a how to add a component in my table. My table is using a JPAContainer as datasource. I'm trying using addContainerProperty but doesn't work and returns an exception.
I'm trying this
private final CustomJPAContainer<Curriculum> datasource = new CustomJPAContainer<Curriculum>(Curriculum.class);
Button btnView = new Button();
Table tabela = new Table("",datasource);
tabela.addContainerProperty("View", Button.class, null);
//exception
java.lang.UnsupportedOperationException
at com.vaadin.addon.jpacontainer.JPAContainer.addContainerProperty(JPAContainer.java:666)
at com.vaadin.ui.AbstractSelect.addContainerProperty(AbstractSelect.java:806)
at com.vaadin.ui.Table.addContainerProperty(Table.java:4260)
at br.ind.ibg.views.VisualizarCurriculum.buildLayout(VisualizarCurriculum.java:58)
at br.ind.ibg.views.VisualizarCurriculum.<init>(VisualizarCurriculum.java:36)
at br.ind.ibg.utils.MenuSistema$1.menuSelected(MenuSistema.java:60)
at com.vaadin.ui.MenuBar.changeVariables(MenuBar.java:186)
at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:396)
at com.vaadin.server.communication.ServerRpcHandler.handleBurst(ServerRpcHandler.java:221)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:111)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:91)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:37)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1382)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:238)
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 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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
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:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Any idea ?
/** edited */
I solved the problem using setGeneratedColumn()
Here how I did.
public class ButtonColumnGenerator implements Table.ColumnGenerator{
private static final long serialVersionUID = 1L;
#Override
public Object generateCell(Table source, Object itemId, Object columnId) {
Property prop = source.getItem(itemId).getItemProperty(columnId);
Button btnView = new Button();
btnView.setData(itemId);
btnView.setDescription("Curriculum: " + itemId);
btnView.setIcon(new ThemeResource("../icons/eye.png"));
btnView.setWidth("20px");
btnView.setHeight("20px");
btnView.setStyleName(Reindeer.BUTTON_LINK);
return btnView;
}
}
/*** my app */
Button btnView = new Button();
Table tabela = new Table("",datasource);
tabela.setVisibleColumns(new Object[]{"idCurriculum", "nome", "cpf"});
tabela.setColumnHeaders(new String[] {"#", "Nome", "Cpf"});
tabela.addGeneratedColumn("", new ButtonColumnGenerator());
now works !
Adding UI components to the data source of a select component (Table, Tree, TreeTable, ComboBox, ...) is the wrong approach for your problem. The container data source of a Table component only contains the data model of the table and not the components that will display this data.
So, instead of adding properties to the JPAContainer (which is disallowed for this container as it handles its properties internally), you set a custom com.vaadin.ui.TableFieldFactory to your table with Table.setTableFieldFactory(TableFieldFactory fieldFactory).

Java calling one servlet from two sources

I'm making a Java web-application with an user profile.
I have a profileServlet which is responsible for rendering two pages: profile.jsp and editProfile.jsp
The first source, from which profileServlet is being called, is a menu link on top of the page, and look like this:
Profile
The second source is a "Edit" button in the profile.jsp:
<form name="editProfile" method="GET" action="profileServlet?param=editProf"><input type="submit" value="Edit"></form>
Now in profileServlet, depending on the param value I want to make redirect either to profile.jsp or editProfile.jsp. Here is the code:
if(request.getParameter("param").equals("profile")) {
response.sendRedirect("profile.jsp");
} else if (request.getParameter("param").equals("editProf")) {
response.sendRedirect("editProfile.jsp");
}
But I keep getting java.lang.NullPointerException.
Could you help please?
Stacktrace:
24.04.2014 11:44:30 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [profilePage.profileServlet] in context with path [/LinkedIn] threw exception
java.lang.NullPointerException
at profilePage.profileServlet.doGet(profileServlet.java:126)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
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.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:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
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:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Your request parameter param is probably null, you can either do it like below, or have proper null checking in place before using your variables
if ("profile".equals(request.getParameter("param")) {
response.sendRedirect("profile.jsp");
} else if ("editProf".equals(request.getParameter("param")) {
response.sendRedirect("editProfile.jsp");
}
Additionally, ensure that the code is place in their respective doGet/doPost handlers, or have one handler for both.
Example:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
handleGetAndPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
handleGetAndPost(request, response);
}
private void handleGetAndPost(HttpServletRequest request, HttpServletResponse response) {
if ("profile".equals(request.getParameter("param")) {
response.sendRedirect("profile.jsp");
} else if ("editProf".equals(request.getParameter("param")) {
response.sendRedirect("editProfile.jsp");
}
}
you should use a post request when submitting a form, and have two different handler methods.
GET returns the empty form, and POST processes the submitted form.
Better add null checks. Looks like you are not able to get param
if (request.getParameter("param") != null && request.getParameter("param").equals("profile")) {
response.sendRedirect("profile.jsp");
} else if (request.getParameter("param") != null && request.getParameter("param").equals("editProf")) {
response.sendRedirect("editProfile.jsp");
}

Categories