Null point always - java

It all ways passing null point after this line, System.out.println("Inside the filter.............." ); so can anyone tell me what's wrong in my code and logic
and home.jsp(index page) did not display. here I want to filter every url and proceed only valid login users requests. here my logic..
UserServlet.java
private void loginDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
User u = new User();
UserService us =new UserServiceImpl() ;
String Uname = request.getParameter("txtUname");
String Pwrd = request.getParameter("txtPwrd");
u.setUname(Uname);
u.setPwrd(Pwrd);
System.out.println(Uname+""+Pwrd);
try {
if(us.Userlogin(u.getUname(),u.getPwrd())){
String message = "Thank you, " + Uname +"..You are now logged into the system";
request.setAttribute("message", message);
//RequestDispatcher rd = getServletContext().getRequestDispatcher("/menu.jsp");
//rd.forward(request, response);
HttpSession session = request.getSession(true);
session.setAttribute("loggedUser", u);
String reqUrl = (String)session.getAttribute("requestedURL");
session.removeAttribute("requestedURL");
response.sendRedirect(reqUrl);
}else{
// direct to login}
FilterRequest.java
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
System.out.println("Inside the filter.............." );
HttpSession session = request.getSession(true);
User u = null;
if(session.getAttribute("loggedUser")!=null){
u = (User) session.getAttribute("loggedUser");
}
if (u!= null)
{
System.out.println("user does exits.." + u.getUname() );
chain.doFilter(req, resp);
}else{
String message = "Please Login!";
req.setAttribute("loginMsg", message);
//response.sendRedirect("login2.jsp");
}
}
web.xml
<filter>
<filter-name>FilterRequest</filter-name>
<filter-class>com.mobitel.bankdemo.web.FilterRequest</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterRequest</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
stack trace
`Jul 11, 2013 10:24:26 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre6/bin/client;C:/Program Files/Java/jre6/bin;C:/Program Files/Java/jre6/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Kaspersky Lab\Kaspersky Anti-Virus 6.0 for Windows Workstations MP4\;C:\Program Files\Java\jdk1.6.0_07/bin;C:\Program Files\MySQL\MySQL Server 5.2\bin;D:\common libs\com.mysql.jdbc_5.1.5.jar;;C:\Users\lcladmin\Documents\Softwares\java related\eclipse-jee-indigo-win32_2\eclipse;
Jul 11, 2013 10:24:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:BankDemoWeb' did not find a matching property.
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Jul 11, 2013 10:24:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 554 ms
Jul 11, 2013 10:24:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jul 11, 2013 10:24:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.41
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jul 11, 2013 10:24:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Jul 11, 2013 10:24:27 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 517 ms
Inside the filter..............
user does exits..`
Thank you..

You have a real simple problem: The user is not logged in ;)
To clarify things:
In you Filter you're checking if the user is logged in and in this case execute the chain with
chain.doFilter(req, resp);
That's fine so far.
But what happens if the user is not logged in? In this case you're not executing the chain and therefore no Servlet. The Servlet is always the last element in the chain.
So your users cannot log in as they never get to the Servlet that allows them to log in as you filter them out before.
You have to extend your filter to allow logins when no user is logged in. This can be done e.g. by changing the url-pattern of the Filter.

Related

When submitting the form on the jsp page is running forever

When submitting the form on the jsp page below (cadastroPaciente.jsp), the System is running forever without returning any error.
I've already tested the connection alone in a Test Class and the Servlet without the connection to the database (only building the object and returning it to the screen) worked. But when I put it in the Servlet to save in the database it is running forever and does not save in database.
The buildpath has:
jakarta.servlet.jsp.jstl-api-2.0.0.jar
mysql-connector-java-8.0.26.jar
On the Console there's just this:
set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Server
version name: Apache Tomcat/9.0.39 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Server
built: Oct 6 2020 14:11:46 UTC set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Server
version number: 9.0.39.0 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: OS Name:
Windows 10 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: OS
Version: 10.0 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO:
Architecture: amd64 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Java Home:
C:\Program Files\Java\jdk-16.0.1 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: JVM
Version: 16.0.1+9-24 set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: JVM
Vendor: Oracle Corporation set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO:
CATALINA_BASE:
D:\Java\workspace-ee.metadata.plugins\org.eclipse.wst.server.core\tmp0
set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO:
CATALINA_HOME: D:\Java\Server\apache-tomcat-9.0.39 set. 09,
2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument:
-Dcatalina.base=D:\Java\workspace-ee.metadata.plugins\org.eclipse.wst.server.core\tmp0
set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Command
line argument: -Dcatalina.home=D:\Java\Server\apache-tomcat-9.0.39
set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Command
line argument:
-Dwtp.deploy=D:\Java\workspace-ee.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
set. 09, 2021 12:25:24 AM
org.apache.catalina.startup.VersionLoggerListener log INFO: Command
line argument: --add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED set.
09, 2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener
log INFO: Command line argument:
--add-opens=java.base/java.io=ALL-UNNAMED set. 09, 2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log INFO: Command
line argument: --add-opens=java.base/java.util=ALL-UNNAMED set. 09,
2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument:
--add-opens=java.base/java.util.concurrent=ALL-UNNAMED set. 09, 2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument:
--add-opens=java.rmi/sun.rmi.transport=ALL-UNNAMED set. 09, 2021 12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252 set. 09, 2021
12:25:24 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -XX:+ShowCodeDetailsInExceptionMessages
set. 09, 2021 12:25:24 AM
org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO:
Loaded Apache Tomcat Native library [1.2.25] using APR version
[1.7.0]. set. 09, 2021 12:25:24 AM
org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: APR
capabilities: IPv6 [true], sendfile [true], accept filters [false],
random [true]. set. 09, 2021 12:25:24 AM
org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO:
APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
set. 09, 2021 12:25:24 AM
org.apache.catalina.core.AprLifecycleListener initializeSSL INFO:
OpenSSL successfully initialized [OpenSSL 1.1.1g 21 Apr 2020] set.
09, 2021 12:25:25 AM org.apache.coyote.AbstractProtocol init INFO:
Initializing ProtocolHandler ["http-nio-8080"] set. 09, 2021 12:25:25
AM org.apache.catalina.startup.Catalina load INFO: Server
initialization in [565] milliseconds set. 09, 2021 12:25:25 AM
org.apache.catalina.core.StandardService startInternal INFO: Starting
service [Catalina] set. 09, 2021 12:25:25 AM
org.apache.catalina.core.StandardEngine startInternal INFO: Starting
Servlet engine: [Apache Tomcat/9.0.39] set. 09, 2021 12:25:25 AM
org.apache.coyote.AbstractProtocol start INFO: Starting
ProtocolHandler ["http-nio-8080"] set. 09, 2021 12:25:25 AM
org.apache.catalina.startup.Catalina start INFO: Server startup in
[687] milliseconds
Can someone help me?
JSP Page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cadastro de Pacientes</title>
</head>
<body>
<form method="post" action="PacienteServlet">
<fieldset>
<legend>Dados do Paciente</legend>
<p>
<label for="cpf">CPF:</label>
<input type="text" size="14" id="cpf" name="cpf" />
</p>
<p>
<label for="nome">Nome:</label>
<input type="text" size="20" id="nome" name="nome" />
</p>
<p>
<label for="idade">Idade:</label>
<input type="number" size="3" id="idade" name="idade" />
</p>
<p>
<label for="telefone">Telefone:</label>
<input type="text" size="20" id="telefone" name="telefone" />
</p>
</fieldset>
<input type="submit" value="Enviar" />
</form>
</body>
</html>
JavaBeans:
package entity;
import java.io.Serializable;
public class Paciente implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String cpf;
private String nome;
private int idade;
private String telefone;
public Paciente(){}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
}
Servlet:
package servlet;
import entity.Paciente;
import persistence.PacienteDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
/**
* Servlet implementation class PacienteServlet
*/
#WebServlet("/PacienteServlet")
public class PacienteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PacienteServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect(response.encodeURL("cadastroPaciente.jsp"));
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Paciente paciente = new Paciente();
PacienteDao dao = new PacienteDao();
paciente.setCpf(request.getParameter("cpf"));
paciente.setNome(request.getParameter("nome"));
paciente.setIdade(Integer.parseInt(request.getParameter("idade")));
paciente.setTelefone(request.getParameter("telefone"));
dao.efetuarCadastro(paciente);
response.getWriter().append("Paciente cadastrado com sucesso!").append("<br />").append("<br />");
response.getWriter().append("CPF: "+paciente.getCpf()).append("<br />");
response.getWriter().append("Nome: "+paciente.getNome()).append("<br />");
response.getWriter().append("Idade: "+paciente.getIdade()).append("<br />");
response.getWriter().append("Telefone: "+paciente.getTelefone()).append("<br />").append("<br />");
response.getWriter().append(" Clique aqui para voltar para o formulário ");
} catch (SQLException e) {
request.setAttribute("error", e.toString());
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
} catch (Exception e) {
request.setAttribute("error", e.toString());
RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
} finally {
out.close();
}
}
}
DAO:
package persistence;
import java.sql.*;
import javax.swing.JOptionPane;
public class Dao {
Connection con;
PreparedStatement stmt;
ResultSet rs;
CallableStatement call;
public void abrirConexao() throws Exception{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/avaliacaojavaee", "root", "admin");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
public void fecharConexao() throws Exception{
con.close();
}
}
DAO Child:
package persistence;
import java.util.ArrayList;
import java.util.List;
import entity.Paciente;
public class PacienteDao extends Dao {
public void efetuarCadastro(Paciente p) throws Exception {
abrirConexao();
stmt = con.prepareStatement("insert into paciente values(?,?,?,?)");
stmt.setString(1, p.getCpf());
stmt.setString(2, p.getNome());
stmt.setInt(3, p.getIdade());
stmt.setString(4, p.getTelefone());
stmt.execute();
stmt.close();
fecharConexao();
}
public List<Paciente> listaPacientes() {
try {
abrirConexao();
stmt = con.prepareStatement("select * from paciente");
rs = stmt.executeQuery();
List<Paciente> lista = new ArrayList<Paciente>();
while (rs.next()) {
Paciente p = new Paciente();
p.setCpf(rs.getString("cpf"));
p.setNome(rs.getString("nome"));
p.setIdade(rs.getInt("idade"));
p.setTelefone(rs.getString("tel"));
lista.add(p);
}
fecharConexao();
return lista;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
public Paciente mostraPaciente(String cpf) throws Exception {
abrirConexao();
stmt = con.prepareStatement("select * from paciente where cpf = ? ");
rs = stmt.executeQuery();
Paciente p = null;
if (rs.next()) {
p = new Paciente();
p.setCpf(rs.getString("cpf"));
p.setNome(rs.getString("nome"));
p.setIdade(rs.getInt("idade"));
p.setTelefone(rs.getString("telefone"));
}
fecharConexao();
return p;
}
}
I got it! It needed to include the mysql-connector-java-8.0.26.jar in the library (in the lib folder), below the WEB-INF. But thank you for the
DanielBarbarian because he pointed out an important subject about the JOptionPane. Actually my application is not a swing application so the JOptionPane doesn't make sense. This was because I copied it from somewhere else that was probably a Swing application.

Can't pass array as body param: Invalid array

Here http request by curl
curl https://api.stripe.com/v1/checkout/sessions \
-u sk_test_4eC39HqLyjWDarjtT1zdp7dc: \
-H "Stripe-Version: 2019-03-14; checkout_sessions_beta=v1" \
-d success_url="https://example.com/success" \
-d cancel_url="https://example.com/cancel" \
-d payment_method_types[]=card \
-d line_items[][name]=T-shirt \
-d line_items[][description]="Comfortable cotton t-shirt" \
-d line_items[][amount]=1500 \
-d line_items[][currency]=usd \
-d line_items[][quantity]=2
It's success work.
Now I want to create them in java project by Retrofit 2.
In my java project I use Retrofit 2 to create http request.
import retrofit2.Response;
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Start request");
//Map<String, Object> bodyMap = getParams();
List<String> payment_method_types = new ArrayList<String>();
payment_method_types.add("card");
List<String> line_items = new ArrayList<String>();
JsonArray jsonArray = new JsonArray();
JsonObject lineItemsJsonObject = new JsonObject();
lineItemsJsonObject.addProperty("name", "T-shirt");
lineItemsJsonObject.addProperty("description", "Comfortable cotton t-shirt");
lineItemsJsonObject.addProperty("amount", 1500);
lineItemsJsonObject.addProperty("currency", "usd");
lineItemsJsonObject.addProperty("quantity", 1);
jsonArray.add(lineItemsJsonObject);
line_items.add(jsonArray.toString());
TransportService.checkoutSessions("https://example.com/success", "https://example.com/cancel", payment_method_types, line_items, new DefaultRestClientCallback<Void>() {
#Override
public void onSuccess(Response<Void> response) {
//super.onSuccess(response);
System.out.println("checkoutSessions: onSuccess: response = " + response);
}
#Override
public void onError(ErrorResponse errorResponse) {
}
});
}
public static void checkoutSessions(String success_url,
String cancel_url,
List<String> payment_method_types,
List<String> line_items, Callback<Void> callback) {
StripeRestClient stripeMonitorRestClient = RestClientFactory.createRestClient(StripeRestClient.class);
Map<String, String> headerMap = new HashMap<>();
headerMap.put("Accept", "application/json");
headerMap.put("Content-Type", "application/x-www-form-urlencoded");
headerMap.put("Stripe-Version", "2019-03-14");
headerMap.put("checkout_sessions_beta", "v1");
headerMap.put("Authorization", "Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc");
Call<Void> adMessagesList = stripeMonitorRestClient.checkoutSessions(headerMap, success_url, cancel_url, payment_method_types, line_items);
// asynchronously
adMessagesList.enqueue(callback);
}
import retrofit2.Call;
import retrofit2.http.*;
import java.util.List;
import java.util.Map;
public interface StripeRestClient {
#FormUrlEncoded
#POST("checkout/sessions")
Call<Void> checkoutSessions(#HeaderMap Map<String, String> headers,
#Field("success_url") String success_url,
#Field("cancel_url") String cancel_url,
#Field("payment_method_types[]") List<String> payment_method_types,
#Field("line_items") List<String> line_items);
}
But when start request I get error.
Here Retrofit 2 log:
> Task :run
Start request
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: --> POST https://api.stripe.com/v1/checkout/sessions http/1.1
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: Content-Type: application/x-www-form-urlencoded
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: Content-Length: 306
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: Authorization: Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: Accept: application/json
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: checkout_sessions_beta: v1
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: Stripe-Version: 2019-03-14
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO:
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: success_url=https%3A%2F%2Fexample.com%2Fsuccess&cancel_url=https%3A%2F%2Fexample.com%2Fcancel&payment_method_types%5B%5D=card&line_items=%5B%7B%22name%22%3A%22T-shirt%22%2C%22description%22%3A%22Comfortable%20cotton%20t-shirt%22%2C%22amount%22%3A1500%2C%22currency%22%3A%22usd%22%2C%22quantity%22%3A1%7D%5D
Apr 01, 2019 11:39:28 AM okhttp3.internal.platform.Platform log
INFO: --> END POST (306-byte body)
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: <-- 400 Bad Request https://api.stripe.com/v1/checkout/sessions (1282ms)
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Server: nginx
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Date: Mon, 01 Apr 2019 08:39:31 GMT
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Content-Type: application/json
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Content-Length: 116
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Connection: keep-alive
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: access-control-allow-credentials: true
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: access-control-allow-methods: GET, POST, HEAD, OPTIONS, DELETE
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: access-control-allow-origin: *
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: access-control-expose-headers: Request-Id, Stripe-Manage-Version, X-Stripe-External-Auth-Required, X-Stripe-Privileged-Session-Required
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: access-control-max-age: 300
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: cache-control: no-cache, no-store
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: request-id: req_sA1AfUFDGzgqDb
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: stripe-version: 2019-03-14
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: Strict-Transport-Security: max-age=31556926; includeSubDomains; preload
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO:
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: {
"error": {
"message": "Invalid array",
"param": "line_items",
"type": "invalid_request_error"
}
}
Apr 01, 2019 11:39:29 AM okhttp3.internal.platform.Platform log
INFO: <-- END HTTP (116-byte body)
checkoutSessions: onError: errorResponse = ErrorResponse{ code = 0, message = 'null'}
I also try this:
#FormUrlEncoded
#POST("checkout/sessions")
Call<Void> checkoutSessions(#HeaderMap Map<String, String> headers,
#Field("success_url") String success_url,
#Field("cancel_url") String cancel_url,
#Field("payment_method_types") List<String> payment_method_types,
#Field("line_items") List<String> line_items);
But I get error:
"error": {
"message": "Invalid array",
"param": "line_items",
"type": "invalid_request_error"
}
}

spring mvc with angular 2 not working on eclipse, data is not getting loaded

I am tying to test a simple spring mvc with angular 2 project running on eclipse.
The html page is getting displayed, but it is not loading any data from spring backend, any idea why this is happening?
console output:
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:AngularjsSpringRestExample' did not find a matching property.
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built: Sep 29 2017 13:46:41 UTC
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number: 8.0.47.0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name: Windows 7
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version: 6.1
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture: amd64
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home: C:\Program Files\Java\jdk1.8.0_111\jre
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version: 1.8.0_111-b14
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor: Oracle Corporation
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE: C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME: C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=C:\Users\dzhao\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=C:\Users\dzhao\Downloads\apache-tomcat-8.0.47\endorsed
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=Cp1252
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.8.0_111\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_131/bin/server;C:/Program Files/Java/jre1.8.0_131/bin;C:/Program Files/Java/jre1.8.0_131/lib/amd64;C:\Program Files (x86)\GnuWin32\bin\;C:\Program Files (x86)\RBTools\bin;C:\ProgramData\Oracle\Java\javapath;C:\Program Files\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\Common Files\Microsoft Shared\Microsoft Online Services;C:\Program Files (x86)\IBM\RationalSDLC\common;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\bin;C:\Program Files (x86)\IBM\gsk8\lib;C:\Program Files (x86)\IBM\gsk8\bin;C:\Program Files (x86)\IBM\RationalSDLC\ClearCase\RemoteClient\cteapis;C:\Program Files (x86)\Common Files\Check Point\UIFramework 3.0\Bin\;C:\Program Files (x86)\CheckPoint\Endpoint Security\Endpoint Common\bin;C:\Program Files (x86)\Sennheiser\SoftphoneSDK\;C:\Users\dzhao\Java_Softwares\eclipse;;.
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:22 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Oct 06, 2017 11:31:22 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1209 ms
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Oct 06, 2017 11:31:22 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.47
Oct 06, 2017 11:31:25 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Oct 06, 2017 11:31:25 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springrest'
Oct 06, 2017 11:31:25 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization started
Oct 06, 2017 11:31:25 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:25 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/springrest-servlet.xml]
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[GET],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.getCountryById(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[POST],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.addCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[PUT],produces=[application/json]}" onto public org.arpit.java2blog.bean.Country org.arpit.java2blog.controller.CountryController.updateCountry(org.arpit.java2blog.bean.Country)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/country/{id}],methods=[DELETE],produces=[application/json]}" onto public void org.arpit.java2blog.controller.CountryController.deleteCountry(int)
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping register
INFO: Mapped "{[/countries],methods=[GET],produces=[application/json]}" onto public java.util.List org.arpit.java2blog.controller.CountryController.getCountries()
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'springrest-servlet': startup date [Fri Oct 06 11:31:25 EDT 2017]; root of context hierarchy
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.handler.SimpleUrlHandlerMapping registerHandler
INFO: Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
Oct 06, 2017 11:31:27 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'springrest': initialization completed in 2531 ms
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 06, 2017 11:31:27 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 06, 2017 11:31:27 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5321 ms
This is 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.arpit.java2blog</groupId>
<artifactId>AngularjsSpringRestExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>AngularjsSpringRestExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
<build>
<finalName>AngularjsSpringRestExample</finalName>
</build>
</project>
servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
<mvc:default-servlet-handler/>
</beans>
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>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
controller class:
package org.arpit.java2blog.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
#RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
public Country addCountry(#RequestBody Country country) {
return countryService.addCountry(country);
}
#RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
public Country updateCountry(#RequestBody Country country) {
return countryService.updateCountry(country);
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public void deleteCountry(#PathVariable("id") int id) {
countryService.deleteCountry(id);
}
}
bean class:
package org.arpit.java2blog.bean;
public class Country{
int id;
String countryName;
long population;
public Country() {
super();
}
public Country(int i, String countryName,long population) {
super();
this.id = i;
this.countryName = countryName;
this.population=population;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
}
service class:
package org.arpit.java2blog.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.arpit.java2blog.bean.Country;
/*
* It is just a helper class which should be replaced by database implementation.
* It is not very well written class, it is just used for demonstration.
*/
public class CountryService {
static HashMap<Integer,Country> countryIdMap=getCountryIdMap();
public CountryService() {
super();
if(countryIdMap==null)
{
countryIdMap=new HashMap<Integer,Country>();
// Creating some objects of Country while initializing
Country indiaCountry=new Country(1, "India",10000);
Country chinaCountry=new Country(4, "China",20000);
Country nepalCountry=new Country(3, "Nepal",8000);
Country bhutanCountry=new Country(2, "Bhutan",7000);
countryIdMap.put(1,indiaCountry);
countryIdMap.put(4,chinaCountry);
countryIdMap.put(3,nepalCountry);
countryIdMap.put(2,bhutanCountry);
}
}
public List getAllCountries()
{
List countries = new ArrayList(countryIdMap.values());
return countries;
}
public Country getCountry(int id)
{
Country country= countryIdMap.get(id);
return country;
}
public Country addCountry(Country country)
{
country.setId(getMaxId()+1);
countryIdMap.put(country.getId(), country);
return country;
}
public Country updateCountry(Country country)
{
if(country.getId()<=0)
return null;
countryIdMap.put(country.getId(), country);
return country;
}
public void deleteCountry(int id)
{
countryIdMap.remove(id);
}
public static HashMap<Integer, Country> getCountryIdMap() {
return countryIdMap;
}
// Utility method to get max id
public static int getMaxId()
{ int max=0;
for (int id:countryIdMap.keySet()) {
if(max<=id)
max=id;
}
return max;
}
}
html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<title>AngularJS $http Rest example</title>
<script type="text/javascript">
var app = angular.module("CountryManagement", []);
//Controller Part
app.controller("CountryController", function($scope, $http) {
$scope.countries = [];
$scope.countryForm = {
id : -1,
countryName : "",
population : ""
};
//Now load the data from server
_refreshCountryData();
//HTTP POST/PUT methods for add/edit country
// with the help of id, we are going to find out whether it is put or post operation
$scope.submitCountry = function() {
var method = "";
var url = "";
if ($scope.countryForm.id == -1) {
//Id is absent in form data, it is create new country operation
method = "POST";
url = '/AngularjsSpringRestExample/countries';
} else {
//Id is present in form data, it is edit country operation
method = "PUT";
url = '/AngularjsSpringRestExample/countries';
}
$http({
method : method,
url : url,
data : angular.toJson($scope.countryForm),
headers : {
'Content-Type' : 'application/json'
}
}).then( _success, _error );
};
//HTTP DELETE- delete country by Id
$scope.deleteCountry = function(country) {
$http({
method : 'DELETE',
url : '/AngularjsSpringRestExample/country/' + country.id
}).then(_success, _error);
};
// In case of edit, populate form fields and assign form.id with country id
$scope.editCountry = function(country) {
$scope.countryForm.countryName = country.countryName;
$scope.countryForm.population = country.population;
$scope.countryForm.id = country.id;
};
/* Private Methods */
//HTTP GET- get all countries collection
function _refreshCountryData() {
$http({
method : 'GET',
url : 'http://localhost:8080/AngularjsSpringRestExample/countries'
}).then(function successCallback(response) {
$scope.countries = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
function _success(response) {
_refreshCountryData();
_clearFormData()
}
function _error(response) {
console.log(response.statusText);
}
//Clear the form
function _clearFormData() {
$scope.countryForm.id = -1;
$scope.countryForm.countryName = "";
$scope.countryForm.population = "";
};
});
</script>
<style>
.blue-button{
background: #25A6E1;
filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #1A87B9
}
.red-button{
background: #CD5C5C;
padding:3px 5px;
color:#fff;
font-family:'Helvetica Neue',sans-serif;
font-size:12px;
border-radius:2px;
-moz-border-radius:2px;
-webkit-border-radius:4px;
border:1px solid #CD5C5C
}
table {
font-family: "Helvetica Neue", Helvetica, sans-serif;
width: 50%;
}
caption {
text-align: left;
color: silver;
font-weight: bold;
text-transform: uppercase;
padding: 5px;
}
th {
background: SteelBlue;
color: white;
}
tbody tr:nth-child(even) {
background: WhiteSmoke;
}
tbody tr td:nth-child(2) {
text-align:center;
}
tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
text-align: center;
font-family: monospace;
}
tfoot {
background: SeaGreen;
color: white;
text-align: right;
}
tfoot tr th:last-child {
font-family: monospace;
}
td,th{
border: 1px solid gray;
width: 25%;
text-align: left;
padding: 5px 10px;
}
</style>
<head>
<body ng-app="CountryManagement" ng-controller="CountryController">
<h1>
AngularJS Restful web services example using $http
</h1>
<form ng-submit="submitCountry()">
<table>
<tr>
<th colspan="2">Add/Edit country</th>
</tr>
<tr>
<td>Country</td>
<td><input type="text" ng-model="countryForm.countryName" /></td>
</tr>
<tr>
<td>Population</td>
<td><input type="text" ng-model="countryForm.population" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
</tr>
</table>
</form>
<table>
<tr>
<th>CountryName</th>
<th>Population</th>
<th>Operations</th>
</tr>
<tr ng-repeat="country in countries">
<td> {{ country.countryName }}</td>
<td >{{ country.population }}</td>
<td><a ng-click="editCountry(country)" class="blue-button">Edit</a> | <a ng-click="deleteCountry(country)" class="red-button">Delete</a></td>
</tr>
</table>
</body>
</html>
If you want to return anything from a rest controller then you must use #ResponseBody annotation just before function declaration.
Like this in your case:
#RestController
public class CountryController {
#Autowired
private HttpServletRequest request;
CountryService countryService = new CountryService();
#RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public List getCountries() {
List listOfCountries = countryService.getAllCountries();
return listOfCountries;
}
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public Country getCountryById(#PathVariable int id) {
return countryService.getCountry(id);
}
.
.
.
}
And in case you are having a rest call which doesn't return anything then make sure to write #ResponseStatus(HttpStatus.NO_CONTENT)
Example:
#RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseStatus(HttpStatus.NO_CONTENT)
public void setCountryById(#PathVariable int id) {
countryService.setCountry(id);
}

Get Arraylist To Fill Out Option List(Model To Servlet To Jsp)

I have a model, servlet, and jsp page. I want to give the option list all of the options in the array list but for some reason I am getting a null pointer exception.
Can someone help me figure out where I am going wrong BELOW IS MY CODE:
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Management</title>
</head>
<body>
<form action="/customerManagment" method="post">
First Name:<br>
<input type="text" name="firstName"/><br>
Last Name:<br>
<input type="text" name="lastName"/><br>
Email:<br>
<input type="text" name="email"/><br>
Phone:<br>
<input type="text" name="phone"/><br>
Phone Type:<br>
Street Address:<br>
<input type="text" name="streetAddress"/><br>
Apartment Number:<br>
<input type="text" name="apartmentNumber"/><br>
City:<br>
<input type="text" name="city"/><br>
State:<br>
<select>
<option><%
ArrayList<edu.witc.Assignment03.model.States> states = (java.util.ArrayList)request.getAttribute("states");
for (edu.witc.Assignment03.model.States state : states) {
state.getStates();
}%></option>
</select><br>
<input type="submit" value="submit">
</form>
servlet
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
/*
* Not thread-safe. For illustration purpose only
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customerManagement"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
public void init() throws ServletException {
States state = new States();
states.add(state);
}
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private void editCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
} else if (uri.endsWith("/editCustomer")) {
sendEditCustomerForm(request, response);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setState(request.getParameter("states"));
customer.setZip(request.getParameter("zip"));
}
addCustomer(response, request);
}
}
Model
package edu.witc.Assignment03.model;
import java.util.ArrayList;
import java.util.List;
public class States {
private List<String> state = new ArrayList<>();{
state.add("Alabama");
state.add("Alaska");
state.add("Arizona");
state.add("Arkansas");
state.add("California");
state.add("Colorado");
state.add("Connecticut");
state.add("Delaware");
state.add("Florida");
state.add("Georgia");
state.add("Hawaii");
state.add("Idaho");
state.add("Illinois");
state.add("Indiana");
state.add("Iowa");
state.add("Kansas");
state.add("Kentucky");
state.add("Louisiana");
state.add("Maine");
state.add("Maryland");
state.add("Massachusetts");
state.add("Michigan");
state.add("Minnesota");
state.add("Mississippi");
state.add("Missouri");
state.add("Montana");
state.add("Nebraska");
state.add("Nevada");
state.add("New Hampshire");
state.add("New Jersey");
state.add("New Mexico");
state.add("New York");
state.add("North Carolina");
state.add("North Dakota");
state.add("Ohio");
state.add("Oklahoma");
state.add("Oregon");
state.add("Pennsylvania");
state.add("Rhode Island");
state.add("South Carolina");
state.add("South Dakota");
state.add("Tennessee");
state.add("Texas");
state.add("Utah");
state.add("Vermont");
state.add("Virginia");
state.add("Washington");
state.add("West Virginia");
state.add("Wisconsin");
state.add("Wyoming");
}
public List<String> getStates(){
return this.state;
}
}
Null Pointer Exception(after the customer button is clicked)
Mar 29, 2014 2:42:50 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\nodejs\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\RailsInstaller\Git\cmd;C:\RailsInstaller\Ruby1.9.3\bin;C:\Users\esder_000\AppData\Roaming\npm;.
Mar 29, 2014 2:42:50 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Justin_EJ_Assignment03_15400579' did not find a matching property.
Mar 29, 2014 2:42:50 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 29, 2014 2:42:50 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 29, 2014 2:42:50 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 756 ms
Mar 29, 2014 2:42:50 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 29, 2014 2:42:50 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
Mar 29, 2014 2:42:51 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 29, 2014 2:42:51 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 29, 2014 2:42:51 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 772 ms
Mar 29, 2014 2:42:55 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Justin_EJ_Assignment03_15400579] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at org.apache.jsp.customerManagement_jsp._jspService(customerManagement_jsp.java:94)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Look here:
State:<br>
<select>
<option><%
ArrayList<edu.witc.Assignment03.model.States> states = (java.util.ArrayList)request.getAttribute("states");
for (edu.witc.Assignment03.model.States state : states) {
state.getStates();
}%></option>
</select><br>
here request.getAttribute("states"); will be null, cause you have not done request.setAttribute("states", states); in your servlet. that cause the java.lang.NullPointerException..
Possible chances of java.lang.NullPointerException :
if you running directly the jsp page(ctrl+F11). Here states object will not available in request.
if states object is null, then in jsp you have foreach loop to iterate states this will cause exception
you have used two ArrayList to hold onlystates`:
In States class: private List<String> state = new ArrayList<>();
and in CustomerServlet servlet:
private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();
where one ArrayList is sufficient.
Final solution
change in CustomerServlet class from:
private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();
to
private edu.witc.Assignment03.model.States states = new States();
then add it to request so that states will available in jsp, in doGet() or anywhere that should adds states to request like:
request.setAttribute("states", states);
and in your jsp render option like:
State:<br>
<select>
<%
edu.witc.Assignment03.model.States states = request.getAttribute("states");
if(states!=null){
for (String state : states.getStates()) {
out.println("<option>"+state+"</option>");
}
}else{
System.out.print("states is null");
}
%>
</select><br>
Note:
Last but not least please avoid script-lets in jsp instead use jstl to render easily

Resin is showing my app as active but I am getting 404

as In topic my war is running without errors on Jetty / Tomcat but when I deploy it to the Resin 4
It shows as running / active in the deployed applications tab on the resin-admin panel. Nothing unusual in the logs as well.
But when I try to access myapp I am getting 404
Aug 14, 2013 9:20:25 AM com.caucho.server.cluster.Server start
INFO: resin.conf = null
Aug 14, 2013 9:20:25 AM com.caucho.server.cluster.Server start
INFO:
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Host[] active
Aug 14, 2013 9:20:25 AM com.caucho.server.port.Port bind
INFO: http listening to *:8080
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Server[id=,cluster=] active
Aug 14, 2013 9:20:25 AM com.caucho.server.resin.Resin start
INFO: Resin started in 2804ms
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toStopping
INFO: Host[] stopping
Aug 14, 2013 9:20:25 AM com.caucho.lifecycle.Lifecycle toActive
INFO: Host[] active
Aug 14, 2013 9:20:26 AM com.caucho.lifecycle.Lifecycle toActive
INFO: WebApp[http://localhost:8080/myapp] active
web 3.0 app initializer
import com.opensymphony.sitemesh.webapp.SiteMeshFilter;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.Filter;
#Order(1)
public class AppWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfiguration.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { new SiteMeshFilter() };
}

Categories

Resources