The map set is used to save the key-value pairs of request paths and class paths, and the corresponding requested resources are obtained through the reflection mechanism.
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 {
// Strong Conversion
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;
// Use reflection to get the instance through newinstance ()
Action = (Action) class. forname (Map. Get (PATH). newinstance ();
Action.exe cute ();
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
}
}
Through the above code, we can further enhance the configuration of relevant information through the xml configuration file. The above code is solved by the XML file,
There are two request paths,
/Primer/useraction. Action
/Primer/helloworldaction. Action
The configuration corresponding to the struts2.xml file is,
<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>
If another class needs to be configured under another package, for example
/Service/useraddservice. Action
// We can add a package based on the original one.
<Package namespaces "/service">
<Action name = "useraddservice. Action" class = "cn. itcast. Service. impl. useraddservice">
</Action>
</Package>
Before getting started with struts2