共 18篇 前 4 页:    每页5篇 下一页  

struts学习

这些东西经常用,贴出来以便查询。
1、struts中的常量类(时间<1>)
package struts.news;

import java.text.*;
import java.util.*;
public final class Constants {
// Session keys
    public static final String DATASOURCE_KEY =
"mysqlDB";
    public static final String LOGIN_USERNAME_KEY =
"username";
    public static final String NEWS_LIST_KEY =
"newslist";
    public static final String NEWS_DETAIL_KEY =
"newsDetail";
              
//system date
    public static final String getDate(){
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
        String cdate = sdf.format(cal.getTime());
        
//System.out.println("times is :"+cdate);
return cdate;
}
}
2、时间<2>
java.util.Date date=new java.util.Date();
int yyyy=1900+date.getYear();
int mm=date.getMonth()+1;
int dd=date.getDate();
int hh=date.getHours();
int mi=date.getMinutes();
int ss=date.getSeconds();
String theDate= yyyy+
"-"+mm+"-"+dd;
String theDates= yyyy+
"-"+mm+"-"+dd+" "+hh+":"+mi+":"+ss;
lunzi   2006-06-16 19:20:34 阅读:1466  评论:0  引用:0
struts 的Validator应用需要配置的关键地方.
struts-config.xml
<?xml version=
"1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
  <data-sources />
  <form-beans >

    <form-bean name=
"userForm" type="org.apache.struts.validator.DynaValidatorForm">
    <form-property name=
"name" type="java.lang.String" />
    </form-bean>


</form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings >
  
  <action
    
  attribute=
"userForm"
    
  input=
"post.jsp"
      
  name=
"userForm"
      
  path=
"/user"
    
  scope=
"request"
    
  type=
"com.lunzi.struts.action.UserAction" />


  </action-mappings>

  <message-resources parameter=
"com.lunzi.struts.ApplicationResources" />
  <plug-in className=
"org.apache.struts.validator.ValidatorPlugIn">
    <set-property property=
"pathnames"
    value=
"/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
  </plug-in>
  
</struts-config>

<?xml version=
"1.0" encoding="iso-8859-1"?>
<!DOCTYPE form-validation PUBLIC
          
"-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
          
"http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
validation.xml        
<form-validation>
   <formset>
      <form name=
"userForm">
         <field
           property=
"name"
           depends=
"required,,minlength,maxlength">
     <arg0 key=
"label.username"/>    
         <arg1 key=
"${var:maxlength}" resource="false" />
<arg2 key=
"${var:minlength}" resource="false" />
         <var>
           <var-name>maxlength</var-name>
           <var-value>10</var-value>
         </var>
<var>
           <var-name>minlength</var-name>
           <var-value>5</var-value>
         </var>
       </field>          
      </form>            
   </formset>  
</form-validation>
post.jsp

<%@ page language=
"java"%>
<%@ taglib uri=
"http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>
<%@ taglib uri=
"http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html>
<head>
<title>JSP for userForm form</title>
</head>
<body>
<html:form action=
"/user">
name : <html:text property=
"name"/><html:errors property="name"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</htm
lunzi   2006-06-15 14:32:55 阅读:1142  评论:0  引用:0
今天用struts的validate,出现了错误,使用代码如下:
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((name == null) || (name.equals(""))){
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionError("error.name.required"));
}
return errors;
}
其中的ActionError弄成了ActionMessage就出现了类型不匹配错误,struts版本不一样也会出这样的错.
参考资料
lunzi   2006-06-13 01:07:33 阅读:1691  评论:5  引用:0
今天花了点时间学习了一下struts的commons-fileupload.jar,在网上找了个例子,用MyEclipse重新开发了一个,大约用时两个小时,算是ok了!下面是系统应用的部分代码:
UploadsActionAction.java

  
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl

package struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import struts.form.UploadsActionForm;
import org.apache.struts.upload.FormFile;
import java.io.*;
/**
* MyEclipse Struts
* Creation date: 06-11-2006
*
* XDoclet definition:
* @struts.action path="/uploadsAction" name="uploadsActionForm" input="/form/uploadsAction.jsp" scope="request" validate="true"
*/

public class UploadsActionAction extends Action {

// --------------------------------------------------------- Instance Variables

// --------------------------------------------------------- Methods

/**
* Method execute
* @param mapping
* @param form
* @param request
* @param response
* @return ActionForward
*/

//UploadsActionForm uploadsActionForm = (UploadsActionForm) form;
public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
throws Exception {

String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase(
"utf-8")))
{
response.setContentType(
"text/html; charset=gb2312");//如果没有指定编码,编码格式为gb2312
}
UploadsActionForm theForm = (UploadsActionForm ) form;
FormFile file = theForm.getFiles();
//取得上传的文件
try {
InputStream stream = file.getInputStream();
//把文件读入
String filePath = request.getRealPath(
"/upload");//上传到指定的upload包中
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath +
"/" +
                               file.getFileName());
//建立一个上传文件的输出流
//System.out.println(filePath+"/"+file.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
//将文件写入服务器
}
bos.close();
stream.close();
}catch(Exception e){
System.err.print(e);
}
//request.setAttribute("dat",file.getFileName());
return mapping.findForward(
"display");

}

}

UploadsActionForm.java

//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.1.1/xslt/JavaClass.xsl

package struts.form;

import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

/**
* MyEclipse Struts
* Creation date: 06-11-2006
*
* XDoclet definition:
* @struts.form name="uploadsActionForm"
*/

public class UploadsActionForm extends ActionForm {
  
//public static final String ERROR_PROPERTY_MAX_LENGTH_EXCEEDED = "org.apache.struts.webapp.upload.MaxLengthExceeded";

// --------------------------------------------------------- Instance Variables

/** theFile property */
protected FormFile files;

// ---------------------------------------------------------

/**
* Returns files.
* @return FormFile
*/

public FormFile getFiles() {
return files;
}

/**
* Set the files.
* @param files The files to set
*/

public void setFiles(FormFile file) {
this.files = file;
}

}

上传用的页面:uploadFile.jsp

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

<html>
<head>
<title>JSP for uploadsActionForm form</title>
</head>
<body>
<html:form action=
"/uploadsAction" enctype="multipart/form-data"> <1>
theFile : <html:file property=
"files"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
刚开始<1>处落下了
"enctype="multipart/form-data" 费了我不少时间才搞定.

lunzi   2006-06-11 15:32:11 阅读:28917  评论:14  引用:0
最近在使用struts开发项目时遇到这样一个问题,就是页面提示信息是乱码,由于页面提示信息及<bean:message key="xx"/>的信息都来自于MyResource_zh.properties,同样条件下的,<bean:message key="xx"/>却正常,很不明白其原由,现在才发现其中原因原来是字符集使用不统一,通过查资料解决方法如下:
1)所有jsp页面均要用
<%@ page language="java" contentType="text/html; charset=GBK" %>
指出当前页面的charset
(2)用notepad等工具(而不是Eclipse Editor)编写中文资源文件,比如ApplicationResources_xx.properties。然后用工具native2ascii将资源文件中的中文字符转换为GBK,方法是在DOS下
  native2ascii -encoding GBK ApplicationResources_xx.properties ApplicationResources_zh.properties
   ApplicationResources_zh.properties是统一转码后的文件
我试过了解决了原来的乱码问题.
还发先了一篇不错的解决struts中文乱码问题的文章各种形式的乱码比较全面.
lunzi   2006-05-29 23:44:12 阅读:1254  评论:1  引用:0

使用DispatchAction的代码:
package hb;

import java.util.List;

import org.apache.struts.action.Action;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionMessage;


import javax.servlet.ServletContext;
import javax.sql.DataSource;
import javax.servlet.http.*;


public final class LoginAction extends DispatchAction {
    
    public ActionForward login(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
              
        UserForm userform = (UserForm) form;        
String name = userform.getName();

if(UserDAO.chkUserName(name)>0){

   return (mapping.findForward(
"successed"));//登陆成功
  }
        else{return mapping.findForward(
"failed");}  

    }
    
    public ActionForward addUser(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
              
        UserForm userform = (UserForm) form;        
String name = userform.getName();

UserDAO userDao=new UserDAO();
         userDao.saveName(name);

   return (mapping.findForward(
"successed"));   

    }
    
    public ActionForward getUser(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response)
    throws Exception {
    
        HttpSession session = request.getSession(true);      
        UserForm userform = (UserForm) form;        
String name = userform.getName();
List list=null;

UserDAO userDao=new UserDAO();

list=userDao.getGbooks();
    session.setAttribute(
"userList",list);

   return (mapping.findForward(
"successed"));   

    }

}
LoginActionstruts-config.xml中的部署:
<action-mappings>
<action path=
"/login" type="hb.LoginAction" name="formBean1" scope="request" validate="false"  input="/error.jsp" parameter="method"/>
        <action path=
"/regist" forward="/addUser.jsp"/>
login.jsp相关代码:
<form action=login.do?method=addUser method=
"post">
<bean:message key=
"item.username"/>
<input size=
"15" name="name">addUser<p>
<html:submit>
<bean:message key=
"item.submit"/>
</html:submit>
</form>
<a href =
"login.do?method=getUser">getUser</a>



lunzi   2006-05-27 00:03:42 阅读:1872  评论:1  引用:0
              
其实中文问题挺好解决的,关键的就两个地方设置对了就ok了。
第一、
1、struts+jdbc情况下:
EncodeActionServlet继承ActionServlet
package classmate;

import org.apache.struts.action.*;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class EncodeActionServlet extends ActionServlet
{
    protected void process(
        HttpServletRequest request,
        HttpServletResponse response)
        throws IOException, ServletException
    {
        HttpSession session = request.getSession(true);
        if (session.isNew())
//session超时
        {
            response.sendRedirect(
"/logout.jsp");
            return;
        }
        request.setCharacterEncoding(
"latin1"); //进行统一的中文转码latin1  <1>
        super.process(request, response);
    }
}
EncodeActionServlet在web.xml完成部署

  <!-- Action Servlet Configuration -->
  <servlet>
    <servlet-name>actionServlet</servlet-name>
    <servlet-class>classmate.EncodeActionServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Action Servlet Mapping -->
  <servlet-mapping>
    <servlet-name>actionServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
还有一个关键的部分是在struts-config.xml中的数据库连接部分如下:
<data-sources>
<data-source key=
"oracleDB1" type="org.apache.commons.dbcp.BasicDataSource">
<set-property property=
"driverClassName"
value=
"org.gjt.mm.mysql.Driver" />
<set-property property=
"url"
value=
"jdbc:mysql://localhost/struts?
                useUnicode=true&amp;characterEncoding=latin1
" />  <2>
<set-property property=
"maxActive"
value=
"5"/>
<set-property property=
"username"
value=
"root"/>
<set-property property=
"password"
value=
"123456"/>
<set-property property=
"autoCommit"
value=
"true"/>
</data-source>
</data-sources>
2、如果是struts+hiberante就在hibernate.cfg.xml的配置的数据库连接部分如下:
<?xml version=
"1.0" encoding="GB2312" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration
DTD
//EN" "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name=
"hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<!-- ?useUnicode=true&amp;characterEncoding=UTF-8 -->
    <property name=
"hibernate.connection.url">jdbc:mysql://localhost/struts?
              useUnicode=true&amp;characterEncoding=latin1</property>  <3>
    <property name=
"hibernate.connection.username">root</property>
    <property name=
"hibernate.connection.password">123456</property>
    
    <property name=
"show_sql">true</property>
    <property name=
"dialect">net.sf.hibernate.dialect.MySQLDialect</property>
    <mapping resource=
"hb/User.hbm.xml" />
  </session-factory>
</hibernate-configuration>
第二、还是在struts+jdbc下用自己的RequestProcessor去控制。
MyRequestProcessor.java
package StudyNews;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.RequestProcessor;

import org.apache.struts.config.ForwardConfig;
import org.apache.commons.logging.Log;


public class MyRequestProcessor extends RequestProcessor {

public MyRequestProcessor() {}

protected boolean processPreprocess( HttpServletRequest request,
                                     HttpServletResponse response ){

try{
   request.setCharacterEncoding(
"latin1");//此处为自己用的数据库的字符集 <4>

}
catch(Exception ex){
System.out.println(
"字符集设置失败");

}

return true;
}

}
它在struts-config.xml中配置如下:
<controller processorClass=
"StudyNews.MyRequestProcessor" />
数据库连接方面和上面一样。

总结:关键是<1><2><3><4>处的字符集设置要与自己数据库用的字符集一致。以前在struts
框架下往数据库插入中文失败的原因在于只设置了<1>处而没设置<2>处。









      
lunzi   2006-05-26 00:49:06 阅读:8354  评论:2  引用:0
                            
LoginAction.java
package hb;

import java.util.List;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.ActionMessage;

import javax.servlet.ServletContext;
import javax.sql.DataSource;
import javax.servlet.http.*;

public final class LoginAction extends Action{  
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws HibernateException {


   UserForm userform = (UserForm) form;        
String name = userform.getName();

HttpSession session = request.getSession(true);

String action=request.getParameter(
"action"); //动作类型

List list=null;

session.setAttribute(
"name",name);  

if(action==null)action=
"login";

if(
"login".equals(action)){ //登录操作
  if(UserDAO.chkUserName(name)>0){

   return (mapping.findForward(
"successed"));//登录成功
  }
  
}

   if(
"addUser".equals(action)){ //增加记录操作
  
         UserDAO userDao=new UserDAO();
         userDao.saveName(name);

   return (mapping.findForward(
"successed"));

  }
  
   if(
"getUser".equals(action)){ //取出记录操作
  
         UserDAO userDao=new UserDAO();
         list=userDao.getGbooks();
             session.setAttribute(
"userList",list);
   return (mapping.findForward(
"successed"));//取出成功

}   

      
// /* else {
ActionMessages errors = new ActionMessages();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("label.deny"));

if (!errors.isEmpty()) {
saveErrors(request, errors);
//request.setAttribute("error",errors);
}
   return  mapping.findForward("failed");  //失败
// }*/


  
// return  mapping.findForward("failed");   }
}
静态的actionForm
UserForm.java
package hb;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;


public class UserForm extends ActionForm{  
private String name = null;
//用户名  
public UserForm(){}
public void setName(String name) {
this.name = name;
}  
public String getName() {
return name;
}  


public void reset(ActionMapping mapping,
HttpServletRequest request) {
this.name = null;
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if ((name == null) || (name.equals(
""))){
errors.add(ActionErrors.GLOBAL_MESSAGE,
new ActionMessage(
"error.name.required"));
}

return errors;
}


}

    rs.GLOBAL_MESSAGE,
new ActionMessage(
"error.name.required"));
}

return errors;
}


}
lunzi   2006-05-23 23:40:10 阅读:2429  评论:6  引用:0
hbstruts是我学习struts+hiberante开发的第一个小系统,非常稚嫩但是可作为日后学习一种参考。
struts1.1+hibernate2.1.7+tomcat4.1.30+MySQL5.0.2开发
1、hbstruts\WEB-INF\classes下的文件
hibernate.cfg.xml
HibernateUtil.java

LoginAction.java  //控制文件
UserDAO.java  //模型文件
UserForm.java
2、hbstruts\\WEB-INF\classes\hb下的文件
User.hbm.xml
User.java

MyResource_zh.properties
hbstruts\WEB-INF\下的文件
struts-config.xml
web.xml
struts-bean.tld
struts-html.tld
3、hbstruts\下的文件 视图文件
login.jsp  
right.jsp
error.jsp





      
lunzi   2006-05-24 00:14:07 阅读:1376  评论:1  引用:0
login.jsp多功能页面
<%@ page contentType=
"text/html;charset=ISO8859_1" language="java" %>
<%@ taglib uri=
"/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri=
"/WEB-INF/struts-html.tld" prefix="html" %>
<META http-equiv=Content-Type content=
"text/html; charset=gb2312">
<body vLink=
"#006666" link="#003366" bgColor="#E0F0F8">

<html:img pageKey=
"title.imageEnter" altKey="title.imgEnterHint"/>
<form action=
"login.do?action=login" method="post">

<bean:message key=
"item.username"/>
<input size=
"15" name="name">login<p>
<html:submit>
<bean:message key=
"item.submit"/>
</html:submit>

</form>
<form action=login.do?action=addUser method=
"post">
<bean:message key=
"item.username"/>
<input size=
"15" name="name">addUser<p>
<html:submit>
<bean:message key=
"item.submit"/>
</html:submit>
</form>
<a href =
"login.do?action=getUser">getUser</a>
<a href =
"/javabean/operSql.jsp">operSql</a>
right.jsp
<%@ page contentType=
"text/html;charset=ISO8859_1" language="java" %>
<%@ taglib uri=
"/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri=
"/WEB-INF/struts-html.tld" prefix="html" %>
<META http-equiv=Content-Type content=
"text/html; charset=gb2312">
<%@ page import =
"hb.*,java.util.*" %>
<%
UserForm formBean1 = (UserForm)request.getAttribute(
"formBean1");
if(formBean1 != null && formBean1.getName()!=null){
%>
<h1><img src=
"smile.gif">
<bean:message key=
"title.welcome"/>
<%=formBean1.getName()%>
<bean:message key=
"title.classmate"/>
<%
}else{
%>
<bean:message key=
"label.deny"/>

<%}
%>
</h1><br>
<a href=
"login.jsp">
<bean:message key=
"item.loginAgain"/>
</a>||
<a href=
"regist.do">
<bean:message key=
"item.regist"/>
</a>
<%
List list=(List)session.getAttribute(
"userList");
  
//out.println("list:"+list);
if(list!=null){
  for(int i=0;i<list.size();i++){
    User g=(User)list.get(i);
    
//out.println(g.getId());
    out.println(g.getName()+
"<br>");
  }
}     
%>

error.jsp
<%@ page contentType=
"text/html;charset=ISO8859_1" language="java" %>
<%@ taglib uri=
"/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri=
"/WEB-INF/struts-html.tld" prefix="html" %>
<META http-equiv=Content-Type content=
"text/html; charset=gb2312">

<h1><p><img src=
"cry.gif">
<html:errors/>

</p></h1>
<a href=
"login.jsp">
<bean:message key=
"item.loginAgain"/>
</a>||

<a href=
"regist.do">
<bean:message key=
"item.regist"/>
</a>

lunzi   2006-05-24 00:01:18 阅读:1049  评论:1  引用:0
Copyright@2004-2010 powered by YuLog