I am trying to run a webapp called TestServer2 in the Tomcat 7 running Ubuntu 14.04 but it gave failed as FAIL - Application at context path /TestServer2-0.0.1-SNAPSHOT could not be started. I followed an example online here and I tested it on my local Tomcat server instance running with Eclipse and it works just fine but when I deployed it into the server Ubuntu 14.04 with Tomcat 7 it gave me that error. Below are the codes I used:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>TestServer2</display-name>
<context-param>
<param-name>resteasy.resources</param-name>
<param-value>com.heyho.rest.JSONService</param-value>
</context-param>
<listener>
<listener-class>
org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>resteasy-servlet</servlet-name>
<servlet-class>
org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>resteasy-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>TestServer2</groupId>
<artifactId>TestServer2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<repositories>
<repository>
<id>JBoss repository</id>
<url>https://repository.jboss.org/nexus/content/groups/public-jboss/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxrs</artifactId>
<version>2.2.1.GA</version>
</dependency>
<!-- <dependency> <groupId>org.jboss.resteasy</groupId> <artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version> </dependency> -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson-provider</artifactId>
<version>2.2.1.GA</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
JSONService.java
package com.heyho.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/service")
public class JSONService {
#POST
#Path("/post")
#Consumes("application/json")
public Response createProductInJSON(UserInput input) {
String result = "User input submitted : " + input;
return Response.status(201).entity(result).build();
}
}
UserInput.java
package com.heyho.rest;
public class UserInput {
int counter;
String attribute;
String publicKey;
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getPublicKey() {
return publicKey;
}
public void setPublicKey(String publicKey) {
this.publicKey = publicKey;
}
#Override
public String toString() {
return "User Input = counter " + counter + " attribute = " + attribute + " public key = " + publicKey ;
}
}
ClientPost.java
package com.heyho.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import com.google.gson.Gson;
public class ClientPost {
public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
try {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, (certificate, authType) -> true).build();
CloseableHttpClient client = HttpClients.custom()
.setSslcontext(sslContext)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpPost postRequest = new HttpPost(
"http://somewebsite.de:50064/TestServer2/service/post");
Gson gson = new Gson();
Map<String,Object> test = new HashMap<String,Object>();
test.put("counter", 1000);
test.put("attribute", "user attribute");
test.put("publicKey", "user public key");
String json = gson.toJson(test);
StringEntity input = new StringEntity(json);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = client.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Is there something wrong with my code? Also how do I debug the Tomcat 7 running on the server so that it could give me some logs or error?
UPDATE
I have found the error in log something like this:
SEVERE: Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
java.lang.UnsupportedClassVersionError: com/heyho/rest/JSONService : Unsupported major.minor version 52.0 (unable to load class com.heyho.rest.JSONService)
I'm not sure what is the problem here. I have declared JSONService on my web.xml but it still gives me error
"Unsupported major.minor version 52.0" means that the class com.heyho.rest.JSONService has been compiled for a newer version of Java as you try to run it with. Upgrade the JVM to 1.8 and it should work. Alternatively, you can make sure to compile the class for the version of the JVM.
Related
Actually , I'm struggling with this issue from two days . I am not able to output in console and I do not know what the problem is?
I am hitting this URL on my local machine, http://localhost:8080/Last/webapi/employee/p2
Below is the Screenshot of my issue :
https://i.stack.imgur.com/vubwA.png
Code is as below.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.webservices</groupId>
<artifactId>Last</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Last</name>
<build>
<finalName>Last</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- Thanks for using https://jar-download.com -->
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-binding</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle -->
<!-- https://mvnrepository.com/artifact/com.sun.jersey/jersey-core -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.glassfish.jersey.media/jersey-media-jaxb -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.31</version>
</dependency>
</dependencies>
<properties>
<jersey.version>2.31</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.webservices.Last</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>
EmployeesList.java
package com.webservices.Last;
import java.util.ArrayList;
import java.util.List;
import javax.print.attribute.standard.Media;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path(value = "employee")
public class EmployeesList {
List<StaffInformation> st = null;
public EmployeesList() {
st = new ArrayList<>();
st.add(new StaffInformation("Kerem", "Kağan","123"));
st.add(new StaffInformation("Java", "Oracle","321"));
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/p2")
public Response listXML()
{
List<StaffInformation> list = new ArrayList<StaffInformation>();
list.add(new StaffInformation("kerem", "ss", "123"));
GenericEntity<List<StaffInformation>> entity = new GenericEntity<List<StaffInformation>>(list) {};
Response response = Response.ok(entity).build();
return response;
}
}
StaffInformation.java
package com.webservices.Last;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class StaffInformation {
#XmlElement
private String name;
#XmlElement
private String surname;
#XmlElement
private String tcNo;
public String getTcNo() {
return tcNo;
}
public void setTcNo(String tcNo) {
this.tcNo = tcNo;
}
public StaffInformation() {
super();
}
public StaffInformation(String name, String surname, String tcNo) {
super();
this.name = name;
this.surname = surname;
this.tcNo = tcNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
you are hitting http://localhost:8080/Last/webapi/employee/p2 url
try with
http://localhost:8080/webapi/employee/p2
or
add '/last' in your web.xml, url pattern field
The path you are requesting is not found by the server, hence you are seeing the 500 internal server error.
You have mentioned as #Path(value = "employee") for your main path whereas that should be
#Path(value = "/employee")
and changing that to "/employee" should work fine. I tried your code in my local machine and it just worked fine after changing to "/employee".
This means the URL starts with /employee (after Application path) and remaining methods to follow this URL. Forex in your case http://localhost:8080/Last/webapi/employee/p2
After add second servlet I am getting Exception:
java.lang.abstractmethoderror: receiver class com.sun.jersey.core.spi.factory.responseimpl does not define or inherit an implementation of the resolved method abstract getstatusinfo()ljavax/ws/rs/core/response$statustype; of abstract class javax.ws.rs.core.response.
I figure out that the problem is in dependencies in my pom.xml but I don't have any idea where.
Anyway, I gonna forward you some codes.
First, my servlets
package vs.api.serlvets;
import com.sun.jersey.api.NotFoundException;
import vs.api.database.UserDBO;
import vs.api.repository.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
#WebServlet(name = "LogInServlet", urlPatterns = { "/LogInUser"})
public class LogInServlet extends HttpServlet
{
main.java.vs.api.database.DatabaseManager databaseManager;
UserDBO userDBO;
HttpSession session;
public void init() throws ServletException
{
databaseManager = new main.java.vs.api.database.DatabaseManager();
try
{
userDBO = new UserDBO(databaseManager.dataSource.getConnection());
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
session = request.getSession();
session.removeAttribute("errorLogIn");
PrintWriter out = response.getWriter();
String email = "";
String password = "";
User user = new User();
try
{
email = request.getParameter("inputEmail");
password = request.getParameter("inputPassword");
user = userDBO.get(email, password);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NotFoundException e)
{
session.setAttribute("errorLogIn", e.getMessage());
response.sendRedirect(request.getHeader("Referer"));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("User: " + user.getName());
}
#Override
public void destroy()
{
userDBO.exit();
}
}
package vs.api.serlvets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.sun.jersey.api.NotFoundException;
import main.java.vs.api.database.DatabaseManager;
import vs.api.database.IDBO;
import vs.api.database.UserDBO;
import vs.api.repository.User;
#WebServlet(description = "RegistrationServlet", urlPatterns = { "/RegisterUser"})
public class RegisterUserServlet extends HttpServlet
{
DatabaseManager databaseManager;
IDBO userDBO;
public RegisterUserServlet()
{
super();
}
public void init() throws ServletException
{
databaseManager = new DatabaseManager();
try
{
userDBO = new UserDBO(databaseManager.dataSource.getConnection());
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
User user = new User();
user.setName(request.getParameter("inputFirstName"));
user.setSurname(request.getParameter("inputLastName"));
user.setEmail(request.getParameter("inputEmail"));
user.setPassword(request.getParameter("inputPassword"));
try
{
userDBO.add(user);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
HttpSession session = request.getSession();
session.setAttribute("errorUserExist", e.getMessage());
response.sendRedirect(request.getHeader("Referer"));
}
catch(AbstractMethodError e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void destroy()
{
userDBO.exit();
}
}
And second my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.drimtim</groupId>
<artifactId>virtualspace</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>virtualspace Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>6.0.53</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
</dependencies>
<build>
<finalName>virtualspace</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
In end, my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Registration User Servlet</servlet-name>
<servlet-class>vs.api.serlvets.RegisterUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration User Servlet</servlet-name>
<url-pattern>/RegisterUser</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogIn User Servlet</servlet-name>
<servlet-class>vs.api.serlvets.RegisterUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogIn User Servlet</servlet-name>
<url-pattern>/LogInUser</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/AppExceptionHandler</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/AppExceptionHandler</location>
</error-page>
</web-app>
This is my all pom.xml Could you say me where is problem ?
Thanks in advance.
First you need to remove unnecessary dependencies for that you can use maven.
Execute below commands by opening terminal in your project root directory.
mvn clean
mvn dependency:analyze
It will show you the unused and required dependencies.
Also you can try by changing your pom. i think you only need following dependencies.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
Trying to produce JSON code from database entries using rest but I am getting a HTTP 500 error code
#Path("product")
public class ProductResource {
#GET
#Produces({ MediaType.APPLICATION_XML })
public List<Product> getProductInformation() {
return ProductDAO.instance.getProductInformation();
}
}
^^ This is the class I have mapped to the resource I am trying to access
It then accesses the ProductDAO class which gets the info from the database and adds it to a HashMap (This part seems to work fine)
public enum ProductDAO {
instance;
private Map<Integer, Product> productMap = new HashMap<Integer, Product>();
private ProductDAO() {
loadFromDb();
}
public Map<Integer, Product> loadFromDb() {
productMap.clear();
try {
Connection conn = Utils.getConnection();
PreparedStatement psmt = conn.prepareStatement("SELECT * FROM products");
ResultSet rs = psmt.executeQuery();
while (rs.next()) {
Product p = new Product(rs.getInt("id"), rs.getString("description"), rs.getInt("CategoryId"),
rs.getDouble("price"), rs.getInt("QuantitySold"), rs.getString("image"));
productMap.put(productMap.size() + 1, p);
System.out.println(productMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return productMap;
}
public List<Product> getProductInformation() {
List<Product> product = new ArrayList<Product>();
product.addAll(productMap.values());
return product;
}
I have 4 test entries in the database currently.
When I add a system.out.println() for the HashMap I get the following output to the console:
Database connection established
{1=myApp.Product#20c427e5}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb}
{1=myApp.Product#20c427e5, 2=myApp.Product#610e026a, 3=myApp.Product#2e0456eb, 4=myApp.Product#5241c547}`
My pom.xml is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.framesinmind</groupId>
<artifactId>FramesIM</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>FramesIM</name>
<build>
<finalName>FramesIM</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version>${jersey.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<jersey.version>2.16</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
Web.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>myApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The Java classes are all part of the 'myApp' package
When trying to access the url 'http://localhost:8080/FramesIM/rest/product' I get the HTTP 500 error. Any ideas?
The internal server error is because you need to code the Product class with the annotations and cannot directly pass the list as response. Please follow the code below.
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
#XmlRootElement(name = "product")
#XmlAccessorType (XmlAccessType.FIELD)
public class Product {
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "products")
#XmlAccessorType (XmlAccessType.FIELD)
public class Products
{
#XmlElement(name="product")
private List<Product> products;
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
}
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("product")
public class ProductResource {
#GET
#Produces(MediaType.APPLICATION_XML)
public Products getProductInformation() {
List<Product> product = ProductDAO.instance.getProductInformation();
Products products = new Products();
products.setProducts(product);
return products;
}
}
The response below is the sample output
<products>
<product>
<id>12</id>
</product>
</products>
I made two classes:
Main class with embedded Tomcat(8.5.20)
ServerEndpoint of Websocket
I run the main class on IntelliJ IDEA
and run this JavaScript: new WebSocket('ws://localhost:8080/ws')
in the console of Google Chrome.
I expected the response code is 200, but actually it is 404.
How can I fix this?
Main class:
package webapp;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import javax.servlet.ServletException;
import java.io.File;
public class Main {
private static final String STATIC_DIR = "src/main/static/";
public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
File staticDir = new File(STATIC_DIR);
tomcat.addWebapp("/", staticDir.getAbsolutePath());
tomcat.start();
tomcat.getServer().await();
}
}
ServerEndpoint:
package webapp.websocket;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/ws")
public class SampleWebSocket {
#OnOpen
public void onOpen(Session session) {
System.out.println("open");
}
#OnClose
public void onClose(Session session) {
System.out.println("close");
}
#OnMessage
public String onMessage(String text) {
System.out.println("message:" + text);
return "Server:" + text;
}
}
Thank you.
I found a solution.
This question is dupricated.
I read Got 404 error on tomcat 7.0.47 websocket and editted my pom.xml.
Following is the whole of my pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>websocket-sample</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>websocket-sample</name>
<properties>
<java.version>1.8</java.version>
<maven.compiler.target>${java.version}</maven.compiler.target>
<maven.compiler.source>${java.version}</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
</project>
Just add the following dependency to pom.xml
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-websocket</artifactId>
<version>8.5.20</version>
</dependency>
What solved the issue for me was switching from the javax.websocket-api dependency to the Tomcat-specific tomcat-embed-websocket dependency instead and switching all my imports (ServerEndpoint, onMessage, etc.) to the Tomcat-specific jakarta.websocket.* packages instead of the javax.websocket.x packages.
Here is the endpoint code that worked for me -- notice that there are no javax.websocket imports and instead I have jakarta.websocket imports:
import java.io.IOException;
import jakarta.websocket.EncodeException;
import jakarta.websocket.OnMessage;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
#ServerEndpoint("/echo")
public class EchoEndpoint {
// Implementation.
#OnMessage
public void onMessage(
Session session,
String message)
throws
IOException,
EncodeException {
// Send the same message back.
session.getBasicRemote().sendText(message);
}
}
And my pom.xml file dependencies:
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-core -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>10.1.0-M8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-websocket -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-websocket</artifactId>
<version>10.1.0-M8</version>
</dependency>
As far as I can tell, the pom.xml should not contain the javax.websocket dependency at all, to ensure there are no collisions/clashes between that one and the Tomcat-specific tomcat-embed-websocket dependency.
This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
While learning spring i was trying to run code examples of Spring in Action
but it is showing me the below mentioned error in tomcat logs:
11-Aug-2016 12:15:57.561 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/RestTester-0.0.1-SNAPSHOT/] in DispatcherServlet with name 'dispatcher'
I am trying to configure spring by the help of java based configuration only.
Code for the same is mentioned below:
TestProjectInitializer.java
package test.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class TestProjectInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{RootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class<?>[]{WebConfig.class};
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[]{"/"};
}
}
WebConfig.java
package test.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("test.webconf")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
RootConfig.java
package test.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"test"}, excludeFilters={#Filter(type=FilterType.ANNOTATION,value=EnableWebMvc.class)})
public class RootConfig {
}
HomeController.java
package test.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
/*#RequestMapping("/")*/
public class HomeController
{
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
return "home";
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>RestTester</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Directory Structure
Please help me understanding what i am doing wrong.
The name of base package on Webmvc was wrong and should be test.controller.