implementing static methods - need assistance - java

Working on a web application and implementing a class called Calculator that calculates certain things about your body to determine how to focus your diet.
I am implementing this caluclator but I am getting an error. Here is the error; and following it below is an example of the source code. If you could tell me where my problem is that would be incredibly appreciated.
The Error:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 83 in the jsp file: /updateProfile.jsp
Calculator cannot be resolved
80: a6 = "checked";
81: }
82:
83: out.println(Calculator.percentBodyFat("f","145","38","38","38","27","27","27",67.0,"6.5"));
84:
85: String theName = request.getParameter("name");
86: if(theName != null)
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:102)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:331)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:457)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
The Source code:
import java.io.BufferedReader;
package hygeia;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Calculator {
public static double percentBodyFat(String sex, String w, String h1,
String h2, String h3, String a1, String a2, String a3, double height, String wr)
{
//statements
}
public static double leanBodyMass(double weight, double percentBodyFat)
{
//statements
}
public static double protein(double leanBodyMass, int activLevel)
{
//statements
}
}
It is able to compile but I cannot get it to work with the jsp.
It seems like it should be very simple.

You have to include the Calculator class in your JSP page
<%#page import="Calculator"%> <%-- with the complete package of Calculator class--%>

This does not compile, package should be at the top.

You may fix the problem by importing your Calculator class.
<%#page import="Calculator"%>

Related

Spring MVC - File upload - Etat HTTP 500 error message

I am getting the error below when trying to upload file using spring mvc.
"Etat HTTP 500 - Request processing failed; nested exception is java.lang.NullPointerException".
It is the first time i am doing this.
I have an idea of the cause but i can't till now find the solution.
Thanks to anybody who can help.
FileModel.java
package com.model;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
FileUploadController.java
package com.controller;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.model.FileModel;
#Controller
public class FileUploadController {
public Logger logger = Logger.getLogger(FileUploadController.class);
public FileUploadController(){
System.out.println("FileUploadController");
}
#Autowired
private ServletContext context;
#RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
System.out.println("Multipart "+multipartFile);
String uploadPath = context.getRealPath("") + File.separator + "fichiers" + File.separator;
System.out.println(uploadPath);
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
model.addAttribute("fileName", fileName);
return "success";
}
}
}
FileUpload.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Upload</title>
</head>
<body>
<form:form action="fileUploadPage" method = "POST" modelAttribute = "fileUpload" enctype = "multipart/form-data">
Please select a file to upload : <input type = "file" name = "file" />
<input type = "submit" value = "upload" />
</form:form>
</body>
</html>
Console
GRAVE: Servlet.service() for servlet [spring] in context with path [/oracle_spring_user_test_project] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.controller.FileUploadController.fileUpload(FileUploadController.java:56)
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.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:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
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:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
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:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
You are using modelAttribute = "fileUpload" in your JSP form. So you should use #ModelAttribute spring annotation as method argument in order to indicate the argument that should be retrieved from the model. This is not necessary although it is the best practice.
The fileUpload model attribute should be populated with data from your form submitted to the fileUploadPage endpoint. So try the below snippet of code:
#RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(#ModelAttribute("fileUpload") FileModel fileUpload, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile file = fileUpload.getFile();
...
On Spring documentation you can read the official information regarding this annotation.

JSP - Only a type can be imported. Name.pacakge.class resolves to a package but the class is there

I'm receiving this error while trying to deploy a webapp via tomcat 7.
The jsp file name analysis.jsp and this is the error:
Apr 05, 2017 3:05:39 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [analyserServlet] in web application [/MWE] threw load() exception
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: [26] in the generated java file: [/usr/share/tomcat/work/Catalina/localhost/MWE/org/apache/jsp/analysis_jsp.java]
Only a type can be imported. mila.HMM.MorphMult2TaggerFormat resolves to a package
An error occurred at line: [27] in the generated java file: [/usr/share/tomcat/work/Catalina/localhost/MWE/org/apache/jsp/analysis_jsp.java]
Only a type can be imported. mila.HMM.HMM2Morph resolves to a package
An error occurred at line: [28] in the generated java file: [/usr/share/tomcat/work/Catalina/localhost/MWE/org/apache/jsp/analysis_jsp.java]
Only a type can be imported. mila.mw.PostProcessor1 resolves to a package
An error occurred at line: [29] in the generated java file: [/usr/share/tomcat/work/Catalina/localhost/MWE/org/apache/jsp/analysis_jsp.java]
Only a type can be imported. mila.mw.MWXMLTokenizer resolves to a package
An error occurred at line: 36 in the jsp file: /analysis.jsp
mila.mw.MWXMLTokenizer cannot be resolved to a type
33: String tokenizeAndAnalyze(String rawText) throws Exception {
34: StringWriter sw = new StringWriter();
35: try (InputStream ins = new ByteArrayInputStream(rawText.getBytes("UTF-8"))) {
36: new mila.mw.MWXMLTokenizer().tokenizeAndAnalyze(ins, new PrintWriter(sw));
37: }
38: StringWriter ppSW = new StringWriter();
39: try (InputStream ins = new ByteArrayInputStream(sw.toString().getBytes("UTF-8"))) {
An error occurred at line: 40 in the jsp file: /analysis.jsp
mila.mw.PostProcessor1 cannot be resolved to a type
37: }
38: StringWriter ppSW = new StringWriter();
39: try (InputStream ins = new ByteArrayInputStream(sw.toString().getBytes("UTF-8"))) {
40: new mila.mw.PostProcessor1().process(ins, new PrintWriter(ppSW));
41: }
42: return ppSW.toString();
43: }
An error occurred at line: 46 in the jsp file: /analysis.jsp
mila.HMM.MorphMult2TaggerFormat cannot be resolved to a type
43: }
44:
45: String runTagger(String xmlAnalyzed, String _tempDirectoryPath) throws Exception {
46: final String taggerFormat = new mila.HMM.MorphMult2TaggerFormat()
47: .myWEBMorp2Tagger(xmlAnalyzed, _tempDirectoryPath);
48: final String roydir = "/data/tagger/royTagger/";
49: final String probabilityDir = "/data/tagger/taggerLearningOutputFile/";
An error occurred at line: 60 in the jsp file: /analysis.jsp
mila.HMM.HMM2Morph cannot be resolved to a type
57:
58: final String xmlTaggedFilename = _tempDirectoryPath + "/tagged.xml";
59: PrintWriter pw = new PrintWriter(xmlTaggedFilename);
60: new mila.HMM.HMM2Morph().process(xmlAnalyzed, taggedFilename, pw);
61: return xmlTaggedFilename;
62: }
63:
Stacktrace:
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366)
at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:494)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:379)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:341)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:662)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:364)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
at org.apache.jasper.servlet.JspServlet.init(JspServlet.java:138)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1282)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1195)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1085)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5318)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5610)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:899)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:875)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:652)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:1260)
at org.apache.catalina.startup.HostConfig$DeployDirectory.run(HostConfig.java:2002)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Here is the import part from the jsp:
<%# page language = "java"
import = "java.lang.StringBuilder"
import = "java.io.StringWriter"
import = "java.io.PrintWriter"
import = "java.io.ByteArrayInputStream"
import = "java.io.IOException"
import = "java.io.File"
import = "java.io.BufferedReader"
import = "java.io.InputStreamReader"
import = "java.io.InputStream"
import = "java.nio.file.Files"
import = "java.nio.file.Paths"
import = "java.nio.file.StandardCopyOption"
import = "mila.HMM.MorphMult2TaggerFormat"
import = "mila.HMM.HMM2Morph"
import = "mila.mw.PostProcessor1"
import = "mila.mw.MWXMLTokenizer"
%>
Under the WEB-INF/lib folder I have a JAR named morphAnalyzer.jar which is basically the project and it contains all the classes needed including the ones that cause this error.
Here is a partial vim look into the JAR
mila/
mila/HMM/
mila/HMM/HMM2Morph.class
mila/HMM/MorphMult2TaggerFormat.class
...
mila/mw/MWXMLMorphAnalyzer.class
mila/mw/MWXMLTokenizer.class
mila/mw/PostProcessor1.class
...
As you can see the jar does include all the classes I need but for some reason the jsp file doesn't recognize them as classes.
P.S there is no other package with classes named the same (i.e all classes names are unique throughout the whole project)
What am I doing wrong? Please help.
Include morphAnalyzer.jar in class path of you application
classes are to be comma separated in the import attribute.
Like the below:
import ="mila.HMM.MorphMult2TaggerFormat, mila.HMM.HMM2Morph, mila.mw.PostProcessor1 ,mila.mw.MWXMLTokenizer"

How to return text_html type response in Jersey

I am developing a REST API using jersey jax-RS. This consumes data in JSON format and produces the output in html format.
When I set the MediaType for #Produces as TEXT_HTML and #Consumes as #APPLICATON_JSON and requested the 'GET' query on POSTMAN REST client, it gave me the following error:
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/try2] threw exception [org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/html, type=class java.util.ArrayList, genericType=java.util.List<org.sc.try2.model.Event>.] with root cause
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/html, type=class java.util.ArrayList, genericType=java.util.List<org.sc.try2.model.Event>.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:247)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:103)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:88)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1154)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:613)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:375)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:365)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:272)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:297)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:252)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1025)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:372)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
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.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
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:142)
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:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
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)
My codes :
StudentResource.java
package org.sc.try2.resources;
//import java.awt.Event;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
//import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.sc.try2.model.Student;
import org.sc.try2.service.StudentService;
#Path("/students")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_HTML)
public class StudentResource {
StudentService studentService = new StudentService();
//EventService es = new EventService();
#GET
#Path("/{studentEmail}/viewAll")
public List<Student> getStudents(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of StudentResource........ ");
return studentService.getAllStudents(emailID);
}
#GET
#Path("/{studentEmail}/viewMyProfile")
public Student getStudent(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of StudentResource........ ");
return studentService.getStudent(emailID);
}
#Path("/{studentEmail}/events")
public AllEventsResource getEvents(){
System.out.println("cmn in this method of StudentResource ");
return new AllEventsResource();
}
#Path("/{studentEmail}/myevents")
public EventResource getStudentEvents(){
return new EventResource();
}
#PUT
#Path("/{studentEmail}/updateProfile")
public String updateStudent(#PathParam("studentEmail") String emailID,Student student){
//student.setEmailID(emailID);
return studentService.updateStudent(emailID,student);
}
#DELETE
#Path("/{studentEmail}/deleteStudent/{delEmail}")
public String deleteStudent(#PathParam("studentEmail") String emailID,#PathParam("delEmail") String delEmail){
return studentService.removeStudent(emailID,delEmail);
}
}
EventsResource.java
package org.sc.try2.resources;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.sc.try2.model.Event;
import org.sc.try2.service.EventService;
#Path("/")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_HTML)
public class EventResource {
EventService es = new EventService();
#GET
public List<Event> getMyEvents(#PathParam("studentEmail") String emailID){
System.out.println("cmn in this method of EventsResource ");
return es.getAllEventsForStudent(emailID);
}
#POST
public String addEvent(#PathParam("studentEmail") String email,Event event){
System.out.println("here in res add evnt..");
return es.addEvent(email,event);
}
#PUT
#Path("/{eventId}")
public String updateEvent(#PathParam("studentEmail") String email,#PathParam("eventId") long id,Event event){
event.seteID(id);
return es.updateEvent(email,id,event);
}
#DELETE
#Path("/{eventId}")
public String deleteEvent(#PathParam("studentEmail") String email,#PathParam("eventId") long id){
return es.removeEvent(email,id);
}
}
On searching about this on the internet, I did not come across any useful solution except it was mentioned to download the genson jar and add it. After adding it as external jar in Eclipse (Java EE) MAVEN Project, it still gave the same exception which I guess is due to the fact that this jar is for json MediaType and is not used in the context of html content type.
Basically, I want to produce the content as HTML. How can I do it? I am entirely new to Jersey and the concept of REST API.

Java and JSP - java.lang.NoSuchMethodError?

How can I set property and get it on a jsp page?
my Hello.class,
package Foo;
public class Hello
{
private String message;
public String sayHello ()
{
return "Hello World!";
}
public String getMessage() {
return this.message;
}
public void setMessage(String x) {
this.message = x;
}
}
My index.jsp,
<html>
<head>
<title>Custom Class</title>
</head>
<body>
<%# page import="Foo.Hello" %>
<%
Hello hello = new Hello();
hello.setMessage("Hello There!");
out.print(hello.getMessage());
out.print(hello.sayHello());
%>
</body>
</html>
Error,
org.apache.jasper.JasperException: An exception occurred processing JSP page /custom-class/index.jsp at line 12
9: <%
10: Hello hello = new Hello();
11:
12: hello.setMessage("Hello There!");
13: out.print(hello.getMessage());
14: out.print(hello.sayHello());
15: %>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:574)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:461)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.servlet.ServletException: java.lang.NoSuchMethodError: Foo.Hello.setMessage(Ljava/lang/String;)V
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:908)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:837)
org.apache.jsp.custom_002dclass.index_jsp._jspService(index_jsp.java:122)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NoSuchMethodError: Foo.Hello.setMessage(Ljava/lang/String;)V
org.apache.jsp.custom_002dclass.index_jsp._jspService(index_jsp.java:103)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I'm new to Java and JSP. What have done incorrectly?
I don't find any problem in your code it is working fine i think you have to clean your project and redeploy it on your server and also clean and restart your server then it will surely work.
For people who encounter this problem in the future:
I just had the same problem and I removed tomcat server from "IntelliJ IDEA > Preferences > Application Servers" and I added it again. and it works fine now.

"Generated servlet error: <class> cannot be resolved to a type" in page

I was trying to implement JNA. I have used the following code for the testing purpose. Now I am getting an exception. Please correct me if I am using an incorrect method or if there are any problems in my testing code.
My reference tutorials were this and this
My class FileModifierLinux:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class FileModifierLinux {
CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);
public void Update(String pth) {
libc.chmod(pth, 0755);
}
}
interface CLibrary extends Library {
public int chmod(String path, int mode);
}
My page:
<%
try
{
FileModifierLinux flx=new FileModifierLinux();
String pathX = getServletContext().getRealPath("/testpage.jsp");
flx.Update(pathX);
out.println("No Exception");
}
catch(Exception exp)
{
out.println("exp :"+exp);
}
%>
Exception:
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: 15 in the jsp file: /index.jsp
Generated servlet error:
FileModifierLinux cannot be resolved to a type
An error occurred at line: 15 in the jsp file: /index.jsp
Generated servlet error:
FileModifierLinux cannot be resolved to a type
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
Did you import the class in the index.jsp? like:
<%#page import="com.somepackage.FileModifierLinux "%>

Categories

Resources