在Struts Action对象中得到类似jsp页面application的ServletContext

今天需要把数据存在网站程序全局范围,需要在struts Aciton对象中得到 ServletContext对象,与jsp页面的application一样。在google中搜索到如下帖子。转帖于此:

How to get 'application' in Struts Action class? (转自:http://forum.java.sun.com/thread.jspa?threadID=609998&messageID=3346689

×××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××

How to get 'application' in Struts Action class?  

Mar 23, 2005 7:45 PM

Click to email this message

 

Hello,

I have a question on how to get 'application' in Struts Action class.

In the jsp file, i have set an application attribute:

<%

applicaiton.setAttribute("userId", "testUser");

%>

But how to get this application attribute in Struts Action class?

So far I only know how to get session in Struts Action class by using:

(HttpServletRequest)request.getSession();

 

[Dukes Earned 1425] evnafets

Posts:7,577

Registered: 29/04/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:08 PM (reply 1 of 2)

Click to email this message

 

The "application" in a JSP page is the ServletContext object.

In a standard servlet you can use

ServletContext application = getServletConfig().getServletContext();

In a Struts Action class, just have to get hold of the servlet first

ServletContext application = getServlet().getServletConfig().getServletContext();

Cheers,

evnafets

 

[Dukes Earned 0] nonameisname

Posts:24

Registered: 8/13/03

Re: How to get 'application' in Struts Action class?  

Mar 23, 2005 8:33 PM (reply 2 of 2)

Click to email this message

 

Hi evnafets,

Thanks a lot for your help. It works.

By the way, i found that it is possible to get ServletContext in Struts in two ways:

ServletContext application = getServlet().getServletConfig().getServletContext();

or

ServletContext application = getServlet().getServletContext();

Both work fine. Any concern about the 2nd way? It does not getServletConfig() but instead it straight away getServletContext().

*********************************************************************************************************

                       转帖完毕

也许是永远也搞不懂了的"bean:write"怪事

学习日记里有3个jsp文件,接受action送来的一个帖子列表,然后循环的用struts中<bean:write/>标记显示出来。

帖子中有一个在3个jsp文件中都有的属性名为"myLastUpdate",在文件:processGoal.jsp中一切正常,但在finishedGoal.jsp和quitedGoal.jsp中却在网站空间中报告帖子对象的一个myLastUpdate的getter方法抛出异常。而同样的文件在本地用Tomcat5.0正常。空间用的是resin2.*。

具体是这3个文件都有一段如下的代码在文件:processGoal.jsp中一切正常,但在finishedGoal.jsp和quitedGoal.jsp出问题:


...

      <td width = "10%" align="center">

        <bean:write name="anGoal" property="finishDate" scope="page" filter="false"/>

      </td>

 

      <td width = "10%" align="center">

        <bean:write name="anGoal" property="myLastUpdate" scope="page" filter="false"/>

      </td>

...

最后,实在找不到原因了,用了jstl中的<c:out/>标记来输出这个对象的"myLastUpdate"属性才全部正常。

如下所示:


...

      <td width = "10%" align="center">

        <bean:write name="anGoal" property="finishDate" scope="page" filter="false"/>

      </td>

 

      <td width = "10%" align="center">

        <c:out value="${anGoal.myLastUpdate}"/>

      </td>

...

这个问题实在是不应该,可就是出现了。也许是Struts中的<bean:write/>加上属性名myLastUpdate加上resin服务器这三者的偶然巧合出现了这个错误?如果有知道答案的朋友指点一下。

如果,你碰巧碰到这样的情况,不妨在jsp文件中改一下取得对象属性的方法,也许就解决了你磨破脑袋也找不到原因的问题。

在Struts的html:select标签中显示默认值(转)

转自:http://www.theserverside.com/discussions/thread.tss?thread_id=35726

Render default value for html:select in STRUTS

Posted by: Jiao Yu on ?? 07, 2005 DIGG

Hello,

I am trying to render the default value for html:select with STRUTS, but can't get it work correctly.

----------------------------------------------------------

Here are the component I have:

The JSP page to render the html:select

<%@ taglib prefix="req" uri="/WEB-INF/taglibs-request.tld" %>

<%@ taglib uri="/WEB-INF/c.tld" prefix="c" %>

<%@ taglib prefix="fmt" uri="/WEB-INF/fmt.tld" %>

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<head><title>eQuation 2.0</title></head>

<body>

<html:form action="/mappingAction" >

<table>

<c:forEach var="line" items="${mappingForm.map.matchColumnList}" >

<TR>

<TD><c:out value="${line.databaseColumnNameLabel}"/></TD>

<TD><c:out value="${line.excelColumnPosition}"/></TD>

<TD>

<html:select name="line" property="excelColumnPosition"

multiple="false" size="5" value="${line.excelColumnPosition}" >

<html:option value="" >No Match</html:option>

<html:optionsCollection name="mappingForm"

property="excelColumnList"

value="index"

label="columnName"/>

</html:select>

</TD>

</TR>

</c:forEach>

</table>

<html:submit value="Process"/>

</html:form>

</body>

----------------------------------------------------------

Here is the form setction for my STRUTS configuration xml:

    <form-bean name="mappingForm" type="org.apache.struts.action.DynaActionForm" >

     <form-property name="excelColumnList" type="rawdata.model.ExcelColumnNameBean[]"/>

     <form-property name="matchColumnList" type="rawdata.model.ColumnMatchBean[]" />

----------------------------------------------------------

Here are the definitions for the two beans used in the mappingForm:

public class ColumnMatchBean {

private String excelColumnName;

private String recommmendedDatabaseColumnName;

private String databaseColumnNameLabel;

private int excelColumnPosition;

...}

public class ExcelColumnNameBean {

private String columnName;

private int index;

...}

----------------------------------------------------------

Here is the action mapping used to populate the mappingForm and render the form in a JSP:

<action

            path="/loadMatchingColumn"

            type="rawdata.LoadMatchingColumnAction"

name="mappingForm"

attribute="mappingForm"

scope="session"

>

<forward name="success"

path="/../upload/showExcelColumns.jsp"

redirect="false"/>

</action>

----------------------------------------------

In LoadMatchingColumnAction, I populated both properties of the mappingForm,

For excelColumnList ( Array of ExcelColumnNameBean), I populated a couple of ExcelColumnNameBean ( with both columnName and index populated),

For matchColumnList ( Array of ColumnMatchBean, I populated a couple of ColumnMatchBean, ( with only recommmendedDatabaseColumnName and databaseColumnNameLabel populated),

Then I the showExcelColumns.jsp, I am going to render a couple of select lists with corresponding labels, see the details of the JSP at the beginning of this POST.

Here my questions come,

1)I can render the couple of select lists successfully, but for each of them, I would like to set a default value, I can't make this to work, although I set the value attribute in the select tag:

<html:select name="line" property="excelColumnPosition"

multiple="false" size="5" value="${line.excelColumnPosition}" >

I wrap select tag with C:foreach tags to render a group of select lists, and the problem seems to happen in

value="${line.excelColumnPosition}"

the correct predefined value can't be retrieved,

If I change "${line.excelColumnPosition}" to a specific number, let's say "2", then it works fine.

How can I get the correct value from line.excelColumnPosition?

2)My second question is: the select list rendered in the JSP page doesn't render a drop down list, but a select box, how can I make it a select drop down list?

Hope I have provided enough and clear information to explain my puzzles?

Thanks so much and have a good night,

Jiao

  Message #180699 Post reply Post reply Post reply Go to top Go to top Go to top

Check html:optionsCollection

Posted by: Cliff Liang on ?? 08, 2005 in response to Message #180569

I think you check the following and its tag doc first.

<html:optionsCollection name="mappingForm"

property="excelColumnList"

value="index"

label="columnName"/>

I guess each item in excelColumnList is the pair of index and value. You set value="index", so when you change "${line.excelColumnPosition}" to "2", it works fine.

Try to change to value="value", which is the value of excelColumnPosition is from.

Of course, html:select can be used for drop down list.

Hope it can help you.

Cliff Liang

  Message #180705 Post reply Post reply Post reply Go to top Go to top Go to top

RE:Render default value for html:select in STRUTS

Posted by: Jiao Yu on ?? 09, 2005 in response to Message #180569

Cliff,

Thanks for your reply. But I don't think that's the problem, since I already identified the issue under the help of a teammate.

The major issue here is that STRUTS doesn't work well with EL, so ${line.excelColumnPosition}" doesn't work well.

He suggests following options to fix the problem:

a)You must use runtime expression in the value parameter. I have not tested following code.

 

<bean:define id="defaultValue" name="line" property="excelColumnPosition"/>

<html:select name="line" property="excelColumnPosition" value='<%= defaultValue %>' >

b) Use Struts-EL library

c) Tomcat bundled with JBoss 4.0.2 is 5.5.x. It is Servlet 2.4 and JSP 2.0 compliant. You could change the web.xml to specify the 2.4 version of the servlet specification. EL expresions would be interpreted by the servlet container - Tomcat. The version 2.2 in web.xml does not interpret EL expressions for compatibility reasons.

 

Changing follow code:

“<!DOCTYPE web-app

  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

  "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">”

To

 

<?xml version="1.0" encoding="ISO-8859-1"?>

 

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

        version="2.4">

    ....

</web-app>

------------------------------------------

To dropdown list issue is also resolved, just omit the multiple attribute for select.

Thanks again and happy programming.

Jiao

  Message #180707 Post reply Post reply Post reply Go to top Go to top Go to top

Render default value for html:select in STRUTS

Posted by: Jiao Yu on ?? 09, 2005 in response to Message #180569

Hello,

Another tricky thing is :

The var attribute (mathchColumnList)in C:forEach tag, the property after map. for the items attribute (matchColumnList) in the C:foeEach tag, and the name attribute for the html:select tag should be all the same, otherwise, you can't get the POST data in the following action.

<c:forEach var="matchColumnList" items="${mappingForm.map.matchColumnList}" >

<TR>

<TD><c:out value="${matchColumnList.databaseColumnNameLabel}"/></TD>

<TD><c:out value="${matchColumnList.excelColumnPosition}"/></TD>

<TD>

<html:select name="matchColumnList" property="excelColumnPosition"

multiple="false" size="5" value="${matchColumnList.excelColumnPosition}" >

<html:option value="" >No Match</html:option>

<html:optionsCollection name="mappingForm"

property="excelColumnList"

value="index"

label="columnName"/>

</html:select>

Have a good night,

Jiao

问题:搞不懂HttpServletRequest的getCharacterEncoding()方法了

运行Struts中那个upload的例子,当使用那个upload-utf8.jsp上传文件时,上传后转到display.jsp时,显的总是乱码。就算在display.jsp中设置了<%@ page contentType="text/html; charset=utf-8" %>也没有用。

如下:

upload-utf8.jsp的设置:


<%@ page language="java" contentType="text/html; charset=gbk" %>

action:


            String encoding = request.getCharacterEncoding();

            System.out.println("the encoding is: "+ encoding);

            if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))

            {

                response.setContentType("text/html; charset=utf-8");

            }

虽然在upload-utf8.jsp中也指定了utf8编码,但是在request.getCharacterEncoding();得到的encoding总是null,也就是没有在request中没有指定编码,明明是指定了的呀?怪事。

还有,就是那个upload.jsp,在昨天的运行中还是在display.jsp中出现了乱码,可是今天却没有了,搞不懂,怪事。

struts在上传文件过程中如何自动建立文件夹(转)

转自:http://bbs.chinajavaworld.com/thread.jspa?messageID=724084&tstart=0

 struts上传文件问题

发表于: 2006-5-23 下午9:27         回复 

 

struts在上传文件过程中如何自动建立文件夹?并根据上传的文件名存入不同的文件夹中?如果能有具体的例子代码更好。请各位多多指教,十分感谢!

 

·Hibernate查询出错 

 

chenyanji 

 

 

发表: 268

点数: 80

来自: 北京

注册: 05-3-1 

  Re: struts上传文件问题

发表于: 2006-5-26 下午11:53    原帖: springlet         回复 

 

还是应该用FILE处理吧

 

POPO帐号:yanji94521 QQ:309157714 MSN:yanji94521@hotmail.com 欢迎加入IT交流QQ群:5468368

 

·不需要编写actionForm、action来完成struts架构。 

 

gzxthebest 

 

 

发表: 9

点数: 100

注册: 05-9-23 

  Re: struts上传文件问题

发表于: 2006-5-29 上午1:16    原帖: springlet         回复 

 

自动创建文件夹?还真没实现过,关注中

 

·关于jsp页面执行问题 

 

test_1982 

 

发表: 116

点数: 100

注册: 05-7-26 

  Re: struts上传文件问题

发表于: 2006-5-29 下午1:30    原帖: springlet         回复 

 

可以通过file对象创建文件夹的。

1: 如果不存在{

File file = new File("d:/testD");

file.mkdir();

}

这样就创建了一个文件夹。后面的你应该知道如何递归的创建文件夹了吧。

 

Knowing how to make the one of the most abilities counts for much more

 

·大家好 关于3gp文件的转换 

 

Forward on committed response错误

原来用struts1.1使用如下注释掉的代码一切正常,

 


if (target.equals("messageSuccess")) {

/*// changed Struts version from 1.1 to 1.2.9, this will generate error: Forward on committed response

PrintWriter out;

response.setContentType("text/html;charset=utf-8");

out = response.getWriter();

out.println(

"<script language=\"JavaScript\" type=\"text/javascript\">");

out.println("alert(\"感谢您对本站提出的宝贵意见和建议!回复见公告牌中的'回复网友留言集'。\")");

out.println("</script>");

out.flush();

*/

request.setAttribute("isMessage", "true");

}

换为struts1.2.9后就出现:Forward on committed response错误(Tomcat5.0控制台debug);在网站上运行resin2.1.12在页面上报错:

500 Servlet Exception

java.lang.IllegalStateException: forward() not allowed after buffer has

committed.

at com.caucho.server.http.QRequestDispatcher.forward(QRequestDispatcher.java:131)

at com.caucho.server.http.QRequestDispatcher.forward(QRequestDispatcher.java:103)

at com.caucho.server.http.QRequestDispatcher.forward(QRequestDispatcher.java:80)

at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1085)

at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:398)

at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:241)

at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)

at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:165)

at javax.servlet.http.HttpServlet.service(HttpServlet.java:103)

at com.caucho.server.http.FilterChainServlet.doFilter(FilterChainServlet.java:96)

at com.learndiary.website.util.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:102)

at com.caucho.server.http.FilterChainFilter.doFilter(FilterChainFilter.java:88)

at com.caucho.server.http.Invocation.service(Invocation.java:315)

at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:346)

at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:274)

at com.caucho.server.TcpConnection.run(TcpConnection.java:139)

at java.lang.Thread.run(Thread.java:595)

--------------------------------------------------------------------------------

Resin 2.1.12 (built Tue Dec 9 14:58:25 PST 2003)

经过查资料,发现是PrintWriter已经返回用户数据后,就不能再forward到其它页面了。也就是这个错误:

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward. forward应当在响应提交给客户端之前调用(响应体输出被刷新前)。如果响应已经被提交,该方法抛出IllegalStateException。响应缓存中未提交的输出在转发之前自动清空。

所以就不在Action中写提示信息了,而把其移动jsp页面,如下:


  <c:if test="${requestScope['isMessage'] == true }">

   <script language="JavaScript" type="text/javascript">

    alert("感谢您对本站提出的宝贵意见和建议!回复见公告牌中的'回复网友留言集'。")

   </script>

  </c:if>

同时,我发现如果在Action中用的是request.setAttribute("isMessage", "true");

则在页面中可以  <c:if test="${requestScope['isMessage'] == true }">

注意,上面的“true”是没有加引号的,可能这就是c:if的boolean类型吧,我也没有去查资料;

但是,如果为:request.setAttribute("isMessage", "otherString");

则必须这样:  <c:if test="${requestScope['isMessage'] == \"otherString\"); }">

就是要加双引号,而且要进行转意。

jsp页面引用Action中的变量

<c:if test="${param.typeID == 2 && requestScope['parentArtVisibility']==0}">只能引用request作用域的变量parentArtVisibility

<c:if test="${param.typeID == 2 && parentArtVisibility==0}">可以引用任何作用域的变量parentArtVisibility

html:radio 标记中怎么样指定一个初始值(默认值)?

  <tr> 

  <td width="100%" align="center">

    <input type="radio" name="visibility" value="0" checked="checked">公开目标  

    <input type="radio" name="visibility" value="1">私人目标</td>

    <!--

     <html:radio property="visibility" value="0"/>公开目标  

     <html:radio property="visibility" value="1"/>私人目标</td>

    -->

 </tr>

如上,怎么样在struts中的html:radio 标签中达到html 中<input type="radio" name=... checked="checked"...的效果?

疑问:关于使用Validator框架后,显示错误信息的问题。

 我发现:使用Validator框架后,

只能使用<html:errors/>显示错误信息,

不能使用诸如:<html:errors property="error1"/>显示指定的错误信息。

我现在需要这样显示错误,

比如:用户名没有填写的话,只在用户名旁边显示错误信息;

如果Email填写不符合标准,只在Email旁边显示错误信息。

我不希望把所有错误都一起显示出来。

可以用Validator实现吗?

因为我不知道如何实现那个目的,

所以,只好把验证的部分放到ActionForm的validate方法中,

这样就可以指定每一个不同的错误信息,以便在错误页面按要求显示了。

可是,每个验证逻辑都需要自己来写,

org.apache.struts.validator.FieldChecks这个类是Validator框架使用的验证类,

里面有很多现成的方法,由于我没有使用这个框架,

所以就无法使用这些现成的方法了(也可能是我不知道如何使用)。

我想知道:有没有现成的验证方法可以下载到?

例如必填、合法日期、合法Email等等。

请前辈指点。

开始Struts的日记。

今天终于对《Jakarta Struts编程》看了一个大概,

准备搭建一个环境进行进一步学习。

我将下载的status-1.2.7.tar.gz解压缩后,

把lib目录中的status.jar、jstl.jar和standard.jar拷贝到了WEB-INF的lib目录中,

起动服务器后,竟然一个劲儿的抛出异常,

郁闷死……

最后,把所有的jar文件都拷贝到WEB-INF的lib目录后,

才解决了问题。

回过头再看书,才发现,

书上已经写的很明白了,只怪当时没有注意到。

看来,看书还是要仔细一些。

又或是,水平不够,所以注意不到书上说的内容的重要性。