struts2入门案例

来源:互联网 发布:关闭nagle算法 编辑:程序博客网 时间:2024/05/17 08:01

struts2所有的重复代码都交给前端控制器去调用完成和调度,开发者只需要在Aciton中编写业务处理相关代码即可。

这里主要介绍struts2入门案例,首先,笔者将struts2开发过程简化为以下6个步骤,想要进行struts2入门学习的朋友照着以下六个步骤进行学习就可以啦!

一.开发步骤和项目工程分析

1. 创建WEB工程

2. 导入必要jar包(struts2开发jar包)

3. 编写JSP页面

4. 编写Action代码处理逻辑

5. 进行框架配置web.xmlstruts.xml

6. 运行测试

接下来就是入门案例详解

1. 创建WEB 工程,笔者将这个web工程取名为strutstest,其实叫什么名字无所谓啦!

http://my.csdn.net/my/album/detail/1830415

2. 导入必要jar包(struts2开发jar包)

官网地址:http://struts.apache.org/

我会将这个教程中用到的struts包上传到资源库中,不想到官网中下载的朋友可以直接到我的资源库中进行下载,方便学习


导入到项目中


3. 编写JSP 页面

hello.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>请求</title></head><body><a href="${pageContext.request.contextPath }/helloAction.action">hello请求啦</a></body></html>
hello1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>响应页面</title></head><body>响应成功!!</body></html>

4. 编写Action代码处理逻辑

public class HelloAction implements Action{@Overridepublic String execute() throws Exception {System.out.println("后台执行代码!!!");return SUCCESS;}}

5. 进行框架配置web.xmlstruts.xml

web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <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></web-app>
struts.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="default" namespace="/" extends="struts-default"><action name="helloAction" class="com.huaqing.test.HelloAction"><result name="success">/jsp/hello1.jsp</result></action> </package></struts>

6. 运行测试





1 0