Struts 入門(一) 搭建Struts環境

 

 

eclipse中建立項目  html

搭建步驟:java

1.建立web項目web

2.下載導入相關jar包apache

3.建立並完善相關配置文件瀏覽器

4.建立(控制器)Action 並測試啓動tomcat

 

 

 

1.文件--新建--動態web項目服務器

 給項目起一個名字  而後選擇項目的服務器運行環境  這裏須要添加tomcat的目錄  有的話請忽略app

而後一直下一步  完成   這樣就建立了一個java web項目eclipse

 

 2.引入Struts須要的jar包  jsp

 

 須要訪問apach struts的下載網站

1.http://struts.apache.org/

解壓下載的壓縮包  從lib裏面選擇下面的幾個基礎包  拷到項目的WEB-INF 下的lib中 

 

 

而後將導入的包添加引用到項目中

 

選擇Add  JARs 添加jar包

而後全選下  點擊OK就行了

配置相關文件

 (1)web.xml 的配置(添加一個過濾器filter)

 

 <filter>
  	<filter-name>struts</filter-name>
  
  	<filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>struts</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

  (2)建立struts核心文件--struts.xml 

 

1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd" >
3 <struts>
4  
5 </struts>

完成配置文件

4.建立一個Action(class文件)

 

建立一個類文件  繼承com.opensymphony.xwork2.ActionSupport

這樣就建立了一個Action 類文件 

1 package com;
2 
3 import com.opensymphony.xwork2.ActionSupport;
4 
5 public class HelloWorld extends ActionSupport {
6 
7 }

建立完成以後如何去執行它的方法呢     這裏struts2有一個默認的方法 

 

 

或者在action中 alt+/   找到execute 方法 而後在裏面打印輸出一句話

package com;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorld extends ActionSupport {

    @Override
    public String execute() throws Exception {
        System.out.println("執行Action");
        return SUCCESS;
    }
    
}

而後咱們繼續配置咱們的struts.xml 文件

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

  result默認是返回sucess的 

 而後咱們建立返回顯示的file   result.jsp

 

 

<%@ page language="java" contentType="text/html; 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>Insert title here</title>
</head>
<body>
  這是result.jsp
</body>
</html>

到此 咱們一個項目就簡單配置完成了

而後咱們發佈下  選擇項目右鍵  Debug As --Debug on Server   選擇咱們的tomcat服務器  而後完成

 

而後在瀏覽器中訪問網址:http://localhost:8080/StrutsDemo/HelloWorld.action

這樣咱們就完成了在eclipse中的簡單搭建

相關文章
相關標籤/搜索