gwt remote procedure call error - java

I am new to GWT and I have no result from my web application.
when I tried debugging, I got an error like "source not found"
and here is the code written in all the project
<---------------------------------------------------------------------------------------->
EntryPoint Class
package body.test.combo.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class Combo implements EntryPoint {
private final FileReaderServiceAsync serviceAsync = GWT
.create(FileReaderService.class);
String content;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
VerticalPanel vPanel = new VerticalPanel();
serviceAsync.readMyFilePlease(new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
content = result;
}
#Override
public void onFailure(Throwable caught) {
System.out.println("Tezak");
}
});
Label lb = new Label(content);
vPanel.add(lb);
RootPanel.get().add(vPanel);
}
}
<---------------------------------------------------------------------------------------->
Service Interface
package body.test.combo.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("readmeplease")
public interface FileReaderService extends RemoteService {
String readMyFilePlease();
}
<---------------------------------------------------------------------------------------->
Service Async
package body.test.combo.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface FileReaderServiceAsync {
void readMyFilePlease(AsyncCallback<String> callbackVariable);
}
<---------------------------------------------------------------------------------------->
Server Implementation class
package body.test.combo.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import body.test.combo.client.FileReaderService;
public class FileReaderServiceImplementation extends RemoteServiceServlet implements FileReaderService {
#Override
public String readMyFilePlease() {
String allContent = "ezayak yad ya sayed";
return allContent;
}
}
<---------------------------------------------------------------------------------------->
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee">
<!-- Servlets -->
<servlet>
<servlet-name>readMyFilePlease</servlet-name>
<servlet-class>body.test.combo.server.FileReaderServiceImplementation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>readMyFilePlease</servlet-name>
<url-pattern>/combo/readmeplease</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>Combo.html</welcome-file>
</welcome-file-list>
</web-app>
Project name is 'combo'.

Does your project xml file (Combo.gwt.xml) contain the following:
<module rename-to='combo'>
You may also want to try some of the suggestions from this post.
it would be very useful for you to post that project xml file as well as the error itself.

Related

Unable to test restful service

I am very new to Restful Services and I followed some guidelines given be the boss to make it. When I am using the URL to test it via browser, it shows not found. Console is not showing any error or exception (However, I removed almost 100 errors to reach this point), but still the result is same.
This is my directory structure
This is my RDRresource.java (Includes the service I want to test)
package org.uclab.IMP.rs.rdr;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.uclab.IMP.*;
import com.google.gson.Gson;
import org.uclab.IMP.datamodel.*;
import org.uclab.IMP.datamodel.RDR.*;
import org.uclab.IMP.datamodel.RDR.dataadapter.*;
/**
* Facade for the Restful Web service to handle the data curation functions
*/
#Path("rdr")
public class RDRresource {
#Context
private UriInfo context;
/**
* Creates a new instance of DataCurationResource
*/
public RDRresource() {
}
private static final Logger logger = LoggerFactory.getLogger(RDRresource.class);
/**
* This function is using to get user by ID
* #param UserID
* #return a list of object Users with "Error", "No Error" and new added ID
*/
#GET
#Produces("application/json")
#Consumes("application/json")
#Path("RetriveRules")
public List<Rules> RetriveRules() {
Rules objOuterRules = new Rules();
List<Rules> objListRules = new ArrayList<Rules>();
try
{
objOuterRules.setRuleID(Long.parseLong("RuleID"));
DataAccessInterface objDAInterface = new RuleDataAdapter();
AbstractDataBridge objADBridge = new DatabaseStorage(objDAInterface);
objListRules = objADBridge.RetriveRules();
logger.info("Get all rules successfully, rules Details="+objOuterRules);
}
catch(Exception ex)
{
logger.info("Error in getting user");
}
return objListRules;
}
This is my web.xml file
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.uclab.IMP.rs.rdr</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/webresources/*</url-pattern>
</servlet-mapping>
</web-app>
URL I am trying and result is here

restful webservice in java and mysql

I am new to the restful webservices. I am new creating restful webservice in java using jersey . This webservice is getting data from mysql database and should display the response in xml..
But i am always getting the response error 500 from apache tomcat 7. In the console no error or exception is shown except the println method is diplaying the strings passed to it..but server is giving 500 error.. Please help me
userData.java
package com.userdb;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class userData {
public String name;
public int iduser;
public userData(){}
public userData(String name, int iduser) {
this.name = name;
this.iduser = iduser;
}
public String getName() {
return name;
}
public int getIduser() {
return iduser;
}
public void setName(String name) {
this.name = name;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
}
airtime.java
package com.userdb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/resttest")
public class airtime {
ResultSet rs=null;
String msg="hello";
Connection con=null;
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/get_users")
public List<userData> get_users(){
List<userData> retUser=new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
System.out.println("DriveManager");
PreparedStatement ps=con.prepareStatement("SELECT * FROM users");
rs=ps.executeQuery();
System.out.println(rs);
while(rs.next()){
userData obj=new userData();
obj.setIduser(rs.getInt("iduser"));
obj.setName(rs.getString("name"));
retUser.add(obj);
System.out.println("userData obj added to list");
}
con.close();
} catch (Exception e){
e.printStackTrace();
}
return retUser;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>userdb</display-name>
<servlet>
<servlet-name>Jersey WebService</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.userdb</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey WebService</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
Solution 1:
Adjust the top of userData.java to contain the following lines at the top your file:
package com.userdb;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public class userData
{...}
Explanation: You will notice that an XmlAccessorType annotation and an XMLAccessType has been added. This configuration is required when using setters in your object. You will notice that adjusting the code to not use setters (with the above excluded) will also allow you to view your RESTful service in a browser.
Solution 2:
A quicker alternative, is to set your public variables name and iduser to private. This will also avoid the clash when mapping to xml.
There should be a warning something like "...messagebodywriter not found for media type=application/xml ...".
The possible cause may be that you didn't include this dependency.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.21.1</version>
</dependency>
this is my workable pom dependencies
<dependencies>
<!-- jersey dependency -->
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to json -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.21.1</version>
</dependency>
<!-- make jersey auto marshel to xml -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-jaxb</artifactId>
<version>2.21.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>stax2-api</artifactId>
<version>3.1.4</version>
</dependency>
</dependencies>
a workable web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Rest</display-name>
<servlet>
<servlet-name>MyApplication</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.blithe.resource</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.scanning.recursive</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyApplication</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
</web-app>
workable resource
package com.blithe.resource;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.blithe.model.User;
#Path("helloworld")
public class HelloWorldResource
{
#GET
#Produces(MediaType.APPLICATION_XML)
public List<User> getStringArray(){
List<User> list = new ArrayList<>();
User u = new User();
u.setName("testName");
list.add(u);
return list;
}
}
and the model
package com.blithe.model;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Hope this will help you.
By the way, it is better not to include too many dependencies which might duplicate in your pom.xml, since some of them might conflict to each other. And it will cost a lot of time on debugging. So it's better to find out what dependencies are really needed.
Cheers!
Gregory Nikitas is right. The issue in your model class should also be taken care of.

CDi in Vaadin is not injecting: NullPointerException

I'm new in Vaadin and I'm trying to inject a #UIScoped-bean in my UI-class. But it throws every time a NullPointerException - why?
Here is my UI-class:
import javax.inject.Inject;
import org.apache.log4j.Logger;
import com.vaadin.annotations.Theme;
import com.vaadin.cdi.CDIUI;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("tableuitheme")
#CDIUI("")
public class Table extends UI {
private final static Logger logger=Logger.getLogger(Table.class);
#Inject
private SomeBean bean;
#Override
protected void init(VaadinRequest request) {
VerticalLayout layout = new VerticalLayout();
setContent(layout);
logger.info("-------------------------- "+bean);
// String art = hakan.toString();
Label label = new Label("Hakan");
layout.addComponents(label);
}
}
And here is the interface SomeBean :
public interface SomeBean {
}
and the implementation class SomeBeanImpl:
import com.vaadin.cdi.UIScoped;
#UIScoped
public class SomeBeanimpl implements SomeBean {
}
And finally my configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>myVaadinUIServlet</servlet-name>
<servlet-class>com.vaadin.server.VaadinServlet</servlet-class>
<init-param>
<param-name>UI</param-name>
<param-value>de.ragms.ui.Table</param-value>
</init-param>
<async-supported>true</async-supported>
</servlet>
<context-param>
<description>Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<servlet-mapping>
<servlet-name>myVaadinUIServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
bean.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

Error With ServletContextListener

I am studying servlets and I made one example from book but I got nullpointerexception.
Here are my classes:
package chala;
public class Dog {
private String breed;
public Dog(String breed) {
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Dog class is POJO class with simple functionality.
package chala;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class CtxListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
String breed = sc.getInitParameter("breed");
Dog d = new Dog(breed);
sc.setAttribute("dog", d);
}
#Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
}
}
This is context listener class where I get servlet context object, get init parameter from it, and creating Dog object, then setting attribute of servlet context.
package chala;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CtxListenerTester
*/
#WebServlet("/CtxListenerTester")
public class CtxListenerTester extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Servlet Context Listener Example");
out.print("<BR/>");
ServletContext sc = (ServletContext) getServletContext();
System.out.println(sc.getAttribute("dog"));
Dog dog = (Dog) getServletContext().getAttribute("dog");
out.print("Dogs breed is :" + dog.getBreed());
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my servlet where I am getting servlet context attribute (DOG object) and calling Dogs getBreed() method. When I start and send GET request I am getting nullpointerexception.
Here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ContextListenerDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>breed</param-name>
<param-value>Labrador</param-value>
</context-param>
<listener>
<listener-class>chala.CtxListener</listener-class>
</listener>
</web-app>
you set the attribute in contextDestroyed() method that will invoked while context is being destroyed you need to set that attribute in contextInitialized()

Shared bean between portlets in separate war files

I'm developing a 'user settings portlet' where users can effect the search behaviour of multiple other portlets. The way I'd like to do it is by a shared bean. All portlets are in different wars, and I'd rather avoid having all wars in a single ear and using a parent application context, so deployment of portlets can be made autonomously, but haven't had much luck in finding any information on how to do it.
I have followed this blog post to try to deploy an ear file with the wars in them, but after many hours of wrestling I've come no closer to solving my problem...
The directory structure looks like this:
portlets
|--- ear
| \--- src/main/application/META-INF/application.xml
|
|--- jar (contains UserSettings.java)
| \--- src/main/resources/beanRefContext.xml
| \--- src/main/resources/services-context.xml
| \--- src/main/java/com/foo/application/UserSettings.java
|
|--- messagehistory (war, portlet 1)
| \--- [...]
|
|--- settings (war, portlet 2)
| \--- [...]
|
\--- pom.xml
I've tried setting scope="session" like the following:
<bean id="userSettings" class="com.foo.application.UserSettings" scope="session">
<aop:scoped-proxy />
</bean>
But then when I deploy the ear I get java.lang.IllegalStateException: No Scope registered for scope 'session'.
This is the controller för the history portlet, where users can search for message history, with restrictions from the settings portlet. The controller for the settings portlet is identical.
package com.foo;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletSession;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import com.foo.application.UserSettings;
import javax.annotation.PostConstruct;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.ServletContextAware;
#Controller
#SessionAttributes({"searchQuery", "searchResults"})
#RequestMapping("VIEW")
public class ViewHistory extends ContextLoader implements ServletContextAware {
private UserSettings userSettings;
private ServletContext servletContext;
#Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
#PostConstruct
public void init() {
ApplicationContext ctx = loadParentContext(servletContext);
servletContext.setAttribute(LOCATOR_FACTORY_KEY_PARAM, "ear.context");
userSettings = (UserSettings) ctx.getBean("userSettings");
}
#ModelAttribute("userSettings")
public UserSettings createUserSettings(Model model) {
model.addAttribute(userSettings);
}
#RequestMapping
public String doSearch(Model model, PortletSession portletSession) {
return "view";
}
#ActionMapping(params = "action=search")
public void searchAction(
Model model,
ActionRequest request, ActionResponse response,
BindingResult bindingResult, SessionStatus status)
{
// do nothing
}
}
The web.xml file for both wars (they are identical) looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>parentContextKey</param-name>
<param-value>ear.context</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<filter>
<filter-name>springFilter</filter-name>
<filter-class>
org.springframework.web.filter.RequestContextFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>springFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>ViewRendererServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ViewRendererServlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Turns out it was really easy just using Spring's #EventMapping annotation for plain JSR 286 eventing. No ear required and no parent application context. I just have my UserSettings.java in a separate jar project and include it as a dependency to both wars.
The controller for the search portlet looks like this:
package com.foo;
import com.foo.event.UserSettings;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import javax.portlet.Event;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.portlet.bind.annotation.EventMapping;
#Controller
#RequestMapping("VIEW")
public class ViewHistory {
private UserSettings userSettings = new UserSettings();
#ModelAttribute("userSettings")
public UserSettings createUserSettings(Model model) {
return userSettings;
}
#RequestMapping
public String doSearch(Model model) {
return "view";
}
#ActionMapping(params = "action=search")
public void searchAction(
Model model,
ActionRequest request, ActionResponse response,
#ModelAttribute("userSettings") UserSettings userSettings,
BindingResult bindingResult, SessionStatus status)
{
// do something
}
/**
* Spring calls this whenever an event is received.
* Can be limited to certain event.
*/
#EventMapping
public void handleEvent(EventRequest request) {
Event event = request.getEvent();
if (event.getName().equals("UserSettings")) {
userSettings = (UserSettings)event.getValue();
}
}
}
...and for the settings portlet:
package com.foo;
import com.foo.event.UserSettings;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import javax.xml.namespace.QName;
import org.springframework.web.bind.annotation.ModelAttribute;
#Controller
#RequestMapping("VIEW")
public class ViewSettings {
private QName qname = new QName("http:foo.com/usersettings", "UserSettings");
#ModelAttribute
public UserSettings createUserSettings(Model model) {
return new UserSettings();
}
#ActionMapping(params = "action=search")
public void searchAction(
Model model,
ActionRequest request, ActionResponse response,
#ModelAttribute("userSettings") UserSettings userSettings,
BindingResult bindingResult, SessionStatus status)
{
// as soon as an action is triggered (save button is pressed or
// whatever), send the modified UserSettings instance as an
// event to the search portlet (actually any portlet, but I
// only have one that will read events).
response.setEvent(qname, userSettings);
}
#RequestMapping
public String doView(Model model) {
return "view";
}
}

Categories