今天第一次学习strut,跟着jdk学习笔记,做了个简单demo。
发现了些问题
1. eclipse创建web project, 然后在项目点右键,选择myeclipse, enable struts, 系统会自动添加struts.config.xml 和web.xml
2. struts.config.xml
<action-mappings>
<action
path="/hello"
type="net.tuolian.struts.HelloAction">
<forward
name="helloUser" <!--此处不要写错名称 -->
path="/WEB-INF/hello.jsp"/>
</action>
</action-mappings>
里面的类名和地址不要写错
3. 编写HelloAction 必须继承struts.action类, 重写exectue方法
主要的逻辑,就是获取页面的parameter
逻辑处理,保存获取的参数
业务分发给相应的jsp页面
比如
request.setAttribute("userInfo", model);
return mapping.findForward("helloUser");
具体配置文件和代码如何。依次为web.xml, struts.config.xml, HelloAction.java
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<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>3</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
<action-mappings>
<action
path="/hello"
type="net.tuolian.struts.HelloAction">
<forward
name="helloUser" <!--此处不要写错名称 -->
path="/WEB-INF/hello.jsp"/>
</action>
</action-mappings>
</struts-config>
package net.tuolian.struts;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class HelloAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
// TODO Auto-generated method stub
String username = request.getParameter("user");
Map model = new HashMap();
if(username != null){
model.put("username", username);
}
else{
model.put("username", "nody");
}
request.setAttribute("userInfo", model);
return mapping.findForward("helloUser");
}
}