lundi 30 décembre 2019

Error while trying to build a CRUD application using Struts2.5 (server-side) and Emberjs(client-side)

Error number 1 POST request: order creation : null0.0 java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null

JSONInterceptor isn't working.

Error number 2 PUT request: freemarker.log._JULLoggerFactory$JULLogger error SEVERE: Error executing FreeMarker template FreeMarker template error: The following has evaluated to null or missing: ==> rootloc.URI [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 15]


Tip: It's the step after the last dot that caused this error, not those before it.

Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??


FTL stack trace ("~" means nesting-related):

- Failed at: ${rootloc.URI} [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 13]

Java stack trace (for programmers):

freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:467) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:389) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:358) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:330) at freemarker.core.Environment.visit(Environment.java:336) at freemarker.core.Environment.visit(Environment.java:336) at freemarker.core.Environment.process(Environment.java:309) at freemarker.template.Template.process(Template.java:384) at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:118) at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:76) at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:912) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:589) at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79) at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.filters.CorsFilter.handleSimpleCORS(CorsFilter.java:259) at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:163) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

Error number 3 Delete Request : "Error: Ember Data Request DELETE http://localhost:8080/crud_ember_struts2/products/8 returned a 403 Payload (text/plain)

at ErrorClass.EmberError [as constructor] (http://localhost:4200/assets/vendor.js:41679:23)
at ErrorClass.AdapterError (http://localhost:4200/assets/vendor.js:69485:17)
at new ErrorClass (http://localhost:4200/assets/vendor.js:69503:24)
at Class.handleResponse (http://localhost:4200/assets/vendor.js:79151:18)
at ajaxError (http://localhost:4200/assets/vendor.js:79440:25)
at ajaxErrorHandler (http://localhost:4200/assets/vendor.js:79486:12)
at Class.hash.error (http://localhost:4200/assets/vendor.js:79231:23)
at fire (http://localhost:4200/assets/vendor.js:3632:31)
at Object.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3762:7)
at done (http://localhost:4200/assets/vendor.js:9876:14)"

Attached my codes below:

web.xml

    ```<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>crud_ember_struts2</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://localhost:4200</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>1800</param-value>
  </init-param>
   </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <url-pattern>/**</url-pattern>
    </filter-mapping>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>```

struts.xml

``` <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="controller"/>
    <constant name="struts.rest.content.restrictToGET" value="false"/>

   <package name="default" namespace="/" extends="rest-default,json-default">
        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
            <interceptor-stack name="myStack">
            <interceptor-ref name="json">
                <param name="contentType">application/json</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myStack" />
        <global-allowed-methods>index,show,create,update,edit,editnew,deleteConfirm,destroy</global-allowed-methods>
        <action name="products/*" class="controller.ProductsController">
            <result name="index" type="json"></result>
        </action>
   </package>
</struts>```

ProductsController.java:

```package controller;
import java.util.List;
//import javax.servlet.http.HttpServletRequest;
import dao.Productdao;
import model.product;
//import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import com.opensymphony.xwork2.ModelDriven;
//import org.json.simple.*;
/*import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.convention.annotation.Result;


@Results({
    @Result(name="index", type="json", params = {"actionName" , "product"})
})*/
public class ProductsController implements ModelDriven<Object>{
    //private static final Logger log = LogManager.getLogger(ProductsController.class);
    product p=new product();
    Productdao dao=new Productdao();
    private List<product> productlist=dao.getAllProduct();
    private int id;
    private String name;
    private double price;
    //private HttpServletRequest request;
    //private JSONObject Object;

    public HttpHeaders show()
    {
        System.out.println("Showing");
        p=dao.getProduct(id);
        return new DefaultHttpHeaders("show");
    }

    public HttpHeaders index() {
        System.out.println("i am inside index");
        return new DefaultHttpHeaders("index").disableCaching();
    }

    public String edit()
    {
        System.out.println("came for editing");
        return "edit";
    }

    public String editNew()
    {
        System.out.println("here in edit new");
        return "editNew";
    }

    public String create()
    {
        System.out.println("order creation : "+name+price);
        boolean result=dao.createProduct(name,price);
        if(result)
        {
            System.out.println("product created successfully");
            return "success";
        }
        else
        {
            System.out.println("product Not created");
            return "increated";
        }
    }

    public String update()
    {
        System.out.println("inside update");
        p.setId(id);
        p.setName(name);
        p.setPrice(price);
        boolean result=dao.updateProduct(p);
        if(result)
        {
            System.out.println("product updated successfully");
            return "success";
        }
        else
        {
            System.out.println("product not updated");
            return "inupdated";
        }
    }
    public String destroy()
    {
        System.out.println("inside destroy");
        boolean result=dao.deleteProduct(id);
        if(result) {
            System.out.println("deleted successfully");
            return "success";
        }
        else
        {
            System.out.println("Not deleted");
            return "indeleted";
        }
    }

    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 double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    /*public JSONObject getObject() {
        return Object;
    }

    public void setObject(JSONObject object) {
        Object = object;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }*/

    @Override
    public Object getModel() {
        System.out.println("getting model");
        return productlist;
    }

}
```

product.java:

```package model;

public class product {
    private int id;
    private String name;
    private double price;
    public product() {

    }

    public product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    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 double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        System.out.println("to stringing");
        return "{\nid: " + id + ",\nname: " + name + ",\nprice: " + price + "\n}";
    }
}
```

productdao.java :

```package dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.product;
import util.DBConnect;

public class Productdao {
    public List<product> getAllProduct()
    {
        List<product> list=new ArrayList<>();
        String query="select * from demotable";
        try {
            ResultSet rs=DBConnect.getConnection().createStatement().executeQuery(query);
            while(rs.next())
            {
                list.add(new product(rs.getInt("id"),rs.getString("name"),rs.getDouble("price")));
            }
            rs.close();
            return list;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public boolean createProduct(String name,double price)
    {
        String query="insert into demotable(name,price) values(?,?)";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            System.out.println(name);
            System.out.println(price);
            pst.setString(1,name);
            pst.setDouble(2,price);
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("i am caught help me");
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateProduct(product p)
    {
        String query="update table demotable set name=? price=? where id=?";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            pst.setInt(1,p.getId());
            pst.setString(2,p.getName());
            pst.setDouble(3,p.getPrice());
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteProduct(int id)
    {
        String query="delete from demotable where id=?";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            pst.setInt(1,id);
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public product getProduct(int id)
    {
        product p=new product();
        String query="select * from demotable where id="+id;
        try {
            ResultSet rs=DBConnect.getConnection().createStatement().executeQuery(query);
            if(rs.next())
            {
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));
                p.setPrice(rs.getDouble("price"));
            }
            rs.close();
            return p;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}```

app.js :

```import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host : "http://localhost:8080",
  namespace : "crud_ember_struts2",
  defaultSerializer: '-json-api'
});```

product.js

```import DS from 'ember-data';

export default DS.Model.extend({
  name : DS.attr('string'),
  price : DS.attr('number')
});```

routes:

create:

```import Route from '@ember/routing/route';

export default Route.extend({
  model()
  {
    //return this.store.createRecord('product');
  },
  actions:{
    create(record)
    {
      let post = this.store.createRecord('product',{
        name: record.nameInput,
        price:record.priceInput
      });
      post.save();
      post.rollbackAttributes();
    }
  }
});```

edit:

```import Route from '@ember/routing/route';

export default Route.extend({
  model(param)
  {
    idFixed: param.product_id;
    return this.store.findRecord('product',param.product_id);
  },
  actions:{
    edit(record)
    {
      console.log(record.idFixed);
      console.log(record.nameInput);
      console.log(record.priceInput);
      this.store.findRecord('product',record.idFixed).then(function(product){
        product.set('name',record.nameInput);
        product.set('price',record.priceInput);
        product.save();
      })
    }
  }
});```

delete:

```import Route from '@ember/routing/route';

export default Route.extend({
  model(param)
  {
    return this.store.findRecord('product',param.product_id,{backgroundReload: false}).then(function(product){
      product.destroyRecord();
    });
  }
});```

read:

```import Route from '@ember/routing/route';

export default Route.extend({
  model()
  {
    return this.store.findAll("product");
  }
});```

router.js

```import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('products');
  this.route('create');
  this.route('edit',{path:'products/:product_id'});
  this.route('delete',{path:'products/del/:product_id'});
});

export default Router;```



Aucun commentaire:

Enregistrer un commentaire