How can i bind an ace:menuItem in ace:menuButton component - java

in my Icefaces 3 application i have a drop down menu. I would like to populate it dynamicaly. In my ManagedBean i have a methode which define the menuItem. it get the label and actionMethod, and valued them on the MenuItem. When i launch my application, the item of drop down menu are always empty.
ManagedBean :
package com.omb.view;
import java.io.Serializable;
import javax.el.MethodExpression;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.icesoft.faces.component.menubar.MenuItem;
#Controller
#Scope("session")
public class MyBean implements Serializable {
private static final Log logger = LogFactory.getLog(MyBean.class);
private MenuItem menuItem1;
public String initMyBean() {
try {
initMenuItem();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
private void initMenuItem() {
menuItem1 = new MenuItem();
menuItem1.setValue("Menu 1");
MethodExpression actionExpression = FacesUtils.createAction("#{menu1Bean.display}", String.class);
menuItem1.setActionExpression(actionExpression);
}
public MenuItem getMenuItem1() {
return this.menuItem1;
}
public void setMenuItem1(MenuItem menuItem1) {
this.menuItem1 = menuItem1;
}
}
FaceUtils
package com.omb.view;
import javax.el.MethodExpression;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;
/**
* JSF utilities.
*/
public class FacesUtils {
public static MethodExpression createAction(String actionExpression, Class<?> returnType) {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().getExpressionFactory()
.createMethodExpression(context.getELContext(), actionExpression, returnType, new Class[0]);
}
public static MethodExpressionActionListener createActionListener(String actionListenerExpression) {
FacesContext context = FacesContext.getCurrentInstance();
return new MethodExpressionActionListener(context
.getApplication()
.getExpressionFactory()
.createMethodExpression(context.getELContext(), actionListenerExpression, null,
new Class[] {ActionEvent.class}));
}
}
screen.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
<ui:composition>
<ice:form id="headerForm" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<div class="menu">
<ace:menuButton id="menuButton" effect="slide" effectDuration="200" value="Menu Button">
<ace:menuItem binding="#{myBean.menuItem1}"/>
</ace:menuButton>
</div>
</ice:form>
</ui:composition>
</body>
</html>

I finally use a the standard solution :
<ace:menuButton id="menuButton" effect="slide" effectDuration="200" value="Menu Button">
<ace:menuItem value="Menu 1" action="#{myBean.display}"/>
</ace:menuButton>

Related

Spring Controller ModelAndView test MockMvc empty Response

I have this simple example setup to unit test spring Controller ModelAndView with MockMvc, but the response is always empty, even though in debug I can see that the controller code is executed.
Here's the code:
/src/main/java/controller/MvcController.java
package controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MvcController {
#RequestMapping("/hello/{id}")
public ModelAndView hello(#PathVariable("id") String id) {
Map<String, String> model = new HashMap<>();
ModelAndView modelAndView = new ModelAndView("hello", model);
return modelAndView;
}
}
/src/main/webapp/WEB-INF/jsp/hello.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="e"
uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project"%>
<%# page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>HELLO WORLD
</body>
</html>
/src/test/java/controller/MvcControllerTest.java
package controller;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = { MvcController.class })
public class MvcControllerTest {
#Autowired
private MvcController mvcController;
private MockMvc mockMvc;
#Before
public void init() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
this.mockMvc = MockMvcBuilders.standaloneSetup(mvcController).setViewResolvers(resolver).build();
}
#Test
public void testHello() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/hello/XWQHEDg9e72t");
ResultActions result = mockMvc.perform(requestBuilder);
MvcResult mvcResult = result.andReturn();
MockHttpServletResponse mockHttpServletResponse = mvcResult.getResponse();
String response = mockHttpServletResponse.getContentAsString();
assertThat(response).contains("HELLO WORLD");
}
}
The key word in MockMvc is mock. This framework does not set up a full Servlet container with a JSP engine. As such, it doesn't render the view that your controller returns and the MockHttpServletResponse does not contain a body (for this use case).
You can use MockHttpServletResponse#getForwardedUrl() to get the url of the JSP that the Servlet container would've forwarded the request to, constructed from your view name and the prefix and suffix of your InternalResourceViewResolver.

Login is not displayed after authorization

I want then user logined(authorize) in header menu displayed menu with username(login) like at picture.
For this purpose i have the corresponding code in angular:
File header.component.html:
<nav class="navbar">
<a routerLink="" id="nav_logo">
DishOnline
</a>
<div id="nav_right_section">
<a routerLink="/loginPage">
Вход
</a>
<button [hidden]=" receivedAnswer!==undefined && receivedAnswer!==null" mat-button [matMenuTriggerFor]="menu">{{receivedAnswer.login}}</button>
<mat-menu #menu="matMenu">
<button mat-menu-item>Мой кабинет</button>
<button mat-menu-item>Выйти</button>
</mat-menu>
</div>
</nav>
File header.component.ts:
import {Component,OnInit } from '#angular/core';
import { LoginNameService} from '../services/loginName.service';
import {LoginName} from '../classes/loginName';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls : ['./header.component.scss'],
providers: [LoginNameService]
})
export class HeaderComponent implements OnInit
{
receivedAnswer: LoginName;
loginNameObject: LoginName=new LoginName();
constructor(private loginNameService: LoginNameService) {}
submit() {
this.loginNameService.postData()
.subscribe((data: LoginName) => {},
error => console.log(error)
);
}
ngOnInit(): void {
this.receivedAnswer=this.loginNameObject;
this.submit();
}
}
I send on server(backend - Spring Boot) empty POST request, using for this service loginName.service.ts.
File loginName.service.t:
import {Injectable} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
#Injectable()
export class LoginNameService {
constructor(private http: HttpClient) { }
postData() {
// tslint:disable-next-line:prefer-const
let baseUrl = 'http://localhost:8089';
return this.http.post(baseUrl + '/loginName', null);
}
}
From service i have the answer in JSON:
{"login":"DishOnline"}
But received login not displayed in header.
Code receiving login on backend(Spring Boot):
package com.greatproject.dishonline.controller;
import com.greatproject.dishonline.service.MyUserDetailsService;
import com.greatproject.dishonline.service.MyUserPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
#RestController
public class AuthorizationController {
#RequestMapping("/loginName")
public #ResponseBody
Map<String,String> loginName(Model model,
Authentication authentication,
HttpSession session,
MyUserPrincipal principal
) {
String login = "";
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
login = auth.getName(); //get logged in username
Map<String, String> mapLoginName = new HashMap<String, String>();
mapLoginName.put("login", login);
return mapLoginName;
}
}
Please help me resolve this problem.
You can get the username off the principal. Try adding the principal.username to the model and retrieving it on the ui that way.

OAuth2 Facebook - not running

Edit: Working with Angular2 -
I'm trying to implement OAuth2 to make users log in using Facebook/Github.
When I'm at localhost:4200/login I simply click "log in with facebook" and it tries to redirect to localhost:4200/login/facebook BUT then it gives me the error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login/facebook'
Error: Cannot match any routes. URL Segment: 'login/facebook'
What could be wrong? I've spent hours trying to figure it out but with no luck. Am I missing anything?
In my OAuth2Index.ts file I have the following:
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'OAuth2Index',
templateUrl: './auth-server/src/main/resources/static/index.html',
// styleUrls: ['./navbar.component.css']
})
export class OAuth2IndexComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
It displays the index.html file, which has:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Demo</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width" />
<base href="/" />
<link rel="stylesheet" type="text/css"
href="/webjars/bootstrap/css/bootstrap.min.css" />
<script type="text/javascript" src="/webjars/jquery/jquery.min.js"></scr>
<script type="text/javascript"
src="/webjars/bootstrap/js/bootstrap.min.js"></script>
</head>
<body ng-app="app" ng-controller="home as home">
<h1>Login</h1>
<div class="container" ng-show="!home.authenticated">
<div>
With Facebook: click here
</div>
<div>
With Github: click here
</div>
</div>
<div class="container" ng-show="home.authenticated">
Logged in as: <span ng-bind="home.user"></span>
<div>
<button ng-click="home.logout()" class="btn btn-primary">Logout</button>
</div>
</div>
<script type="text/javascript" src="/webjars/angularjs/angular.min.js"></script>
<script type="text/javascript">
angular
.module("app", [])
.config(
function($httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).controller("home", function($http, $location) {
var self = this;
$http.get("/user").success(function(data) {
if (data.name) {
self.user = data.name;
self.authenticated = true;
} else {
self.user = "N/A";
self.authenticated = false;
}
}).error(function() {
self.user = "N/A";
self.authenticated = false;
});
self.logout = function() {
$http.post('logout', {}).success(function() {
self.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
self.authenticated = false;
});
};
});
</script>
Please notice the: "With Facebook: click here
xxxx"
I have some beans in my SocialApplication.java file that should handle the action when user clicks login with facebook (i.e. /login/facebook).
/*
* Copyright 2012-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example;
import java.security.Principal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.filter.CompositeFilter;
#SpringBootApplication
#RestController
#EnableOAuth2Client
#EnableAuthorizationServer
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SocialApplication extends WebSecurityConfigurerAdapter {
#Autowired
OAuth2ClientContext oauth2ClientContext;
#RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
Map<String, String> map = new LinkedHashMap<>();
map.put("name", principal.getName());
return map;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
.logoutSuccessUrl("/").permitAll().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.antMatcher("/me").authorizeRequests().anyRequest().authenticated();
// #formatter:on
}
}
public static void main(String[] args) {
SpringApplication.run(SocialApplication.class, args);
}
#Bean
public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
#Bean
#ConfigurationProperties("github")
public ClientResources github() {
return new ClientResources();
}
#Bean
#ConfigurationProperties("facebook")
public ClientResources facebook() {
return new ClientResources();
}
private Filter ssoFilter() {
CompositeFilter filter = new CompositeFilter();
List<Filter> filters = new ArrayList<>();
filters.add(ssoFilter(facebook(), "/login/facebook"));
filters.add(ssoFilter(github(), "/login/github"));
filter.setFilters(filters);
return filter;
}
private Filter ssoFilter(ClientResources client, String path) {
OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(
path);
OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext);
filter.setRestTemplate(template);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(
client.getResource().getUserInfoUri(), client.getClient().getClientId());
tokenServices.setRestTemplate(template);
filter.setTokenServices(tokenServices);
return filter;
}
}
class ClientResources {
#NestedConfigurationProperty
private AuthorizationCodeResourceDetails client = new AuthorizationCodeResourceDetails();
#NestedConfigurationProperty
private ResourceServerProperties resource = new ResourceServerProperties();
public AuthorizationCodeResourceDetails getClient() {
return client;
}
public ResourceServerProperties getResource() {
return resource;
}
}
I'm my app-routing.module.ts I have:
const routes: Routes = [
// {path: 'index.html ', data: {title: 'Login'}, component: LoginComponent},
// {path: 'login', data: {title: 'Login'}, component: LoginComponent},
// {path: 'index ', data: {title: 'Login'}, component: OAuthIndexComponent},
{path: 'login', data: {title: 'Login'}, component: OAuth2IndexComponent},
{path: 'signup', data: {title: 'Login'}, component: UserRegistrationComponent},
{path: '', pathMatch: 'full', redirectTo: '/login'},
{
path:'',component: AppWrap,
children:[
{path: 'cars', data: {title: 'Car'}, component: ProductsComponent},
{path: 'cars/:id', data: {title: 'Car'}, compoent: ProductSingleDetailComponent},
// {path: 'login/facebook', data: {title: 'facebookLogin'}, component: OAuth2IndexComponent}
]
}
];
In my app.module.ts I have remembered to declare OAuth2IndexComponent.

Http 404 error in Hello world Spring MVC Web app fully java configured

I'm new to Spring Web MVC and I tried to try Hello world app.
I followed an example from "Spring In Action 4th ed" book which only uses java config (without any XML file). I use Tomcat v7.0 server and servlet 3.
The problem is when I try to go to the home page I get Http 404 error.
The used Java classes are :
DispatcherServlet configuration:
package config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class FirstWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
}
Spring MVC configuration :
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("web")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Configuration used to get other Beans (doesn't do any thing in the hello world app)
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages={"lgmi_cr"},excludeFilters={#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)})
public class RootConfig {
}
Home page controller
package web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping(value="/")
public String home() {
return "home";
}
}
A JSP file "home" uneder /WEB-INF/views/
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>First app</title>
</head>
<body>
<h1>Hello world</h1>
</body>
</html>
Since it 404 error, my first impression is that it could not find any controller but I don't know why.
Thank you for any help
I have just found the problem.
Actually, I added the external Spring jar files to the project classpath and I forget to add them to myProject/WebContent/WEB-INF/lib.

java wicket error!

This is my code,
package com.mywicketapp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.extensions.ajax.markup
.html.autocomplete.AutoCompleteTextField;
public class HomePage extends WebPage
{
public HomePage()
{
Form form = new Form("form");
add(form);
final AutoCompleteTextField field =
new AutoCompleteTextField("auto", new Model(""))
{
protected Iterator getChoices(String input)
{
if (Strings.isEmpty(input))
{
return Collections.EMPTY_LIST.iterator();
}
List choices = new ArrayList(10);
Locale[] locales = Locale.getAvailableLocales();
for (int i = 0; i < locales.length; i++)
{
final Locale locale = locales[i];
final String country = locale.getDisplayCountry();
if (country.toUpperCase().startsWith(input.toUpperCase()))
{
choices.add(country);
if (choices.size() == 10)
{
break;
}
}
}
return choices.iterator();
}
};
form.add(field);
final Label label = new
Label("selectedValue", field.getModel());
label.setOutputMarkupId(true);
form.add(label);
field.add(new AjaxFormSubmitBehavior(form, "onchange")
{
protected void onSubmit(AjaxRequestTarget target)
{
target.addComponent(label);
}
#Override
protected void onError(AjaxRequestTarget target)
{
}
});
}
}
This is my application code:
package com.mywicketapp;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* #see com.mywicketapp.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* Constructor
*/
public WicketApplication()
{
}
/**
* #see org.apache.wicket.Application#getHomePage()
*/
public Class<HomePage> getHomePage(){
return HomePage.class;
}
}
Some html:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
The textfield below will autocomplete country names
<br><hr>
<form wicket:id="form">
Selected value is: <span wicket:id="selectedValue"></span>
<br/>
Country: <input type="text" wicket:id="auto" size="20"/>
</form>
</body>
</html>
And the error:
- log - Logging to org.slf4j.impl.Log4jLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog
>>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP
INFO - log - jetty-6.1.25
INFO - log - NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
WARN - log - failed wicket.mywicketapp: java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
ERROR - log - Failed startup of context org.mortbay.jetty.webapp.WebAppContext#66e7b3f2{/,src/main/webapp}
java.lang.ClassCastException: wicket.extensions.Initializer cannot be cast to org.apache.wicket.IInitializer
at org.apache.wicket.Application.addInitializer(Application.java:864)
at org.apache.wicket.Application.load(Application.java:938)
at org.apache.wicket.Application.initializeComponents(Application.java:715)
at org.apache.wicket.protocol.http.WicketFilter.init(WicketFilter.java:732)
at org.mortbay.jetty.servlet.FilterHolder.doStart(FilterHolder.java:97)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:662)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1272)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:489)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.handler.HandlerWrapper.doStart(HandlerWrapper.java:130)
at org.mortbay.jetty.Server.doStart(Server.java:224)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at com.mywicketapp.Start.main(Start.java:43)
INFO - log - Started SelectChannelConnector#0.0.0.0:8080
Looks to me like you have a version incompatibility problem... Check to make sure that the version of wicket-extensions that you're using is compatible with your wicket version. The wicket.extensions.Initializer that's getting loaded and causing the exception is surely getting loaded up by your AutoCompleteTextField.

Categories