How to print 2d array created using java in HTML - java

I'm trying to print a 2d array on HTML. I'm trying to learn "Spring Boot Framework" and I'm stuck here. Is anybody know the solution? Posting my codes below, please help me.
MatrixApplication.java
package com.example.matrix;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MatrixApplication {
public static void main(String[] args) {
SpringApplication.run(MatrixApplication.class, args);
}
}
IndexController.java
package com.example.matrix.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.matrix.model.Matrix;
#Controller
public class IndexController {
#GetMapping("/")
public String index() {
return "index";
}
#PostMapping("/generate")
public String matrixRegistration(#ModelAttribute Matrix matrix, Model model) {
matrix.fillArrayList();
model.addAttribute("matrix", matrix);
return "redirect:/";
}
}
Matrix.java
package com.example.matrix.model;
import java.util.Arrays;
import java.util.Random;
public class Matrix {
public String xValue;
public String yValue;
public String matrixList[][];
public Matrix() {
fillArrayList();
}
public void setMatrixList(String[][] matrixList) {
this.matrixList = matrixList;
}
public void printMatrixList() {
for(int i=0; i < Integer.parseInt(this.xValue); i++){
for(int j=0; j < Integer.parseInt(this.yValue); j++){
System.out.print(this.matrixList[i][j] + " ");
}
System.out.println("");
}
}
#Override
public String toString() {
return "Matrix [matrixList=" + Arrays.toString(matrixList) + "]";
}
public void fillArrayList() {
int xValue = Integer.parseInt(this.xValue);
int yValue = Integer.parseInt(this.yValue);
this.matrixList = new String[xValue][yValue];
Random rand = new Random();
for(int i=0; i < xValue; i++){
for(int j=0; j < yValue; j++){
this.matrixList[i][j] = String.valueOf(rand.nextInt(100));
}
}
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="generate" method="post">
<label for="x">X</label>
<input type="text" name="xValue"/><br />
<label for="y">Y</label>
<input type="text" name="yValue"/> <br />
<button type="submit">Generate</button>
</form>
<table border="1" cellpadding="10">
<table border="1" cellpadding="10">
<tbody>
<tr th:each="matrix : ${matrix}">
<td th:text="${matrix.xValue}"></td>
<td th:text="${matrix.yValue}"></td>
</tr>
</table>
</table>
</body>
</html>
Part of the error I got. I cut it in half because it was too long.
java.lang.NumberFormatException: Cannot parse null string
at java.base/java.lang.Integer.parseInt(Integer.java:630) ~[na:na]
at java.base/java.lang.Integer.parseInt(Integer.java:786) ~[na:na]
at com.example.matrix.model.Matrix.fillArrayList(Matrix.java:38) ~[classes/:na]
at com.example.matrix.model.Matrix.<init>(Matrix.java:15) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.constructAttribute(ModelAttributeMethodProcessor.java:247) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:220) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:85) ~[spring-webmvc-5.3.23.jar:5.3.23]
2022-10-17 20:27:10.540 ERROR 39459 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.matrix.model.Matrix]: Constructor threw exception; nested exception is java.lang.NumberFormatException: Cannot parse null string] with root cause
java.lang.NumberFormatException: Cannot parse null string
at java.base/java.lang.Integer.parseInt(Integer.java:630) ~[na:na]
at java.base/java.lang.Integer.parseInt(Integer.java:786) ~[na:na]
at com.example.matrix.model.Matrix.fillArrayList(Matrix.java:38) ~[classes/:na]
at com.example.matrix.model.Matrix.<init>(Matrix.java:15) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.23.jar:5.3.23]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.constructAttribute(ModelAttributeMethodProcessor.java:247) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:220) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:85) ~[spring-webmvc-5.3.23.jar:5.3.23]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:147) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179) ~[spring-web-5.3.23.jar:5.3.23]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146) ~[spring-web-5.3.23.jar:5.3.23]
Thank you for your attention.
Good deeds.

Based on the assumption that you've filled in valid data in the form you'r submitting to the post. You will need standard setter (and maybe getter for view) methods for spring to be able to fill your model entity.
Also <tr th:each="matrix : ${matrix}"> is problematic as you'r defining the same variable name twice this way.
To prevent errors like these it's good practice to add bean validation with #NotNull on your y and x variables and modify controller as such
#PostMapping("/generate")
public String matrixRegistration(#Valid Matrix matrix, Model model, BindingResult bindingresult)
{
if (bindingResult.hasErrors())
{
//handle errors
}
matrix.fillArrayList();
model.addAttribute("matrix", matrix);
return "redirect:/";
}
see https://zetcode.com/spring/bindingresult/ for more details

I solved my own problem myself.
<table>
<tr th:each="values :${matrixArray}">
<th:block th:each="val :${values}">
<td th:text="*{val}"></td>
</th:block>
</tr>
</table>
Thans for suggestions. Its help a lot.

Related

Error 500 while trying to load a xml file in java

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

JSF #Inject mechanism returning NullPointerException

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

Unable to execute jdbc query on a servlet [duplicate]

This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 6 years ago.
I am trying to create an html page which takes some input and saves that data in oracle database using jdbc and servlet.
This is the HTML file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="HelloServlet" method="post">
<input type="text" placeholder="ID" name="id">
<input type="text" placeholder="NAME" name="name">
<input type="text" placeholder="SALARY" name="salary">
<input type="submit" value="submit">
</form>
</body>
</html>
Here is javafile contains the servlet
package com.gaurav;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
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 org.apache.jasper.tagplugins.jstl.core.Out;
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Set response content type
// Actual logic goes here.
//String name=request.getParameter("name");
//out.println(name);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url="jdbc:oracle:thin:#localhost:1521:xe";
String user="system";
String pass="inception";
try{
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");
int salary=Integer.parseInt(request.getParameter("salary"));
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,user,pass);
String query="INSERT INTO employee VALUES(?,?,?)";
PreparedStatement stm=con.prepareStatement(query);
stm.setInt(1, id);
stm.setString(2, name);
stm.setInt(3, salary);
stm.executeUpdate();
con.close();
}
catch(ClassNotFoundException e){
out.println("class not found ");
}
catch(SQLException e){
out.println("SQL Exception");
}
}
#Override
public void destroy() {
// resource release
super.destroy();
}
}
file hierarchy
whenever i tries to run the above program,it doesn't shows any error but when i write some data and press the submit button it thorws a ClassNotFound Exception.I don't have any idea whats happening.so someone help me.
Stack Trace:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.gaurav.HelloServlet.doPost(HelloServlet.java:50)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
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)
It looks like you are using Oracle 10g. From Oracle 9i onwards, support for oracle.jdbc.driver.OracleDriver is deprecated (documentation here). Could you try using oracle.jdbc.OracleDriver instead?
Check if you loaded the correct oracle jar driver on your project.

Spring MVC + Hibernate + JSP

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

why my spring validation annotations doesnt work

i have simple for where i put one string and im using annotations to valid the value
and it doesnt work
here is my class:
public class Destination
{
#NotNull
String address;
public Destination(){}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
here is my controller method
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String findDestination(#ModelAttribute("destination") #Valid Destination destination, BindingResult result, RedirectAttributes redirectAttrs) {
if(result.hasErrors()) {
return "redirect:/";
}
Location location = LocationManager.getLocation(destination.getAddress());
Weather weather = WeatherManager.getWeather(location);
redirectAttrs.addFlashAttribute("weather", weather);
redirectAttrs.addFlashAttribute("location", location);
return "redirect:/";
}
and here is my form in jsp file:
<form:form method="post" action="search" commandName="destination" class="form-horizontal">
<div class="control-group">
<div class="controls">
<form:input path="address" placeholder="Enter destination address"/>
<form:errors path="address" cssclass="error"></form:errors>
<input type="submit" value="Search" class="btn"/>
</form:form>
</div>
</div>
so the problem is that it doesnt valid my input
when i left it empty it still try to get addres for location object from null destination object and i get the exception
HTTP Status 500 - Request processing failed; nested exception is java.util.NoSuchElementException
exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.util.NoSuchElementException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.util.NoSuchElementException
java.util.ArrayList$Itr.next(ArrayList.java:794)
com.springapp.mvc.domain.LocationManager.getLocation(LocationManager.java:52)
com.springapp.mvc.controller.HomeController.findDestination(HomeController.java:51)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Empty html inputs when submitted are empty strings, this could be why your validation isn't working. You can try adding the #Size annotation, i.e. #Size(min=1)

Categories