Java Web框架------------------struts2(官网教程版HelloWorld)
我们都知道Struts是Java Web 常用的三大框架之一,另外还有Spring、Hibernate。学习Struts很有必
要!那么怎么学习呢?我的建议是:
1、对于英语能力还可以的人,学技术我们要从官网文档学起,再结合中文别人所写的论文、博客,视频
等。这样可以达到事半功倍的效果。
2、对于阅读英语稍微吃力的人,我们可以下载有道词典,再来本计算机专业英语书,不懂就查,但是,
我们决不能面对英文就退缩。因为官网的技术是最标准的,几乎所有的技术书都是根据官网的文档衍生
出来的。
下面我们就根据官网的文档,就Struts2.3.30版进行HelloWorld的编写。
首先在Eclipse上创建Dynamicn Web project,建立好之后,我的目录结构是这样的。
建立好目录结构之后,我们就要进行一些相关文件的配置了!
HelloWorld.java(其实就是一个action)
官网关于action是这样描述的:
When you submit a HTML form to the framework, the input is not sent to another server page, but to a Java class
that you provide. These classes are called Actions. After the Action fires, a Result selects a resource to render the
response. The resource is generally a server page, but it can also be a PDF file, an Excel spreadsheet, or a Java
applet window.
package tutorial; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport { private static final long serialVersionUID = 1L; public static final String MESSAGE = "Struts is up and running ..."; private String message; public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; } public void setMessage(String message){ this.message = message; } public String getMessage() { return message; } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>My Application</display-name> <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(该文件在上图的WEB-INF/classes目录下)
<?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="HelloWorld" class="tutorial.HelloWorld"> <result>/HelloWorld.jsp </result> </action> </package> </struts>
HelloWorld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <h2><s:property value="message" /></h2><!--获得action(HelloWorld.java)属性的值--> </body>
编写好之后,在Tomcat服务器上运行即可!