webwork是struts2的前身,是一个mvc框架,使用方法和struts2很相似。研究webwork已经没有太大的意义,但是对于理解struts2的核心机制还是有一定意义的。下面介绍如何通过webwork2来搭建一个简单的demo。
com.opensymphony
webwork
2.2.6
javax.servlet
javax.servlet-api
3.1.0
User.java
package com.xxx.webwork.entity;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
LoginAction.java
package com.xxx.webwork.action;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ModelDriven;
import com.xxx.webwork.entity.User;
public class LoginAction implements Action,ModelDriven {
private User user = new User();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String execute() throws Exception {
if(user.getUsername().equals("admin")&& user.getPassword().equals("123456")) {
return SUCCESS;
}else {
return ERROR;
}
}
@Override
public Object getModel() {
return user;
}
}
/WEB-INF/content/admin/index.html
/success.html
/error.html
/success.html
webwork
index.html
webwork
com.opensymphony.webwork.dispatcher.ServletDispatcher
webwork
*.action
index.html
success.html
hello,welcome,${user.username}
error.html
oh,sth is wrong.
启动web服务器,访问首页,出现登录页:
输入admin/123456,点击登录,会跳转到成功页面,同时,显示用户名admin。如果用户名密码不对,跳转到错误页面。
LoginAction中引入了模型驱动ModelDriven,这样,页面上的参数可以直接通过username,password的名字传过来封装成User对象,否则需要通过user.username,user.password来传过来。涉及到传参,一般需要在action中声明页面对应的参数。还有一种做法,就是通过request.getParameter("username")的方式获取参数,下面给出RegistAction的代码,通过该代码,了解一下如何通过request的方式获取参数。
package com.xxx.webwork.action;
import javax.servlet.http.HttpServletRequest;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.xxx.webwork.entity.User;
public class RegistAction implements Action{
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
String username =(String) request.getParameter("username");
String password = (String) request.getParameter("password");
System.out.println("regist : "+username+" --> "+password);
User user = new User();
user.setUsername(username);
user.setPassword(password);
ActionContext.getContext().put("user", user);
return SUCCESS;
}
}
这种方式也就是传统Servlet获取参数的方式。为此需要在项目中引入javax.servlet:javax.servlet-api的依赖。
另外页面使用freemarker作为模板,传统的freemaker需要.ftl文件后缀,但是我们如果使用.html文件作为freemarker模板,好像也是可以的。本例中的页面全部就是html文件。
xwork.xml的配置和struts.xml的配置基本类似,但是需要引入默认的webwork-default.xml配置文件。