您的位置:首页 > 编程语言 > Java开发

struts环境基本配置

2015-08-28 22:40 495 查看


1、搭建struts运行环境
1)建立Web项目,将struts相关包引入到项目中

2)将struts-config.xml配置文件复制到项目中

3)在web.xml配置文件中配置Servlet如下:

[html] view
plaincopy

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>2</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>



<!-- Standard Action Servlet Mapping -->

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

2、建立相关ActionForm及Action对象
1)ActionForm对象


[java] view
plaincopy

/**

* 登陆ActionForm,负责表单数据收集

* 其继承:org.apache.struts.action.ActionForm

* 注意:表单的属性必须和ActionForm中的get和set的属性一致

*/

public class LoginActionForm extends ActionForm {

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;

}

}

2)Action对象

[java] view
plaincopy

/**

* 登陆Action

* 负责取得表单数据、调用业务逻辑、返回转向信息

*/

public class LoginAction extends Action {

@Override

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

//接收前台传递过来的数据

LoginActionForm laf=(LoginActionForm)form;

//获取表单数据

String userName=laf.getUserName();

String password=laf.getPassword();



UserManager userManager=new UserManager();

try{

//调用业务处理对象的登陆方法

userManager.login(userName, password);

//将数据设置到request中,以在前台jsp中获取显示

request.setAttribute("userName", userName);

//成功则转向到成功界面

return mapping.findForward("success");

}catch(Exception e){

e.printStackTrace();

}

//失败则转向到失败界面

return mapping.findForward("error");

}

}

3、配置struts-config.xml文件

[html] view
plaincopy

<struts-config>

<form-beans >

<form-bean name="loginForm" type="com.tgb.struts.LoginActionForm" />

</form-beans>



<action-mappings>

<action path="/login" type="com.tgb.struts.LoginAction"

name="loginForm"

scope="request">

<forward name="success" path="/login_success.jsp" />

<forward name="error" path="/login_error.jsp" />

</action>

</action-mappings>

</struts-config>

解释:上面form-bean配置的就是第二步建立的LoginActionForm对象

Action配置的就是第二步建立的LoginAction对象,在其属性name指向的就是配置的form-bean。
forward就是要转向的前端页面
4、在界面调用

[plain] view
plaincopy

<form action="login.do" method="post">

<input type="text" name="userName" ><br>

<input type="text" name="password"><br>

<input type="submit" value="登陆">

</form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: