在Wicket程式用Spring,要在web.xml加入設定:
<context -param> <param -name>contextConfigLocation</param> <param -value>/WEB-INF/spring*.xml</param> </context> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
在WebApplication中要建立SpringComponentInjector:
public class BasicApplication extends WebApplication { @Override protected void init() { super.init(); addComponentInstantiationListener(new SpringComponentInjector(this)); } }
如果還想把bean注入WebSession,要用InjectorHolder:
public class BasicSession extends WebSession { public BasicSession(Request request) { super(request); InjectorHolder.getInjector().inject(this); } }
設定好之後,只要在需要注入bean的地方用@SpringBean即可,範例如下:
public class SignUpPage extends BasePage { @SpringBean private UserService userService; public SignUpPage() { add(new SignUpForm("signUpForm")); } class SignUpForm extends Form { private String name; private String email; private String password; @SuppressWarnings("unused") private String confirmPassword; public SignUpForm(String id) { super(id); PasswordTextField passwordField, confirmPasswordField; add(new TextField("name", new PropertyModel(this, "name")).setRequired(true).add(new StringValidator.LengthBetweenValidator(2, 32))); add(new TextField("email", new PropertyModel(this, "email")).setRequired(true).add(EmailAddressValidator.getInstance())); add(passwordField = new PasswordTextField("password", new PropertyModel(this, "password"))); add(confirmPasswordField = new PasswordTextField("confirmPassword", new PropertyModel(this, "confirmPassword"))); add(new EqualPasswordInputValidator(passwordField, confirmPasswordField)); } @Override protected void onSubmit() { User user = new User(name, email, password, User.ROLE_USER); try { userService.createUser(user); setResponsePage(HomePage.class); } catch (DuplicatedUserNameException e) { error(getLocalizer().getString(getId() + ".nameTaken", getWebPage(), "User's name is taken: " + name)); } catch (DuplicatedUserEmailException e) { error(getLocalizer().getString(getId() + ".emailTaken", getWebPage(), "User's email is taken: " + email)); } } } }
全站熱搜
留言列表