第17章 J2EE SSH基础学习-struts2应用概述

在Servlet编程学习中中,我们发现在处理大部分数据封装和存储代码都是拷贝和粘贴的操作。所以那么我们能不能将这些无聊的拷贝工作抽象出来封装成方法,然后缩减我们工作的负荷。同时我们对于各种数据回显和传递业务都聊熟于心之后,感觉就是增加工作量,但是技术含量却没变。

Struts就是针对jsp对象数据对象回显工作进行开发的一个工具。


对于数据库的一些增删改查操作,大多是拷贝和粘贴工作,那么我们能不能考虑使用简单的对象数据封装工具来代替我们平时的拷贝粘贴工作呢?Hibernate应运而生,我们只需要配置一些配置文件,然后以少量的代码实现数据的存储操作,替代我们平时servlet数据存储工作。

对于后台的一些无状态类,我们没有必要创建很多实例,例如创建数据库连接,我们没必要每次请求都做一次数据库连接操作,同时dao层的数据存储也是无状态的类,所以Spring提供了一些类似于池操作的工具,我们在程序启动时候便创建了一定量的对象,当我们需要的时候,自动获取这些类对象,当我们使用结束之后,自动归还这些存储对象。这可以极大的提升我们的程序运行效率。也就是使得程序能够达到负载均衡的效果。

(注:我们使用Struts hibernate Spring等框架技术是建立在我们足够理解Servlet工作原理的情况下,再接触的作业框架。但是servlet还是基础。)

struts:1.x版本

10-20种表现层MVC框架,struts的性能以及稳定性各方面都处于领先地位,大量软件公司都使用这个软件,属于行业标准。

webwork MVC框架。

struts下载地址:http://struts.apache.org/download.cgi#struts2516

需要导入到Struts项目中lib下的jar包列表:


在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>StrutsDemo-20180523</display-name>
  
  <!-- Filters 过滤器 
  	过滤器在系统启动的时候,会自动实例化,进入工作状态,根据过滤规则,对任何符合该规则的web访问进行过滤操作。
 	struts2就是通过一个过滤器执行任务的。
 	该过滤器工作的时候,主要查看该访问是否应该归struts2处理,如果是,则执行规则处理。否则忽略该访问
  	既定规则书写在struts.xml文件中,该文件如果没有特殊指定,只能放在src目录下。
  -->
  <!-- START SNIPPET: filter -->
  	<filter>
  		<filter-name>action2</filter-name>
  		<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  	</filter>
  	<!-- end snippet :filter -->
    <filter-mapping>
    	<filter-name>action2</filter-name>
   		<url-pattern>/*</url-pattern><!-- 对任何web访问地址,都将执行struts2过滤 -->
    </filter-mapping>
 
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

i下面以计算某范围内数据和为例:强调:jsp中要导入struts标签需要导入加入标签代码:<%@ taglib uri="/struts-tags" prefix="s" %>

calc_sum.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>

<%
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>Calc sum</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style>
		.errorMessage{
			color:red;
			list-style-type:none;
			<%-- float:left;--%>
		}
	</style>
  </head>
  
  <body>
    <h3>计算某范围数字和</h3>
    <s:form namespace="/work" action="sum" method="post">
    	<div>
    		<span>开始范围:</span>
    		<s:textfield name="beginScope"></s:textfield>
    		<s:fielderror class="errorMessage" name="errMsgBegin"></s:fielderror>
    	</div>
    	<div>
    		<span>结束范围:</span>
    		<s:textfield name="endScope" ></s:textfield>
    		<s:fielderror class="errorMessage" name="errMsgEnd"></s:fielderror>
    	</div>
    	
    	
    	<div>
    		<s:submit value="计算"></s:submit>
    	</div>
    </s:form>
  </body>
</html>

struts项目中常用action代替servlet的控制文件;

CalculateAction.java    这个文件需要继承ActionSupport类

/**
 * 工  程   名:StrutsDemo-20180523	<br>
 * 文  件   名:CalculateAction.java	<br>
 * 工具包名:edu.fjnu.stuwork.action	<br>
 * 功能描述:TODO	<br>
 * 创建时间:2018年5月23日 下午5:48:49	<br>
 * 版本信息:V1.0
 * @创建人:周开伦	
 */
package edu.fjnu.stuwork.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 类名:CalculateAction	<br>
 * 功能描述:	<br> 
 * 创建日期:2018年5月23日 下午5:48:49	<br>
 * 修改备注:
 * @作者信息:Zhou kailun	<br>
 */
public class CalculateAction extends ActionSupport {
	/**开始范围*/
	private int beginScope;
	/**结束范围*/
	private int endScope;
	/**计算结果*/
	private int sum;
	
	public String execute()throws Exception{
		sum=beginScope+endScope;
//		System.out.println("begin:"+beginScope+" end:"+endScope+" sum:"+sum);
		if(this.beginScope<=10){
			this.addFieldError("errMsgBegin", "开始范围不能小于10");
			this.beginScope++;
			return INPUT;
		}
		if(this.endScope>100000){
			this.addFieldError("errMsgEnd", "结束范围不能大于100000");
			this.endScope--;
			return INPUT;
		}
		
		for(int i=beginScope;i<endScope;i++){
			sum+=i;
		}
		return SUCCESS;
	}
	/**<p>构造函数:</p><br><br>
	 * <p>描述:</p><br> 
	 */
	public CalculateAction() {
		// TODO Auto-generated constructor stub
	}
	public int getBeginScope() {
		return beginScope;
	}
	public void setBeginScope(int beginScope) {
		this.beginScope = beginScope;
	}
	public int getEndScope() {
		return endScope;
	}
	public void setEndScope(int endScope) {
		this.endScope = endScope;
	}
	public int getSum() {
		return sum;
	}
	public void setSum(int sum) {
		this.sum = sum;
	}

}


运行struts项目需要配置struts.xml文件

如下是案例:

<?xml version="1.0" encoding="UTF-8" ?>
<!--
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
-->
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "http://struts.apache.org/dtds/struts-2.5.dtd">


<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>
	<constant name="struts.devMode" value="false"></constant> <!-- 在网页中以开发模式打开,用于程序员直接在网页中查看运行情况 -->
	<constant name="struts.action.extension" value="do,action"></constant> <!-- 如果没有显示配置,默认为action, -->
	<constant name="struts.ui.theme" value="simple"></constant><!-- Struts 生成的UI界面代码风格,我们一般希望是自己能控制的。但是也可以一局各单位公司不同,有不同风格 -->
	<!-- 
	  http://localhost:8080/strutsDemo/work/demo.do
	  1.struts过滤器拦截到url地址,获得该url的后缀,如果是*.do,则为struts处理范畴。去掉猴嘴,获得实体路径。
	  2.取得包路径(最后一个/之前的路径)/work
	  3.获得action的名字demo,然后找到这个action,创建该action的实例。执行execute方法一次。
	  
	 -->
	<package name="pkg" namespace="/work" extends="struts-default">
		<action name="demo" class="edu.fjnu.stuwork.action.DemoAction"><!-- action是struts基本处理单位,用来代替servlet。其只能放在包中。 -->
		
		</action>
		<action name="sum" class="edu.fjnu.stuwork.action.CalculateAction">
			<result name="input">/calc_sum.jsp</result>
			<result name="success">/success.jsp</result>
		</action>
	</package>
</struts>

下面是一些附属文件:

success.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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>My JSP 'success.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	calc sum result page....
  	<h3>计算结果:</h3>
  	<s:property value="beginScope"/>+....+<s:property value="endScope"/>=<s:property value="sum"/>
  </body>
</html>

log4j.xml配置文件可以帮助我们查看项目调试运行状态:

<?xml version="1.0" encoding="UTF-8"?>
<!--
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
-->
<Configuration>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="com.opensymphony.xwork2" level="info"/>
        <Logger name="org.apache.struts2" level="info"/>
        <Logger name="org.demo.rest" level="debug"/>
        <Root level="info">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

猜你喜欢

转载自blog.csdn.net/qq_36346496/article/details/80419547