I have this uni project going on, and I'm stuck on this error and can't find the solution.
First there's the JSP file that loads a list
<%#page import="Controllers.RestClient"%>
<%#page import="java.util.List"%>
<%#page import="Model.Stationss"%>
<%#page import="javax.xml.bind.JAXBException"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<label for="Origin">Embark Station:</label>
<select name ="StartStation" id="stations">
<%
List<Stationss> listS = RestClient.getStations();
for (int i = 0; i < listS.size(); i++) {
out.print("<option value = " + i + ">" + listS.get(i).getName() + "</option>");
}
%>
</select><br>
</body>
</html>
There's also the ReST client access
package Controllers;
import java.util.List;
import Model.Stationss;
import java.util.ArrayList;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;
public class RestClient {
public static List<Stationss> getStations() {
System.out.print("test");
String link = "http://localhost:8080";
String path = "/Service/webresources/pkg.service.stations";
Client client = ClientBuilder.newBuilder().build();
WebTarget target = client.target(link).path(path);
Invocation.Builder invocation = target.request(MediaType.APPLICATION_XML);
System.out.print(link);
System.out.print(path);
Response response = invocation.get(Response.class);
System.out.print(response);
List<Stationss> list = response.readEntity(new GenericType<List<Stationss>>() {
});
System.out.print(list);
return list;
}
};
and after I have the model
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package Model;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Stationss {
private int id;
private String name;
private int zone;
Gate gates = new Gate(zone);
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getZone() {
return zone;
}
public void setZone(int zone) {
this.zone = zone;
}
public Gate getGates() {
return gates;
}
public void setGates(Gate gates) {
this.gates = gates;
}
public Stationss() {
}
public Stationss(int id, String name, int zone) {
this.id = id;
this.name = name;
this.zone = zone;
}
#Transient
public CheckTicket enter(String xml) {
return gates.enter(xml);
}
#Transient
public boolean exit(String xml) {
return gates.exit(xml);
}
}
and at last, the huge error screen
HTTP Status 500 – Internal Server Error
Type Exception Report
Message An exception occurred processing [/newjsp.jsp] at line [23]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: An exception occurred processing [/newjsp.jsp] at line [23]
20: <label for="Origin">Embark Station:</label>
21: <select name ="StartStation" id="stations">
22: <%
23: List<Stationss> listS = RestClient.getStations();
24: for (int i = 0; i < listS.size(); i++) {
25: out.print("<option value = " + i + ">" + listS.get(i).getName() + "</option>");
26: }
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:610)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:499)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
org.glassfish.jersey.jaxb.internal.AbstractCollectionJaxbProvider.readFrom(AbstractCollectionJaxbProvider.java:359)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:363)
org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:229)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:389)
org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:264)
org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
Controllers.RestClient.getStations(RestClient.java:36)
org.apache.jsp.newjsp_jsp._jspService(newjsp_jsp.java:143)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
- with linked exception:
[java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory]
javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:269)
javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getStoredJaxbContext(AbstractJaxbProvider.java:288)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getJAXBContext(AbstractJaxbProvider.java:273)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getUnmarshaller(AbstractJaxbProvider.java:189)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getUnmarshaller(AbstractJaxbProvider.java:164)
org.glassfish.jersey.jaxb.internal.AbstractCollectionJaxbProvider.readFrom(AbstractCollectionJaxbProvider.java:289)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:363)
org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:229)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:389)
org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:264)
org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
Controllers.RestClient.getStations(RestClient.java:36)
org.apache.jsp.newjsp_jsp._jspService(newjsp_jsp.java:143)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1444)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1252)
javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122)
javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155)
javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:267)
javax.xml.bind.ContextFinder.find(ContextFinder.java:412)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getStoredJaxbContext(AbstractJaxbProvider.java:288)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getJAXBContext(AbstractJaxbProvider.java:273)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getUnmarshaller(AbstractJaxbProvider.java:189)
org.glassfish.jersey.jaxb.internal.AbstractJaxbProvider.getUnmarshaller(AbstractJaxbProvider.java:164)
org.glassfish.jersey.jaxb.internal.AbstractCollectionJaxbProvider.readFrom(AbstractCollectionJaxbProvider.java:289)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:363)
org.glassfish.jersey.client.InboundJaxrsResponse$2.call(InboundJaxrsResponse.java:126)
org.glassfish.jersey.internal.Errors.process(Errors.java:316)
org.glassfish.jersey.internal.Errors.process(Errors.java:298)
org.glassfish.jersey.internal.Errors.process(Errors.java:229)
org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:389)
org.glassfish.jersey.client.InboundJaxrsResponse.runInScopeIfPossible(InboundJaxrsResponse.java:264)
org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:123)
Controllers.RestClient.getStations(RestClient.java:36)
org.apache.jsp.newjsp_jsp._jspService(newjsp_jsp.java:143)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:380)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:328)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:777)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/10.0.16
It's my first time learning java and I'm completely at loss on what I'm doing wrong.
I know the link the xml list is working fine.
You have missing dependencies on your classpath
See the stack trace
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
This answer might be helpful
Related
When using JSF with Tomcat on eclipse, a null pointer is always returned. This project is on IP tracking, and it is required to inject another bean into the application bean.
Bean to be injected: track
bean using the injection: increaseCount
The Track class
import java.util.HashMap;
import java.util.Map;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
#Named(value = "track")
#ApplicationScoped
public class Track {
private Map<String, Integer> map = new HashMap<>();
public void add(String ipAddress) {
map.put(ipAddress, map.containsKey(ipAddress) ? map.get(ipAddress) + 1 : 1);
}
public int getCount(String ipAddress) {
return map.containsKey(ipAddress) ? map.get(ipAddress) : 0;
}
public String getAllCount() {
return "Count summary is " + map;
}
}
The IncreaseCount Class
I tried following the solution indicated here 👇 but encountered the same problem.
httpss://stackoverflow.com/questions/16399974/nullpointerexception-while-trying-to-access-inject-bean-in-constructor
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
#Named(value = "increaseCount")
#SessionScoped
public class IncreaseCount implements java.io.Serializable {
#Inject
private Track track;
private String ipAddress;
#PostConstruct
public void init() {
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
.getRequest();
this.ipAddress = request.getRemoteAddr();
}
/*
* public IncreaseCount() { HttpServletRequest request = (HttpServletRequest)
* FacesContext.getCurrentInstance().getExternalContext() .getRequest();
* this.ipAddress = request.getRemoteAddr(); }
*/
public void click() {
track.add(ipAddress);
}
public String getIpAddress() {
return ipAddress;
}
public int getCount() {
return track.getCount(ipAddress);
}
}
The XHTML page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>IncreaseCount</title>
</h:head>
<h:body>
<h:form>
<h:commandButton action="#{increaseCount.click()}" value="Click Me" />
<br>The current count is #{increaseCount.getCount()} and your IP address is #{increaseCount.getIpAddress()}.</br>
</h:form>
</h:body>
</html>
The Exception
As you can see, invoking the getCount() method in the Track class produces an Exception.
Root Cause
java.lang.NullPointerException
chapter39.IncreaseCount.getCount(IncreaseCount.java:39)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:567)
javax.el.BeanELResolver.invoke(BeanELResolver.java:158)
javax.el.CompositeELResolver.invoke(CompositeELResolver.java:79)
org.apache.el.parser.AstValue.getValue(AstValue.java:159)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190)
com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(Unknown Source)
com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(Unknown Source)
com.sun.faces.facelets.compiler.TextInstruction.write(Unknown Source)
com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(Unknown Source)
com.sun.faces.facelets.compiler.UILeaf.encodeAll(Unknown Source)
javax.faces.render.Renderer.encodeChildren(Unknown Source)
javax.faces.component.UIComponentBase.encodeChildren(Unknown Source)
javax.faces.component.UIComponent.encodeAll(Unknown Source)
javax.faces.component.UIComponent.encodeAll(Unknown Source)
javax.faces.component.UIComponent.encodeAll(Unknown Source)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Unknown Source)
com.sun.faces.application.view.MultiViewHandler.renderView(Unknown Source)
com.sun.faces.lifecycle.RenderResponsePhase.execute(Unknown Source)
com.sun.faces.lifecycle.Phase.doPhase(Unknown Source)
com.sun.faces.lifecycle.LifecycleImpl.render(Unknown Source)
javax.faces.webapp.FacesServlet.service(Unknown Source)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
For JSF-based bean definitions:-
javax.faces.bean.SessionScoped //for bean scoping
javax.faces.bean.ManagedBean //for bean declaration
javax.faces.bean.ManagedProperty //for bean injection
#ManagedProperty(value="#{yourBeanName}")
private Track track;
For Better Understanding Please Go through this link
I'm trying to send variables between jsp and servlets, but I got this error that I still can't figure out why. It keeps sending HTTP Status 500 error.
it sending HTTP status 500 eror and java.lang.NullPointerException
but when i test java class in junit it ran fine.
this is jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="model.StudentDao"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Student</h1>
<table class="table">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach items="${requestScope.students}" var="student">
<tr>
<td><c:out value="${student.getStudentId()}"/></td>
<td><c:out value="${student.getStudentName()}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
and this my servlet:
package controller;
import...
#WebServlet("/StudentListServlet")
public class StudentListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DbConnect dbConnect = new DbConnect();
Connection connection = dbConnect.connect();
StudentDao studentDao = new StudentDao(connection);
ArrayList<Student> students = null;
try {
students = studentDao.findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
StudentDao :
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentDao {
private Connection connection;
public StudentDao(Connection connection) {
super();
this.connection = connection;
}
public ArrayList<Student> findAll() throws SQLException{
ArrayList<Student> students = new ArrayList<>();
Student student = null;
Statement statement = this.connection.createStatement();
String sqlText = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sqlText);
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getString("student_Id"));
student.setStudentName(resultSet.getString("student_Name"));
students.add(student);
}
resultSet.close();
statement.close();
return students;
}
}
DbConnect:
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnect {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
if(!this.connection.isClosed())
System.out.println("MySQL Connected");
else
System.out.println("MySQL Connect fail!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return this.connection;
}
public void close() throws SQLException {
this.connection.close();
}
}
Stack Trace :
SEVERE: Servlet.service() for servlet [controller.StudentListServlet] in context with path [/MySQLDemo] threw exception
java.lang.NullPointerException
at model.StudentDao.findAll(StudentDao.java:21)
at controller.StudentListServlet.doGet(StudentListServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Sorry for the long post.
anyone with an idea why this get error?
You are not loading the jdbc driver in your servelet
you can the jdbc driver as follows:
String driver = "com.mysql.jdbc.Driver";
// Load the JDBC driver
Class driver_class = Class.forName(driver);
This is how far i have come trying to respond with a List<> of Users to a Client . Every time i get Error 500 so i tried to respond with just a String and it worked so there is not a problem with the server/client communication. I searched the Internet and i found some examples that they returned Lists<> without error but i can't get mine to work.
User Class
package org.cs131111.user;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "user")
public class User implements Serializable{
private String studentID;
private String Fname;
private String Lname;
private int semester;
public User(){}
public User(String sID,String fname,String lname,int sem){
this.studentID=sID;
this.Fname=fname;
this.Lname=lname;
this.semester = sem;
}
public String getId() {
return studentID;
}
#XmlElement
public void setId(String id) {
this.studentID = id;
}
public String getName() {
return Fname+"_"+Lname;
}
#XmlElement
public void setFName(String name) {
this.Fname = name;
}
#XmlElement
public void setLName(String name) {
this.Lname = name;
}
public int getSemester() {
return semester;
}
#XmlElement
public void setSemester(int semester) {
this.semester = semester;
}
}
UserList class
package org.cs131111.user;
import org.cs131111.db.DatabaseConnection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UserList {
public List<User> list = null;
public List<User> getAllUsers(){
User stud = null;
DatabaseConnection newc = null;
newc = new DatabaseConnection();
list = new ArrayList<User>();
try {
newc.results=newc.query.executeQuery("select * from `students`");
while(newc.results.next()){
stud = new User(newc.results.getString("studentid"),newc.results.getString("fname"),newc.results.getString("lname"),newc.results.getInt("semester"));
list.add(stud);
System.out.println(stud.getId()+" "+stud.getName());
}
} catch (SQLException ex) {
Logger.getLogger(UserList.class.getName()).log(Level.SEVERE, null, ex);
}
newc.close();
return list;
}
}
UserService class
package org.cs131111.user;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/UserService")
public class UserService {
UserList userOb = new UserList();
#GET
#Path("/users")
#Produces(MediaType.APPLICATION_XML)
public List<User> getUsers(){
final List<User> users = userOb.getAllUsers();
return users;
}
}
The Client
<%#page import="java.util.List"%>
<%#page import="User.User"%>
<%#page import="java.io.IOException"%>
<%#page import="java.net.MalformedURLException"%>
<%#page import="java.io.InputStreamReader"%>
<%#page import="java.io.BufferedReader"%>
<%#page import="java.net.HttpURLConnection"%>
<%#page import="java.net.URL"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
try {
URL url = new URL("http://localhost:11118/EclassServer/webresources/UserService/users");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
List<User> u= (List<User>)conn.getContent();
out.println("Output from Server .... \n");
String test=u.get(1).getId();
out.println(test);
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
%>
</body>
</html>
Server's stack trace
Warning: StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.RuntimeException: Failed : HTTP error code : 500
at org.apache.jsp.clientGet_jsp._jspService(clientGet_jsp.java:80)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I can't post this as a comment so here it is. You can't really expect HttpUrlConnection.getContent to return a List of User instances. From the Javadoc
This method first determines the content type of the object by calling
the getContentType method. If this is the first time that the
application has seen that specific content type, a content handler for
that content type is created:
If the application has set up a content handler factory instance using
the setContentHandlerFactory method, the createContentHandler method
of that instance is called with the content type as an argument; the
result is a content handler for that content type. If no content
handler factory has yet been set up, or if the factory's
createContentHandler method returns null, then the application loads
the class named:
The usual way to get the content (when using HttpUrlConnection) is by using BufferedReader in combination with InputStreamReader something like
if(resCode==200){
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
stringBuilder = new StringBuilder();
String line=null;
while((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
}
But even now you will only get your User list as one large string (formatted as XML) and you should use an object mapper to convert the content/entity string to a List of User instances.
If, on the other hand, you used a Jersey client, it would be able to do the conversion automatically for you (it uses JAXB under the hood). Your Jersey client code might look something like (not tested)
WebTarget target = client.target(UriBuilder.fromUri("http://localhost:11118/EclassServer/webresources/UserService/users").build());
GenericType<List<User>> genType = new GenericType<List<User>>();
List<User> userList =(String) target.request().accept(MediaType.XML_APPLICATION).get(genType);
You don't have a correct root element. You've added the #XmlRootElement annotation to the User class, but it's not the root element as you're returning a list of users not a single user.
I recommend to specify a XSD and generate the JAXB classes rather than writing them yourself.
So I am trying to call a Java method in LoginCheckAction.java from LoginCheckAction.jsp. The method in the prior calls a method in LoginCheckBO.java which is an interface implemented by LoginCheckBOImpl. I am getting an error.
LoginCheckAction.jsp
<%# page import="action.LoginCheckAction" %>
<%# page import="bo.LoginCheckBO" %>
<%# page import="bo.impl.LoginCheckBOImpl" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginCheckAction ls = new LoginCheckAction();
// ls.printSomething(username);
ls.startBo(username);
%>
LoginCheckAction.java
package action;
import bo.LoginCheckBO;
import bo.impl.LoginCheckBOImpl;
public class LoginCheckAction{
LoginCheckBO bo = new LoginCheckBOImpl();
public LoginCheckAction(){
super();
}
public void printSomething(String username){
System.out.println(username);
}
public void startBo(String username){
bo.printSomethingBO(username);
}
}
LoginCheckBO.java
package bo;
public interface LoginCheckBO{
public void printSomethingBO(String username);
}
LoginCheckBOImpl.java
package bo.impl;
import bo.LoginCheckBO;
public class LoginCheckBOImpl implements LoginCheckBO{
public void printSomethingBO(String username){
System.out.println(username);
}
}
The error is in LoginCheckAction.jsp and I don't understand why I am getting that error. Can someone please explain? Here is the error:
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /jsp/LoginCheckAction.jsp at line 10
7:
8: LoginCheckAction ls = new LoginCheckAction();
9: // ls.printSomething(username);
10: ls.startBo(username);
11: %>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
root cause
java.lang.NullPointerException
action.LoginCheckAction.startBo(LoginCheckAction.java:26)
org.apache.jsp.jsp.LoginCheckAction_jsp._jspService(LoginCheckAction_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
I'm new using these tools so you'll probably find this very stupid.
I'm getting this error, when trying to access my webapp (where I'm supposed to show every user in my database "User" table.
HTTP ERROR 500
Problem accessing /maven-archetype-webapp/index. Reason:
Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
Caused by:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'contact' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.LabelTag.autogenerateFor(LabelTag.java:130)
at org.springframework.web.servlet.tags.form.LabelTag.resolveFor(LabelTag.java:120)
at org.springframework.web.servlet.tags.form.LabelTag.writeTagContent(LabelTag.java:90)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.WEB_002dINF.jsp.usuario_jsp._jspx_meth_form_label_0(org.apache.jsp.WEB_002dINF.jsp.usuario_jsp:299)
at org.apache.jsp.WEB_002dINF.jsp.usuario_jsp._jspx_meth_form_form_1(org.apache.jsp.WEB_002dINF.jsp.usuario_jsp:222)
at org.apache.jsp.WEB_002dINF.jsp.usuario_jsp._jspService(org.apache.jsp.WEB_002dINF.jsp.usuario_jsp:106)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:109)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:389)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:486)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:380)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:327)
at org.mortbay.jetty.servlet.Dispatcher.forward(Dispatcher.java:126)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:209)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:266)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1225)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1012)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:401)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
So I'm gonna send you my Controller, my JSP and my Service implementation.
UsuarioController.java
package org.maven.archetypes.Project.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.maven.archetypes.Project.form.Usuario;
import org.maven.archetypes.Project.service.UsuarioService;
#Controller
public class UsuarioController {
#Autowired
private UsuarioService usuarioService;
#RequestMapping("/index")
public String listUsers(Map<String, Object> map) {
map.put("usuario", new Usuario());
map.put("usuarioList", usuarioService.listUsuario());
return "usuario";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addUsuario(#ModelAttribute("user")
Usuario user, BindingResult result) {
usuarioService.addUsuario(user);
return "redirect:/index";
}
#RequestMapping("/delete/{email}")
public String deleteUsuario(#PathVariable("email")
String email) {
usuarioService.removeUsuario(email);
return "redirect:/index";
}
}
Usuario.jsp
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<!--
<h3>Usuarios</h3>
<c:if test="${!empty usuarioList}">
<table class="data">
<tr>
<th><spring:message code="label.firstname"/></th>
<th><spring:message code="label.email"/></th>
<th> </th>
</tr>
<c:forEach items="${usuarioList}" var="usuario">
<tr>
<td>${usuario.lastname}, ${usuario.firstname} </td>
<td>${usuario.email}</td>
<td>Eliminar</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
UsuarioServiceImpl.java (implementation of the interface UsuarioService.java)
#Service
public class UsuarioServiceImpl implements UsuarioService {
#Autowired
private UsuarioDAO UsuarioDAO;
#Transactional
public void addUsuario(Usuario user) {
UsuarioDAO.addUsuario(user);
}
#Transactional
public List<Usuario> listUsuario() {
return UsuarioDAO.listUsuario();
}
#Transactional
public void removeUsuario(String email) {
UsuarioDAO.removeUsuario(email);
}
}
I don't know if it's necessary to keep going with the DAOs ... the problem is that the error names a "Contact" and I don't even use that name in anything at all (I use "Usuario"). And yes, before you ask, I did replace some internet code which did have the word "contact" but I replaced them all to my code. So maybe this caused a mess but I'm really lost now. Hope you can help me. If there's something you don't understand don't hesitate to ask.
Thank you a lot!
You are only putting your object into a map. You need to put your objects in http request. Spring has model objects Model and ModelAndView that do this as shown below:-
<code>
#RequestMapping("/index")
public String listUsers(Model model) {
model.addAttribute("usuario", new Usuario());
model.addAttribute("usuarioList", usuarioService.listUsuario());
return "usuario";
}
</code>
OR
<code>
#RequestMapping("/index")
public ModelAndView listUsers() {
ModelAndView mav = new ModelAndView("usuario");
mav.addObject("usuario", new Usuario());
mav.addObject("usuarioList", usuarioService.listUsuario());
return mav;
}
</code>
What I can suggest you here is delete the target folder where the build is prepared and recreate the build and war and then run, if problem persists then let us know with the necessary files. Thanks