1. 程式人生 > >Struts2專案的搭建過程

Struts2專案的搭建過程

Struts2搭建過程

1.使用Myeclipes,新建一個Web project 在這裡插入圖片描述 2.新建jsp頁面 在這裡插入圖片描述 jsp內頁面程式碼如下:

 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>註冊頁面</title>
  </head>
  <body>
  <form action="register" method="post">
   使用者名稱:<input type="text" name="name" /><br>
   性別:<input type="text" name="sex" /><br />
   	 <input type="submit" value="提交" /> 
   	 </form>
  </body>
</html>

3.在index.jsp裡邊寫跳轉後接受的使用者資訊頁面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>資訊展示頁</title>
  </head>  
  <body>
   使用者名稱:${requestScope.name }<br />
    性別:${requestScope.sex }  <br />
  </body>
</html>

4.在src檔案下新建一個class: 在這裡插入圖片描述

程式碼如下:

package com.hnpi.action;

public class RegisterAction{
	private String name;
	private String sex;
	
	public String getName(){
		return name;
	}
	public void setName(String name){
		this.name =name;
	}
	public String getSex(){
		return sex;
	}
	public void setSex(String sex){
		this.sex =sex;
	}
	public String execute(){
		return "success";
	}
}

5.在專案web-inf內的lib包裡邊新增Struts2需要的jar包 在這裡插入圖片描述 6.在web.xml中配置Struts2的過濾器 程式碼如下:

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

7.在src下新建一個配置檔案.xml檔案: 在這裡插入圖片描述 .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" extends="struts-default">
         <action name="index" class="com.hnpi.controller.RegisterAction" method="struts">
             <result name="success">/index.jsp</result>
         </action>
    </package> 
 </struts>

8.以上內容做完以後再把專案在Tomcat裡邊部署後就可以運行了。這樣一個簡單的Struts2專案的搭建就完成了。 (注意每個專案的專案名,檔名或者類名都要有意義要知道自己寫的是什麼)