HelloStruts2
很久没进行web开发,感觉快要忘光了,重拾起快遗忘的记忆,从struts2基础学起。 第一步,当然是从官网下载最新的struts2,地址http://struts.apache.org/,我习惯下载-all.zip,解压,准备开始第一个struts2。 第二步,打开MyEclipse,我用的是MyEclipse10,新建一个Dynamic web project工程,命名为“HelloStruts2”。 第三步,将解压后lib目录下的commons-logging-1.1.1.jar、freemarker-2.3.19.jar、ognl-3.0.5.jar、struts2-core-2.3.4.1.jar、xwork-core-2.3.4.1.jar,这个版本的struts2同时需要commons-fileupload-1.2.2.jar、commons-io-2.0.1.jar、commons-lang3-3.1.jar。这样子貌似可以了,但当运行时死活不行,网上查了后说仍需要一个不存在struts.zip里面的javassist-3.7.ga.jar.......这样在MyEclipse直接run on server运行通过,但部署到tomcat,通过tomcat运行的时候报了class cast异常,最终发现在tomcat的context.xml文件里面加入元素后总算可以正常运行了。 第四步,修改web.xml文件 [code="xml"] HelloStruts2 struts2 org.apache.struts2.dispatcher.FilterDispatcher struts2 /* [/code] 第五步,在HelloStruts2的WebContent文件夹下新建一个login.jsp文件 [code="jsp"] <%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 登录页面
username:
password:
[/code] 第六步,新建一个action,不用像struts1一样强制继承action,更容易维护和写单元测试,也不会与servletAPI联系过紧。 [code="java"] package cn.com.hellostruts2.action; public class LoginAction { 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; } public String execute() throws Exception { return "success"; } } [/code] 第七步,在src目录下新建一个struts.xml文件,MyEclipse可以替我们生成xml with struts,但我更偏向从struts2.zip解压包中的app文件夹中的war中解压提取一个struts.xml来使用。 [code="xml"] /result.jsp [/code] 第八步,在WebContent文件夹下新建一个result.jsp文件。 [code="jsp"] <%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> 登录成功页面 username:${requestScope.username }
password:${requestScope.password } [/code] 以上是代码的编写工作,测试的话可以直接通过MyEclispe集成tomcat,并用run on server来运行,或者右键点击HelloStruts2这个项目的名称,在菜单中选择myeclipse,再选择add and remove project,配置发布的地址就可以了。 最后,运行tomcat,打开浏览器,在浏览器中输入 http://localhost:8080/struts2/login.jsp 就可以了。 重拾struts2,发现很多东西都忘了,但还是觉得入门其实不难,用了框架,简化了很多的操作,以后继续认真学习web开发。