首页 > 代码库 > struts2学习入门前
struts2学习入门前
利用map集合来保存请求路径和和类的路径的键值对,通过反射的机制来得到相应的请求的资源。
package cn.itcast.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Struts2Filter implements Filter {
Map<String, String> map = new HashMap<String, String>();
public void init(FilterConfig config) throws ServletException {
map.put("/primer/userAction.action", "cn.itcast.action.UserAction");
map.put("/helloWorld/helloWorldAction.action", "cn.itcast.action.HelloWorldAction");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//强转
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
String path = req.getServletPath();
System.out.println("path = "+path);
if(path.equals("/test.jsp")){
chain.doFilter(req, res);
}else{
try {
Action action;
//利用反射,通过newInstance()得到实例化
action = (Action)Class.forName(map.get(path)).newInstance();
action.execute();
req.getRequestDispatcher("/success.jsp").forward(req, res);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void destroy() {
// TODO Auto-generated method stub
}
}
通过上面的代码我们可以进一步增强,通过xml配置文件来配置相关的信息。将上面众多代码由xml文件来解决,
下面有两个请求路径,
/primer/userAction.action
/primer/helloworldaction.action
对应到struts2.xml文件的配置就是,
<struts>
<package namespaces"/primer">
<action name="userAction" class="cn.itcast.action.UserAction">
<result name="success">/success.jsp</result>
</action>
<action name="helloworldAction" class="cn.itcast.action.HelloworldAction">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
如果在另外一个包下还有一个类需要配置,比如说
/service/userAddService.action
//那么我们可以在原来的基础上添加包就行了
<package namespaces"/service">
<action name="userAddService.action" class="cn.itcast.service.impl.UserAddService">
</action>
</package>
struts2学习入门前