struts2-blank.war,放到tomcat的webapps下,重新启动会部署,在部署后,会产生practice_struts2
下载地址:http://pan.baidu.com/s/1jGKcvgq
一:加载Struts2类库
struts2-core-2.3.16.3.jar 框架的核心类库
xwork-core-2.3.16.3.jar XWork类库,构架基础
ognl-3.0.6.jar 使用的一种表达式语言类库
freemarker-2.3.19.jar 标签模板使用类库
commons-fileupload-1.3.1.jar 文件上传依赖包
commons-io-2.2.jar
javassist-3.11.0.GA.jar
commons-lang3-3.1.jar
二:配置web.xml
(将全部请求定位到指定的Struts2过滤器中)
1 <filter> 2 <filter-name>struts2</filter-name> 3 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter- 4 5 class> 6 </filter> 7 <filter-mapping> 8 <filter-name>struts2</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
(<url-pattern>/*</url-pattern>是所有的都走filter-class.)
(<url-pattern>*.action</url-pattern>是.action的才走filter-class.)
三:开发控制层
struts.xml的配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 <struts> 6 7 <package name="default" namespace="/user" extends="struts-default"> 8 <action name="loginAction" class="struts.loginAction"> 9 <result name="success" type="dispatcher">/user/Success.jsp</result> 10 <result name="error" type="dispatcher">/user/Error.jsp</result> 11 </action> 12 13 </package> 14 15 </struts>
(<package name="default" namespace="/user" extends="struts-default">
namespace是jsp所在的包名,extends是继承struts-default.xml的方法)
(<result name="success" type="dispatcher">/user/Success.jsp</result>)
接收返回的result的值,判断显示哪个jsp
四:显示层:UserLogin.jsp:
1 <form action="/practice_struts2/user/loginAction.action" method="post"> 2 3 用户名:<input name="username" type="text"><br/> 4 密 码:<input name="userpwd" type="password"><br/> 5 <input type="submit" value="登录"/><input type="reset" value="重置"/> 6 7 </form>
(<form action="/practice_struts2/user/loginAction.action" method="post">)
action里是/工程名+namespace+struts.xml里action的name,调用相对应的class
五:业务处理:
1 package struts; 2 3 import servlet.UserServlet; 4 import com.opensymphony.xwork2.ActionSupport; 5 public class loginAction extends ActionSupport { 6 7 private String username; 8 private String userpwd; 9 private UserServlet userservlet=new UserServlet(); 10 public String execute(){ 11 //业务功能的调用 12 System.out.println(username+userpwd); 13 boolean ret=userservlet.login(username, userpwd); 14 if(ret){ 15 //呈现数据,给struts.xml的result 16 return "success"; 17 }else{ 18 return "error"; 19 } 20 } 21 22 public String getUsername() { 23 return username; 24 } 25 public void setUsername(String username) { 26 this.username = username; 27 } 28 public String getUserpwd() { 29 return userpwd; 30 } 31 public void setUserpwd(String userpwd) { 32 this.userpwd = userpwd; 33 } 34 }
1 package servlet; 2 public class UserServlet { 3 public boolean login(String username,String userpwd){ 4 if(username.equals("111")&&userpwd.equals("111")){ 5 return true; 6 }else{ 7 return false; 8 } 9 } 10 }