创建第一个struts2程序

一切从最简单的做起,困难的是到底能走多深。

本人三年工作经验,工作基本不用struts,工作中一直jsf, spring mvc, struts2从来都只是知道个大概,从不深究。开博客就是开始想记录一下自己感兴趣的,自己观察一下自己3年以来的改变,并无过多想法,至于它能改变我多少,我能坚持多久,就拭目以待。3年前曾经就看过struts2,遥想当年稚嫩的我,无名师指导让我一片迷雾,3年后再看他,对驾驭这批小马已感余裕。人就是在不知不觉中成长。

Struts2的Hello World

开发环境

1. STS 2.9.1

2. Maven  3.0

3. Tomcat 7.0

Maven  POM

在STS中创建一个maven-archetype-quickstart project.

struts2 的配置非常简单,在maven depnedency 里面加入这个就ok

<dependency>

<groupId> org.apache.struts</groupId >

<artifactId> struts2-core</artifactId >

<version> 2.3.15</ version>

</dependency>

成功后maven lib就是这样的

ScreenClip

Web.xml

 

以下这个图对struts的描述比较清晰了。客户初始化一个request之后,会进入一系列的过滤器(filter),然后会进入action mapper, mapper 会决定好要调用哪个action.

真要调用的话,FilterDispather会把请求交给ActionProxy,Action Proxy会通过配置管理从用户配置的struts.xml里面寻找合适的action 类。随之创建一个Action invocation实例。Invocation会经过一系列的拦截器之后调用Action,注意Action可以为简单的pojo,只需要存在execute方法即可。

Execute方法执行后返回result,师徒模板会根据配置内容返回适合的response回到用户浏览器。

注意绿色的是要用户修改的。简单来说,使用stuts框架和其他框架类似。只需要配置struts.xml,编写action的execute方法以及内在逻辑,根据模板构建视图。

ScreenClip(1)

有了以上基本概念,就不难理解web.xml里面这个filter的用处。在做这一步之前要在facet里面讲项目转成dynamic web project 3.0

<%@ page contentType= "text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri= "/struts-tags"%>

<html>

<head></ head>

<body>

<h1> please input your username </h1>

<s:form action= "Welcome">

<s:textfield name= "username" label ="Username" />

<s:submit />

</s:form>

</body>

</html>

JSP

用基本的jsp来测试一下

加入struts2 的taglib

<%@ taglib prefix="s" uri="/struts-tags" %>

 

logon.jsp

<%@ page contentType= "text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri= "/struts-tags"%>

<html>

<head></ head>

<body>

<h1> please input your username </h1>

<s:form action= "Welcome">

<s:textfield name= "username" label ="Username" />

<s:submit />

</s:form>

</body>

</html>

 

welcom.jsp

<%@ page contentType= "text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri= "/struts-tags"%>< html><head ></head>< body>

<h1> mxiao sample of struts 2</h1 >

<h4>

             欢迎使用struts2,

<s:property value= "username" />

</h4>

</body></ html>

Action

编写一个HelloAction,简单的记录用户的名字并返回成功。

package org.mxiao.struts.action;

public class HelloAction{

private String username ;

public String getUsername() {

return username ;

       }

public void setUsername(String username) {

this.username = username;

       }

// all struts logic here

public String execute() {

return "SUCCESS" ;

       }

}

struts.xml

这是struts的配置文件,如上图所示,可以标识出用户的那个request对用那个action和view,以下是最简单的例子。这个文件最后要在classpath中,所以放在resources里面。

 

以上就是建立一个基本struts程序的流程,项目结构如下:

ScreenClip(2)

访问网址

http://localhost:9084/Struts2Example/User/Login.action

ScreenClip(3)

ScreenClip(4)

posted @ 2013-07-15 23:36  萧大爷  阅读(686)  评论(0编辑  收藏  举报