I am working on Spring Project and am I am trying to prevent URL Parameters for Session Tracking programmatically. This is my code
import org.auctions.Config.MvcConfig;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import web.SessionListenerWithMetrics;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.SessionTrackingMode;
import java.util.EnumSet;
public class SecurityWebApplicationInitializer implements ServletContextInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MvcConfig.class);
servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
servletContext.addListener(SessionListenerWithMetrics.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
**My question** is, are there any other approaches to do this programmatically. I am not sure if this a proper way,
Can someone help me to put this line of code in the right place
servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
If you change your mind about having to be programmatically, in application.properties:
server.servlet.session.tracking-modes=cookie
Done.
You could specify the session tracking mode in web.xml
<web-app>
....other stuff
<session-config>
<tracking-mode>COOKIE</tracking-mode>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
This will disable url rewriting by the server
Related
We have an application developed in Spring MVC and deployed on a Jetty 9 Standalone (JDK 1.8) and served in principle without Apache / Nginx.
The application makes, internally, requests to obtain external xml and xsd files to make a series of validations.
We would need to be able to intercept the calls, especially for the response as we need to be able to modify the xmls and xsds (to remove a number of characters).
The challenge is that we can NOT modify the application. That is we cannot add something to the source code and recompile.
The first strategy has been to include a jar with a Filter / ServletFilter but only to log the requests, so that we could check if the GET calls that we suppose the controller makes to the xml / xsd appear.
Filter code
package com.htmlfilter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class HtmlFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("HtmlFilter: init method");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("HtmlFilter: doFilter method");
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length());
System.out.println(path);
chain.doFilter(request, response);
}
#Override
public void destroy() {
System.out.println("HtmlFilter: destroy method");
}
}
ServletFilter code
package com.htmlfilter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HtmlServletFilter extends HttpServlet {
public void init() throws ServletException {
System.out.println("HtmlServletFilter: init");
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
System.out.println("HtmlServletFilter: doGet");
String path = request.getRequestURI();
System.out.println(path);
response.getWriter().println("Hello This is GET
Response.");
}
}
web.xml
<filter>
<filter-name>HtmlFilter</filter-name>
<filter-class>com.htmlfilter.HtmlFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HtmlFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>HtmlServletFilter</servlet-name>
<servlet-class>com.htmlfilter.HtmlServletFilter</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HtmlServletFilter</servlet-name>
<url-pattern>*.xsd</url-pattern>
</servlet-mapping>
PrintNamesServlet.java:
This servlet prints the entered name of the user
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "PrintNamesServlet")
public class PrintNamesServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Ram Dhakal");
}
}
CounterServlet.java:
Counts the number of hits or visit in the page
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CounterServlet") public class CounterServlet
extends HttpServlet {
int totalHits;
public void init() throws ServletException{
totalHits = 0;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Total visit count: " + totalHits++);
} public void destroy(){
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
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_1.xsd"
version="3.1">
<servlet>
<servlet-name>PrintNamesServlet</servlet-name>
<servlet-class>PrintNamesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PrintNamesServlet</servlet-name>
<url-pattern>/PrintNamesServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CounterServlet</servlet-name>
<servlet-class>CounterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterServlet</servlet-name>
<url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>
</web-app>
I am getting error:
No webpage was found for the web address: http://localhost:8080/
As, I am trying to run the servlet for the first time, I am not getting what is wrong with my code. I typed http://localhost:8080/PrintNamesServlet in the url.
You have used Servlet 3.0 specification
Lets takes look at it
In Servlet 3.0, servlet metadata can be specified using #WebServlet
#WebServlet(name="mytest",
urlPatterns={"/myurl"})
public class TestServlet extends javax.servlet.http.HttpServlet {
....
}
In this way the servlet is accessed by using the url pattern specified in the annotation.
##WebServlet(name="mytest",urlPatterns={"/myurl"})
according to that servlet is acceseed using
http://localhost:8080/myurl
In you case you have only specified name you have to specify urlPatterns also, so you can able to call you servlet properly.
#WebServlet(name = "CounterServlet",urlPatterns={"/CounterServlet"}) public class CounterServlet extends HttpServlet {}
And you do not need to use web.xml file.
When you use annotations like this #WebServlet(name = "PrintNamesServlet") the web.xml mapping is not used.
You have to either remove these annotations or add urlMapping attribute to them.
Appreciate any help.
I'm facing the problem with the CORS on my newly deployed Tomcat 8.0.30. I keep getting the error below. I am using 127.0.0.1 as the API server address and 192.168.1.100 is the address of my HTTP server.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '_http://192.168.1.100:8999' is therefore not allowed access. The response had HTTP status code 403.
Read through whole Tomcat documentation, added the cors filter under the tomcat web.xml, as well as the project web.xml, but nothing magic happens here, still getting the same error. Tried both minimal and advanced with init-param, same error.
I am using Spring 4 as my rest api framework. Any more configurations need to be done on the project coding part?
Here are the steps I've done so far:
add cors filter under web.xml, mininal config according to documentation, not working
add cors filter under web.xml, full config, not working as well.
tried to use cors filter from http://software.dzhuvinov.com/cors-filter.html, still not working
Any suggestions?
Add the web.xml configuration
I've tried to change cors.allowed.origins to *, to 127.0.0.1,192.168.1.100, all not working,
remove credentials and maxage
<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://192.168.1.100</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,Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Suggested by Vishal, changing tomcat version from 8.0 to 8.5, still same issue
XMLHttpRequest cannot load http://127.0.0.1:8080/leyutech-framework-gurunwanfeng/api/ad/getAdInfoByAdType.html?adType=0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.1.100:8080' is therefore not allowed access. The response had HTTP status code 403.
I've used the custom filter to accomplish this issue, I have no idea why offical tomcat cors filter is not working in my case, Any one can suggest the logic behind this, I am willing to try this out.
Original Post from Tobia
The code is modified from the link above.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void destroy() {
// TODO Auto-generated method stub
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml configuration under current project
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>com.example.util.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
I encountered this problem once and I developed a custom handler for a Jetty Web application.
Maybe it can help you.
CORSHandler.hava
import java.io.IOException;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.server.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class CORSHandler extends HandlerWrapper {
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
public CORSHandler() {
super();
}
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// Allow Cross-site HTTP requests (CORS)
response.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*");
// Accept Content-Type in header
response.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, "content-type");
// Accept GET, POST, PUT and DELETE methods
response.addHeader(ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE");
if (_handler!=null && isStarted())
{
_handler.handle(target,baseRequest, request, response);
}
}
}
Starter.java
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import com.example.config.AppConfig;
import com.example.handlers.CORSHandler;
import com.example.properties.*;
public class Starter {
public static void main( final String[] args ) throws Exception {
Server server = new Server( 8080 );
// Register and map the dispatcher servlet
final ServletHolder servletHolder = new ServletHolder( new CXFServlet() );
HandlerWrapper wrapper = new CORSHandler();
final ServletContextHandler context = new ServletContextHandler();
context.setContextPath( "/" );
context.addServlet( servletHolder, "/rest/*" );
context.addEventListener( new ContextLoaderListener() );
context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() );
context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() );
wrapper.setHandler(context);
server.setHandler(wrapper);
server.start();
server.join();
}
}
I'm trying to run elementary spring-4 web-mvc application without xml configuration at all. I've looked spring documentation and examples, but it didn't work for me.
My controller:
package com.nikolay.exam.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
#ResponseBody
public String home() {
return "Hello world!";
}
}
AppConfig:
package com.nikolay.exam.config;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
}
WebConfig:
package com.nikolay.exam.config;
import com.nikolay.exam.controller.HomeController;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public HomeController homeController() {
return new HomeController();
}
}
And WebInitializer:
package com.nikolay.exam.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setConfigLocation("com.nikolay.exam.config");
servletContext.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(root));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
But when I run my application on tomcat I receive an error:
14-Feb-2015 11:35:29.825 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
14-Feb-2015 11:35:32.766 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager
14-Feb-2015 11:35:32.904 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager has finished in 136 ms
14-Feb-2015 11:35:34.888 WARNING [http-nio-8080-exec-3] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
I think it's the way you register your config class that is not correct.
Try using the AnnotationConfigWebApplicationContext#register instead.
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
Probably you need to change
dispatcher.addMapping("/*");
to
dispatcher.addMapping("/");
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";
}
}