了解了struts2的相关知识并且搭建好了struts2开发环境后,我们就可以使用struts2技术来开发自己的web应用了。
下面是我用struts2技术编写的第一个web程序,请参照源码:
项目如图:
先看登陆页面index.jsp
<body>
<h2>这是第一个使用structs2开发的应用实例!</h2>
<form action="${pageContext.request.contextPath}/csdn/FirstStrutsDemo.action" method="post">
用户名:<input name="userName" type="text" /><br/>
密码:<input name="userPass" type="password" /><br/>
<input type="submit" value="登陆校验" />
</form>
</body>
在UserDaoImpl.java中有实现方法:
public User select(String userName, String userPass) {
User user = null;
conn =DBConn.getConnction();
String sql = "select userID,userName,userPass from user where userName =? and userPass=? ";
try {
ps = conn.prepareStatement(sql);
int index =1;
ps.setString(index++, userName);
ps.setString(index++, userPass);
rs = ps.executeQuery();
while(rs.next()){
user = new User();
user.setUserID(rs.getInt("userID"));
user.setUserName(rs.getString("userName"));
user.setUserPass(rs.getString("userPass"));
}
return user;
} catch (SQLException e) {
thrownew RuntimeException(e);
}finally{
DBConn.release(conn, ps, rs);
}
}
然后在:
FirstStrutsDemo.java里
publicclass FirstStrutsDemo extends ActionSupport{
UserDao ud = new UserDaoImpl();
private User user;
private String userName;
private String userPass;
public String getUserName() {
returnuserName;
}
publicvoid setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
returnuserPass;
}
publicvoid setUserPass(String userPass) {
this.userPass = userPass;
}
public User getUser() {
returnuser;
}
public String execute(){
String code =null;
user = ud.select(userName,userPass);
if(user!=null&&(userName!=null&&(!userName.equals("")))&&(userPass!=null&&(!userPass.equals("")))){
code = "lijizh1013";
System.out.println("登陆成功!!!!!!!!!");
}else{
code = "lijizh";
System.out.println("登陆失败!!!!!!!!!");
}
return code;
}
}
Web.xml文件中作如下配置:
<!-- 读取初始化struts2环境 读取struts.xml文件 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
接下来是一个struts.xml文件:
<struts>
<package name="struts" namespace="/csdn" extends="struts-default">
<action name="FirstStrutsDemo" class="www.csdn.net.FirstStrutsDemo" method="execute">
<result name="lijizh1013" >/StrutsHelloWorldResponse.jsp</result>
<result name="lijizh" >/StrutsHelloWorldRequest.jsp</result>
</action>
</package>
</struts>
最后是两个相应文件了,负责将处理的数据返回到jsp页面:
StrutsHelloWorldRequest.jsp:
<body>
<h2>这是第一个使用structs2开发的应用实例!</h2>
<h3>struts登陆失败!${user.userName}用户没有存在!!</h3>
</body>
StrutsHelloWorldResponse.jsp:
<body>
<h2>这是第一个使用structs2开发的应用实例!</h2>
<h3>struts登陆成功!!!</h3>
用户名:${user.userName}<br/>
密码:${user.userPass}
</body>
最终效果如下图所示: