Spring MVC REST api not consuming json in chrome web client - angularjs

I have an angularjs spring web app that returns a json. This is the url
http://localhost:8080/AngularJSPostFormSpringMVC/
The above is the output of the json url.
When I luanch the url in chrome web client it does not consume json even though it returns a status of 200 : 0k.
This is the out put
This is my controller code
public class SpringMVCController {
#RequestMapping(value = "/PostFormData", method = RequestMethod.POST)
public #ResponseBody
Person PostService(#RequestBody Person person) {
return person;
}
#RequestMapping(value = "/PostFormDataByParam", method = RequestMethod.POST)
public #ResponseBody Person PostFormDataByParam(HttpServletRequest request) {
Person person = new Person();
person.setName(request.getParameter("name"));
person.setName(request.getParameter("location"));
person.setName(request.getParameter("phone"));
return person;
}
Please what could be wrong?

create model
public class Person {
private int name;
private String location;
private String phone;
getter setter ...
dependencies
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
controller
#RequestMapping(value = "/PostFormDataByParam", method = RequestMethod.POST)
public #ResponseBody Person PostFormDataByParam(#RequestBody Person person, HttpServletRequest request) {
person.get ...
return person;
}
good luck ~

Change type of parameter define in method PostService, like this;)
#RequestMapping(value = "/PostFormData", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE})
public #ResponseBody
Person PostService(#RequestBody Person[] person) {
return person[0];
}

Related

how to create request type scope through annonation in spring mvc?

requirement is that i want request type scope in particular bean Omsdashboard.java .i have to submit the architecture of controller where i want every time request i want new object .so this can be achieve by request scope because controller is by default singleton that why i cant not handle this problem please explain it. thanks for giving your time.
beans class
Omsdashborad.java
#Component
public class OMSDashBoard implements Serializable{
controller class
I am using autowire but they give singleton object but i want another object when project is loaded both method call onload time first call below method then call first method.
#Autowired
private WebApplicationContext context;
private OMSDashBoard omsDashBoard;
public OMSDashBoard getOMSDashBoard() {
System.out.println("##2"+(OMSDashBoard) context.getBean("omsDashBoard"));
return (OMSDashBoard) context.getBean("omsDashBoard");
}
#Autowired(required = false)
public void setOmsDashBoard(#Qualifier("omsDashBoard") OMSDashBoard omsDashBoard) {
this.omsDashBoard = omsDashBoard;
#RequestMapping(value = "/stuck/order/{fromDate}/{toDate}/{requestType}", method = RequestMethod.POST)
public ResponseEntity<OMSDashBoard> getAllStcukOrdersByRequestType(#PathVariable("fromDate") String fromDate,
#PathVariable("toDate") String toDate, #PathVariable("requestType") String orderTypeCd) {
return new ResponseEntity<OMSDashBoard>(omsDashBoard, HttpStatus.OK);
}
#RequestMapping(value = "order/summary/{fromDate}/{toDate}", method = RequestMethod.POST)
public ResponseEntity<OMSDashBoard> getOrderSummaryDetails(#PathVariable("fromDate") String fromDate,
#PathVariable("toDate") String toDate) {
return new ResponseEntity<OMSDashBoard>(omsDashBoard, HttpStatus.OK);
}
step :
use scope(value="request") in omsdashboard.java
step-2
autowired
public AnnotationConfigWebApplicationContext context;
step-3
OMSDashBoard omsDashBoard = (OMSDashBoard) context.getBean(OMSDashBoard.class); in both method to get new object through bean.

jspViewResolver and #RestController

Learning Restful web service using Spring MVC and angularJS.
Background story:
I was doing some form submission particular PUT method I was getting 405 method not allowed..
Spring MVC PUT Request returns 405 Method Not Allowed
One of the answers stated to should change to from #Controller to #RestController much cleaner implementation.
Setup:
I use jspViewResolver to direct my pages.
app-dispatcher-servlet
// -- app-dispatcher-servlet
<!-- ViewResolver JSP -->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/html/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
Like so
// -- Controller
#Controller
#RequestMapping(value="/spa")
public class spaController {
#RequestMapping(method = RequestMethod.GET)
public String pagIndex(Model model){
/* some code here */
return "spa"; // Goes to --> spa.jsp
}
}
Problem
But once I change #Controller to #RestController spa.jsp page doesn't show up just String 'spa' is returned....
Right now I created two controllers which I think is redundant... looks something like this
spaController -- handles all jsp pages
#Controller
#RequestMapping(value="/spa")
public class spaController {
#RequestMapping(method = RequestMethod.GET)
public String pagIndex(Model model){
/* some code */
model.addAttribute("bookForm", new Book());
return "spa";
}
}
spaRestController -- rest end point
#RestController
#RequestMapping(value="/spa")
public class spaRestController {
#Autowired
private BookDao bookDao;
// Get list of books
#RequestMapping(path="/booklist", method = RequestMethod.GET, produces="application/json")
public Map<String, Object> getListBooks(){
System.out.println("method called");
List<Book> books = bookDao.getBookList();
Map<String, Object> data = new HashMap<String, Object>();
data.put("results", books);
return data;
}
// Save only
#RequestMapping(path="/booklist/{id}", method = RequestMethod.PUT)
public String save(#PathVariable("id") Integer id, #RequestBody Book book, BindingResult result){
System.out.println("Save method clicked");
System.out.println(book);
System.out.println(result);
return null;
};
}
Question:
I think having two controllers is a bit redundant is there away to combine these two?
Is there a better way of handling this?
Thank you all...

How to display tables from DB in Spring MVC Controller

I have referred to ->
Spring MVC how to display data from database into a table
My aim is to try and understand what is the syntax and process to create queries, and whether I'm correct.
The following code tries to display all Order entities.
#AutoWired
private OrderService orderService;
#RequestMapping("/")
//public String orderPage(Model model) {
// model.addAttribute("orderList", SomeApp.getStore().getOrderList());
// return "form/orderPage"};
// this is the code I am trying to translate below
#ResponseBody
public List<order> orderList(Map<String, Object> model) {
List<order> orderList = OrderService.findALl();
//orderRepository.findAll <- where does this come in? is it needed at all
return orderList;
}
If the Service layer is not being used, in my Repo do I only state
List<Order> findAll();
Additional Info:
Service layer is not used in this project and instead business logic will be in Controller (partly why I'm confused as to what code goes where)
You need to #Autowire the OrderRepository so that you can call orderRepository.findAll() in your Controller as shown below. For that, you also need to define the OrderRepository and Order Entity classes.
Controller:
#Controller
public class Controller {
#AutoWired
private OrderRepository orderRepository;
#RequestMapping("/")
#ResponseBody
public List<order> orderList(Map<String, Object> model) {
List<order> orderList = OrderService.findALl();
orderRepository.findAll();
return orderList;
}
}
Repository:
#Repository
public interface OrderRepository extends JpaRepository<Order, Integer> {
public Order findAll();
}
Entity:
#Entity
public class Order {
//add your entity fields with getters and setters
}
You can refer here for spring-data-jpa basic example.

Session management in angularjs and spring

I am using session service in AngularJS and #SessionAttributes in spring. Now how can we link both sessions and track the user session appropriately.
Below is my code:
#SessionAttributes("usersessionobj")
public class LoginController {
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("userModel") User user, ModelMap model) {
/*...*/
model.addAttribute("usersessionobj",userModel);
return "result";
}
}
#RequestMapping("/endsession")
public String nextHandlingMethod2(SessionStatus status){
status.setComplete();
return "login";
}

Failed to create an instance of Service via deferred binding

I have been trying to build a GWT / Google App Engine web app using the mvp4g framework.
I keep getting an error about Failing to create an instance of my Service via deferred binding.
My Acebankroll.gwt.xml file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='acebankroll'>
<inherits name='com.google.gwt.user.User'/>
<inherits name="com.google.gwt.i18n.I18N"/>
<inherits name='com.google.gwt.user.theme.standard.Standard'/>
<inherits name='com.mvp4g.Mvp4gModule'/>
<entry-point class='com.softamo.acebankroll.client.AceBankroll'/>
<source path='client'/>
</module>
My Entry Module looks like:
public class AceBankroll implements EntryPoint {
public void onModuleLoad() {
Mvp4gModule module = (Mvp4gModule)GWT.create( Mvp4gModule.class );
module.createAndStartModule();
RootPanel.get().add((Widget)module.getStartView());
}
}
Error Trace
I post the complete error trace as an answer.
FAQ and Trials
I have read that the next list of common mistakes may cause this error:
The ServiceAsync interfaces have methods with return values. This is wrong, all methods need to return void.
The Service interfaces don't extend the RemoteService interface.
The methods in the ServiceAsync interfaces miss the final argument of AsyncCallback.
The methods on the two interfaced, ExampleService and ExampleServiceAsync, don't match up exactly (other than the return value and AsyncCallback argument)
I have checked all the above conditions and did not find the problem.
How do you insert your services in the presenters?
Here is a snippet illustrating how I do inject the service in my presenter classes.
protected MainServiceAsync service = null;
#InjectService
public void setService( MainServiceAsync service ) {
this.service = service;
}
Do you have the required libraries?
Yes, I have commons-configuration-1.6.jar, commons-lang-2.4.jar and mvp4g-1.1.0.jar in my lib directory.
Does your project compiles?
Yes, it does compile. I use Eclipse with GWT/Google App Engine plugin. Next I post my .classpath
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" output="test-classes" path="test"/>
<classpathentry kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/>
<classpathentry kind="con" path="com.google.gwt.eclipse.core.GWT_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/commons-configuration-1.6.jar"/>
<classpathentry kind="lib" path="lib/commons-lang-2.4.jar"/>
<classpathentry kind="lib" path="lib/mvp4g-1.1.0.jar"/>
<classpathentry kind="lib" path="test/lib/emma.jar"/>
<classpathentry kind="lib" path="test/lib/junit-4.5.jar"/>
<classpathentry kind="lib" path="C:/Users/sdelamo/Programms/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.1_1.3.1.v201002101412/appengine-java-sdk-1.3.1/lib/testing/appengine-testing.jar"/>
<classpathentry kind="lib" path="C:/Users/sdelamo/Programms/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.1_1.3.1.v201002101412/appengine-java-sdk-1.3.1/lib/impl/appengine-api.jar"/>
<classpathentry kind="lib" path="C:/Users/sdelamo/Programms/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.1_1.3.1.v201002101412/appengine-java-sdk-1.3.1/lib/impl/appengine-api-labs.jar"/>
<classpathentry kind="lib" path="C:/Users/sdelamo/Programms/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.1_1.3.1.v201002101412/appengine-java-sdk-1.3.1/lib/impl/appengine-api-stubs.jar"/>
<classpathentry kind="lib" path="C:/Users/sdelamo/Programms/eclipse/plugins/com.google.appengine.eclipse.sdkbundle.1.3.1_1.3.1.v201002101412/appengine-java-sdk-1.3.1/lib/impl/appengine-local-runtime.jar"/>
<classpathentry kind="output" path="war/WEB-INF/classes"/>
</classpath>
Are your Bean Serializable?
Yes, they are serializable. They implements the next interface:
public interface BasicBean extends Serializable {
public String getId();
public void copy(BasicBean ob);
}
They all have an empty argument constructor. Some of them have two constructors. One without arguments and one with arguments.
Some of them implement this interface
public interface NameObject extends BasicBean, BaseOwnedObject, Comparable<NameObject> {
public String getName();
public void setName(String name);
public abstract int compareTo(NameObject ob);
}
Can the Comparable cause problems?
How does your service code looks like?
I post my service code:
MainService
#RemoteServiceRelativePath( "main" )
public interface MainService extends RemoteService {
public List<UserBean> getUsers();
public void deleteUser(UserBean user);
public void createUser(UserBean user);
public void updateUser( UserBean user );
public String authenticate(String username, String password);
public boolean isSessionIdStillLegal(String sessionId);
public void signOut();
public boolean userAlreadyExists(String email);
public UserBean getByEmail(String email);
public void confirmUser(String email);
public UserBean getUserById(String id);
}
MainServiceAsync
public interface MainServiceAsync {
public void getUsers(AsyncCallback<List<UserBean>> callback);
public void deleteUser(UserBean user, AsyncCallback<Void> callback);
public void createUser(UserBean user, AsyncCallback<Void> callback);
public void updateUser( UserBean user, AsyncCallback<Void> callback);
public void authenticate(String username, String password, AsyncCallback<String> callback);
public void isSessionIdStillLegal(String sessionId, AsyncCallback<Boolean> callback);
public void signOut(AsyncCallback<Void> callback);
public void userAlreadyExists(String email, AsyncCallback<Boolean> callback);
public void getByEmail(String email, AsyncCallback<UserBean> callback );
public void confirmUser(String email, AsyncCallback<Void> callback );
public void getUserById(String id, AsyncCallback<UserBean> callback);
}
Basic Bean
import java.io.Serializable;
public interface BasicBean extends Serializable {
public String getId();
public void copy(BasicBean ob);
}
User Bean
#PersistenceCapable(identityType = IdentityType.APPLICATION)
public class UserBean implements BasicBean {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
protected Long ident;
#Persistent
private String name = null;
#Persistent
private String email = null;
#Persistent
private boolean confirmed = false;
#Persistent
private String password = null;
public UserBean() { }
public String getId() {
if( ident == null ) return null;
return ident.toString();
}
public void setId(String id) {
this.ident = Long.parseLong(id);
}
public String getEmail( ) { return email; }
public void setEmail(String email) { this. email = email; }
public String getName() { return name; }
public void setName(String name) { this. name = name; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password;}
public boolean isConfirmed() { return confirmed;}
public void setConfirmed(boolean confirmed) {this.confirmed = confirmed;}
public void copy(BasicBean ob) {
UserBean user = (UserBean) ob;
this.name = user.name;
this.email = user.email;
this.password = user.password;
}
}
Next I post an extract of web.xml
Note. I have 7 other services. I am using the module functionality of MVP4G. I have other servlets defined for each module in web.xml
<servlet>
<servlet-name>mainServlet</servlet-name>
<servlet-class>com.softamo.acebankroll.server.MainServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>/acebankroll/main</url-pattern>
</servlet-mapping>
Server
BaseServiceImpl
public abstract class BaseServiceImpl extends RemoteServiceServlet {
protected Map users = new HashMap();
protected static final MemcacheService memcache = MemcacheServiceFactory.getMemcacheService();
protected static final Logger log = Logger.getLogger(BaseServiceImpl.class.getName());
protected String getSessionId() {
return getThreadLocalRequest().getSession().getId();
}
protected String getCurrentUserId() {
String id = getSessionId();
UserBean user = (UserBean) users.get(id);
if(user!=null)
return user.getId();
return null;
}
protected void saveBaseObject(BasicBean ob) {
PersistenceManager pm = JdoUtil.getPm();
String sessionId = getSessionId();
UserBean user = (UserBean) users.get(sessionId);
if(user!=null) {
String user_id = user.getId();
((BaseOwnedObject)ob).setUserId(user_id);
pm.makePersistent(ob);
}
}
protected void deleteBaseObject(Class classname, String id) {
PersistenceManager pm = JdoUtil.getPm();
pm.deletePersistent( pm.getObjectById(classname, Long.parseLong(id) ));
}
protected List getAll(Class class_name) {
PersistenceManager pm = JdoUtil.getPm();
pm.setDetachAllOnCommit(true);
Query q = pm.newQuery(class_name);
if(q==null)
return new ArrayList<BasicBean>();
q.setFilter("userId == userIdParam");
q.declareParameters("String userIdParam");
String userId = getCurrentUserId();
return (List) q.execute(userId);
}
public boolean isSessionIdStillLegal(String sessionId) {
return (users.containsKey(sessionId))? true : false;
}
public void signOut() {
String id = getSessionId();
synchronized(this) {
users.remove(id);
}
}
public BasicBean getObjectById(Class classname, String id) {
BasicBean result = null;
PersistenceManager pm = JdoUtil.getPm();
pm.setDetachAllOnCommit(true);
result = pm.getObjectById(classname, Long.parseLong(id) );
return result;
}
}
MainServiceImpl
public class MainServiceImpl extends BaseServiceImpl implements MainService {
public MainServiceImpl() {}
public String authenticate(String username, String password) {
PersistenceManager pm = JdoUtil.getPm();
UserBean user = getByEmail(username);
if(user==null || !user.isConfirmed())
return null;
String hashFromDB = user.getPassword();
boolean valid = BCrypt.checkpw(password, hashFromDB);
if(valid) {
String id = getSessionId();
synchronized( this ) {
users.put(id, user) ;
}
return id;
}
return null;
}
public void deleteUser(UserBean user) {
deleteBaseObject(UserBean.class, user.getId());
}
public List<UserBean> getUsers() {
PersistenceManager pm = JdoUtil.getPm();
pm.setDetachAllOnCommit(true);
Query q = pm.newQuery(UserBean.class);
if(q==null)
return new ArrayList<UserBean>();
return (List) q.execute();
}
public boolean userAlreadyExists(String email) {
return (getByEmail(email)!=null) ? true : false;
}
public void updateUser(UserBean object) {
saveBaseObject(object);
}
public void confirmUser(String email) {
PersistenceManager pm = JdoUtil.getPm();
UserBean user = getByEmail(email);
if(user!=null) {
user.setConfirmed(true);
pm.makePersistent(user);
}
}
public void createUser(UserBean user) {
PersistenceManager pm = JdoUtil.getPm();
String sessionId = getSessionId();
// Only store it if it does not exists
if( (getByEmail(user.getEmail()))==null) {
String hash = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
user.setPassword(hash);
pm.makePersistent(user);
synchronized( this ) {
users.put(sessionId, user);
}
}
}
public UserBean getByEmail(String email) {
return new MyAccountServiceImpl().getByEmail(email);
}
public UserBean getUserById(String id) {
return new MyAccountServiceImpl().getUserById(id);
}
}
SOLUTION
Apparently the Google App Engine Annotations in my Bean classes were causing the problem. Removing the annotation from the client side code solved the issue. What I do know if I have the classes with the JDO notation in the server side. That it is to say the beans are plain data transfere object which get cloned into object with JDO annotations in the server side.
I am literally stacked. I do not know what to try. Any help is really appreciated!
If your service methods contains POJO's they can cause you problems, they must have a zero argument constructor or no constructor defined. Also they must implement either IsSerializable or Serializable.
You can trie to create the service manually with:
MainServiceAsync service = GWT.create(MainService.class);
And maybe post the MainService classes.
Edited:
This is an output from the treelogger with a deferred binding failing, and it is outputed into the console when you do a gwt compile. You can also see this output in the devmode console if you run in hosted mode. Always check the first error, because the others are most of the time caused by the first error.
Compiling module se.pathed.defa.DefaultGwtProject
Scanning for additional dependencies: file:/C:/Users/Patrik/workspace/skola-workspace/DefaultGwtProject/src/se/pathed/defa/client/DefaultGwtProject.java
Computing all possible rebind results for 'se.pathed.defa.client.GreetingService'
Rebinding se.pathed.defa.client.GreetingService
Invoking com.google.gwt.dev.javac.StandardGeneratorContext#16c6a55
Generating client proxy for remote service interface 'se.pathed.defa.client.GreetingService'
[ERROR] se.pathed.defa.shared.UserBean is not default instantiable (it must have a zero-argument constructor or no constructors at all) and has no custom serializer. (reached via se.pathed.defa.shared.UserBean)
[ERROR] se.pathed.defa.shared.UserBean has no available instantiable subtypes. (reached via se.pathed.defa.shared.UserBean)
[ERROR] subtype se.pathed.defa.shared.UserBean is not default instantiable (it must have a zero-argument constructor or no constructors at all) and has no custom serializer. (reached via se.pathed.defa.shared.UserBean)
[ERROR] Errors in 'file:/C:/Users/Patrik/workspace/skola-workspace/DefaultGwtProject/src/se/pathed/defa/client/DefaultGwtProject.java'
[ERROR] Line 37: Failed to resolve 'se.pathed.defa.client.GreetingService' via deferred binding
Scanning for additional dependencies: jar:file:/C:/eclipse/plugins/com.google.gwt.eclipse.sdkbundle.2.0.3_2.0.3.v201002191036/gwt-2.0.3/gwt-user.jar!/com/google/gwt/core/client/impl/SchedulerImpl.java
[WARN] The following resources will not be created because they were never committed (did you forget to call commit()?)
[WARN] C:\Users\Patrik\AppData\Local\Temp\gwtc301646733929273376.tmp\se.pathed.defa.DefaultGwtProject\compiler\se.pathed.defa.client.GreetingService.rpc.log
[WARN] For the following type(s), generated source was never committed (did you forget to call commit()?)
[WARN] se.pathed.defa.client.GreetingService_Proxy
[ERROR] Cannot proceed due to previous errors
This can happen if anything that is in your client package has an import that is not whitelisted. For example i hit this because my autoimport imported an apache commons lang class into my client code.
One would have to look at their imports to make sure nothing odd is in the client code.
GWT projects are structured like:
com.app.client
com.app.server
you can't having anything that not GWT compatible in client.

Resources