struts学习笔记

来源:互联网 发布:四大中锋巅峰数据 编辑:程序博客网 时间:2024/06/05 19:23

一:标签使用的声明方式:

<%@ taglib uri=http://struts.apache.org/tags-bean” prefix=”bean” %>

<%@ taglib uri=http://struts.apache.org/tags-html” prefix=”html” %>

 

二:可以在web.xml文件中手工定义一个uri

web.xml文件中定义一个jsp-config元素

<jsp-config>

 <taglib>

   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>

   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

</jsp-config>

 

三:web.xml文件又被称为deployment descriptor

这个文件服务器自动读取其中的配置

 

四:struts中的转向方式

分为两种情况:

1、使用ActionForward对象来转向

   return new ActionForward(“/index.jsp”).

2、在配置文件中配置forward节点

   <forward name=”index” path=”/index.jsp” redirect=””></forward>

   Return mapping.findForward(“index”);

如果设置redirect=true,则表示使用的是response.sendRedirect()方式,则在跳转后的页面通过request.getAttribute()是得不到跳转前的页面设置的属性值的。反之,如果redirect=false,则表示采用的是

request.getRequestDispatcher(“index.jsp”).forward(request,response)的方式,该方式是可以在页面之间传递属性值。

 

 

一:struts标签库

常用的标签库有三类:

html标记:展示一些html元素,比如

html:form,html:submit,html:text,html:password

bean 标记:用来输出一些bean内容,比如bean:write,bean:define

logic标记:用来实现逻辑操作,比如logic:equals,logic:iterator

 

二:使用标签的两种模式:

1、使用tld文件中默认uri配置

2、web.xml文件中设置tag-lib节点

 

三:配置和引入用户标签库

第一种方式:Web.xml文件配置

<jsp-config>

 <taglib>

   <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>

   <taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

</jsp-config>

第二种方式:页面引用

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

红色部分必须保证一致

备注:表示资源定位的一般以斜杠开头。

 

 四:常用标签示例

<html:select property=”sex”>

<html:option value=”male”></html:option>

<html:option value=”female”></html:option>

</html:select>

在对应的formbean中对应的属性值用String类型。

1<html:radio>标签

<html:radio property=”sex” value=”male”></html:radio>

<html:radio property=”sex” value=”female”><html:radio>

<html:radio property=”sex” value=”unknown”>未知<html:radio>

在对应的formbean中对应的属性值用String类型。

 

2<html:checkbox>标签

<html:checkbox property=”fav” value=”reading”>读书</html:checkbox>

<html:checkbox property=”fav” value=”news”>新闻</html:checkbox>

<html:checkbox property=”fav” value=”music”>音乐</html:checkbox>

在对应的formbean中对应的属性值用String【】类型。

取值的时候用String[] fav = loginForm.getFavorite()

try{

for(int i=0;i<fav.length;i++){

   response.getWriter().println(fav[i]);

}

}

即可。

3<html:image>标签

<html:image alt=”显示图片” src=”sunset.jpg”></html:image>

<html:img alt=”显示图片” src=”sunset.jpg”></html:image>

 

备注:src=”sunset.jgp”中的sunset.jpg存放在WebRoot文件夹下。

4<html:link>标签

<html:link href=”A.jsp”>链接</html:link>

<html:link href=”login.do?username=zhangsan”>链接</html:link>

 

5<html:hidden>标签

<html:hidden property=”flag” value=”delete”/>

 

6<html:multibox>标签

<html:multibox property=”fav” value=”sport”> </html:multibox>体育

<html:multibox property=”fav” value=”sport”> </html:multibox>财经

<html:multibox property=”fav” value=”sport”> </html:multibox>旅游

 

7Cookie的使用

<%

Cookie ck = new Cookie(“username”,administrator)

ck.setMaxAge(1000*60*60);

response.addCookie(ck);

 

Cookie[] cks = request.getCookies();

For(int i=0;i<cks.length;i++){

           Cookie ck = cks[i];

           Out.println(ck.getName());

}

%>

 

Cookie标签使用:

  <bean:cookie name=”username” id=”a”/>

  <bean:write name=”a” property=” name”/>

  <bean:write name=”a” property=” value”/>

 

8<bean:difine>标签

传统方式:

<%

  String username = “administrator”;

  Out.println(username);

%>

 

<bean:define id=”myname” value=”administrator”></bean:define>

<bean:write name=”myname”/>

 

/*request范围内的一个值保存到session */

传统方式:

<%

   Request.setAttribute(“username”,”administrator”);

   String username = “” + request.getAttribute(“username”);

   Session.setAttribute(“myname”,username);

%>

 

<bean:define>标签

<bean:define id=”myname” name=”username” scope=”request” toScope=”session”>

<%

   out.println(session.getAttribute(“myname”);

%>

 

9<bean:write>标签

<bean:parameter id=”myname” name=”username” value=”administrator” multiple=”true”/> //其中multiple表示可以接受多个参数值

<bean:write name=”myname”/>

 

10、显示属性值的四种方法

<%

  request.setAttribute(“username”,”administrator”);

%>

第一种:

   <%

        out.println(request.getAttribute(“username”));

 

   %>

第二种:

<%=request.getAttribute(“username”)%>

第三种:

${username}

第四种:

<bean:write name=”username”>

 

11<bean:write>标签输出对象的属性值

<%

  Emp emp = new Emp();

  emp.setUsername(“zhangsan”);

  emp.setPasswd(“123456”);

%>

 

<br>${emp.passwd}

<bean:write name=”emp” property=”passwd”>

 

12<logic:empty>标签

  <logic:empty name=”username”>

     对不起,usename值为空

  </logic:empty>

 

13<logic:equal>标签

   <logic:equal name=”myname” value=”zhangsan”>

      <jsp:forward page=”index.jsp/>

   </logic:equal>

 

14<logic:match>标签

<logic:match parameter=”username” value=”admin”>

   你具有管理员的权限

</logic:match>

备注:在IE地址栏里如下输入:

http://localhost:8080/web/a.jsp?username = admin

 

 

一:常用标签示例

1、转向的几种方式

第一种:

<jsp:forward page=”index.jsp”/></jsp:forward>

第二种:

request.getRequestDispatcher(“index.jsp”).forward(request,response)

第三种:

<logic:forward name=”K”/>

备注:

在配置文件里要有如下配置:

<global-forward>

   <forward name=”K” path=”k.jsp”/>

</global-forward>

 

2<logic:iterator>标签

传统方式

 

 <table border=”1” bgcolor=”red”>

<%

  List list = (List)request.getAttribute(“userlist”);

  for(int i=0;i<list.size();i++){

      String str = (String)list.get(i);

  %>

 

  <tr>

     <td><%=str%></td>

  </tr>

<%}%>

 

</table>

 

<bean:iterate>方式

<table border=”1” bgcolor=”red”>

<logic:iterate id=”u” name=”userlist”>

<tr>

   <td><bean:write name=”u”%></td>

</tr>

 

3ApplicationResources.properties为默认的资源文件名称,struts会在其他资源里找不到时,在这个文件里寻找该资源

4、格式化日期

Locale lc = new Locale(“zh”,”CN”);

System.out.println(Local.getDefault().getDisplayCountry());

 

int datesstyle = DateFormat.FULL;

int timestyle = DateFormat.FULL;

DateFormat df = DateFormat.getDateTimeInstance(datestyle,timestyle,lc);

Date date = new Date();

String str = df.format(date);

System.out.println(str);

 

5、资源文件的输出

  配置文件里配置(ApplicationResource.properties)

   title = my project!

  jsp文件里输出:

   <bean:message key=”title”/>

  struts-config.xml里需配置资源文件

 

6、修改struts属性文件,使属性文件里可以保存中文

windows->Preferences->General->Content Types里的Text->Java Properties File

 

7、显示资源文件里的错误信息

资源文件里:

username = username cannot be null

form表单里:

ActionErrors errors = new ActionErrors();

ActionMessage message = new ActionMessage(“username”);

errors.add(“username”,username):

jsp文件里:

<html:form action=”/login”>

<html:text property=”username”/><html:errors property=”username”/>

   备注:刷新一个jsp页面时,会调用formbean里的reset()方法,可以把一些初始信息放到该方法中

 

8、鼠标移过的时候颜色发生变化的效果实现

字体颜色发生变化:<tr onmouseover=”this.style.color=’#CF3698’” onmouseout=”this.style.color=’’” onclick=”this.style.color=’blue’”

1、删除传递id

<td><a href=”login.do?flag=2&empno=${emp.empno}”>修改</a>

 

2、DispatcherAction的使用

DispatcherAction里不再使用execute()方法,而是多个方法,每一个方法对应一个业务逻辑。

struts-config.xml文件里DispatcherAction文件的配置:

<action

attribute=”usermgrForm”

type=”com.sun.demo.action.UsermgrAction” parameter=”function”>

</action>

备注:其中UsermgrAction继承自DispatcherAction

jsp文件里访问该Action中指定的方法

<td><a href=”login.do?function=updateUser&empno=${emp.empno}”>修改</a>

备注updateUserUsermgrAction中的方法名。

 

3、DynamicForm的使用

(1):struts-config.xml文件里配置:

<form-bean>

<form-bean name=”loginForm” type=”org.apache.struts.action. DynaActionForm”>

<form-property name=”username” type=”java.lang.String”></form-property>

</form-bean>

(2)Action里使用DynaActionForm

DynaActionForm loginForm = DynaActionFormform

String username =(String) loginForm.get(“username”);

String password =(String) loginForm.get(“password”);

 

4、自建一个类继承自RequestProcess控制类

(1):struts-config.xml文件里配置:

 <controller processorClass=”com.sun.demo.MyRequestProcess”></controller>

 备注:<controller>标签必须在<message-resources>标签之前

       其中MyrequestProcess继承自RequestProcess,可以在MyRequestProcess里重写processPreprocess等方法。

 

5、Struts中文转换

Struts默认的转向方式是使用RequestDispatcher来完成的,对于request作用域范围内的字符串进行转码,可使用下面的方式

request.setCharacterEncoding(“GBK”)

定位位置可以为:

1.resetvalidate方法中加入下面代码

2.在过滤器中定义

 

示例一request设置,在两个jsp文件里传递

A.jsp文件里:

<%

request.setAttribute(“myname”,”我的名字”);

%>

<jsp:forward page=”B.jspusername=“张三”></jsp:forward>

 

B.jsp文件里:

<%

  out.println(request.getAttribute(“myname”))

  out.println(request.getParameter(“username);”

%>

 

结果显示:

我的名字(正常显示)

????(乱码)

修改如下即可:

<%

  request.setCharactorEncoding(“GBK”);

  out.println(request.getAttribute(“myname”))l

  out.println(request.getParameter(“username);”

%>

即可正常显示

 

   示例二:request设置,在一个Action和一个jsp文件里传递

  Action 文件exectue方法里:

  request.setAttribute(“myname”,”张三”)

  return new ActionForward(“/index.jsp”);//根据Struts语法规则,index.jsp必须以斜杠开头。

 

  index.jsp文件里:

  ${myname}

  出现乱码,解决方案:把jsp文件表头的ISO-8859-1 改为GBK即可

 

示例三:从text里提交过来的中文信息

LoginForm form = (LoginForm)form;

String username = form.getUsername();

try{

   username= new String(username.getBytes(“iso8859-1”),”GBK”);

}

6、  中文过滤器

新建一个类实现了Filterjavax.servlet.Filter.

再新建的类中写入下面这句话:

 request.setCharacterEncoding(“GBK”);

 chain.doFilter(request,response);

 

web.xml里配置该Filter

<filter>

   <filter-name>encodingFilter</filter-name>

   <filter-class>com.sun.demo.acton.CharacterEncodingFilter</filter-class>

 

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

1、Struts上传文件

1):页面表单设置

      <body>

         <html:form action=”/login” enctype=”multipart/form-data”>

         passwd:<html:text property=”passwd”/><br/>

         username:<html:text property=”username”/><br/>

         <html:file property=”file”></html:file>

         <html:submit/>

         </html:form>

      </body>

(2)FormBean 设置

  FormFile file

  public FormFile getFile(){

     return file;

}

  public void setFile(FormFile file){

    this.file = file;

}

(3)获取数据

  FormFile file = loginForm.getFile();

 

  InputStream is = file.getInputStream();

  OutputStream out = new FileOutputStream(“c:/file.xml”)

 

  int n=0;

  while((n=is.read()!=-1){

out.write(n);

 

}

  out.close();

 

或者如下获取数据

FormFile file = fileuploadForm.getFormfile();

try{

byte[] data = file.getFileData();

FileOutputStream fos = new FileOutputStream(“c:/”+file.getFileName());

fos.write(data);

fos.close();

}

 

String path = this.getServlet().getServletContext().getRealPath();

备注:getRealPath可以得到web应用程序所在的目录

 

 

 

 

2、Struts里连接数据库

1):Struts里配置<data-source>

<data-sources>

   <data-source>

   </data-source type=”org.apache.commons.dbcp.BasicDataSource”>

   <set-property value=”oracle.jdbc.dirver.OracleDriver” property=”driverClassName”/>

   <set-property property=”username” value=”scott”/>

<set-property property=”password” value=”tiger”/>

<set-property property=”jdbc:oracle:thin:@127.0.0.1:1521:orci” property=”uri”/>

</data-sources>

 

2)在Action里的execute方法里:

   DataSource ds = this.getDataSource(request);

   try{

     Connection conn = ds.getConnection();

}catch(Exception e){

   e.printStackTrace();

}

 

3、Struts里的页面引用

  1. jsp里引用B.jsp

<%@ taglib uri=http://struts.apache.org/tags-tiles “ prefix=”tiles”%>

<tiles:insert page=”B.jsp?username=admin”></tiles:insert>或者<jsp:include page=”B.jsp></jsp:include>

  1. jsp里:

B页面:${param.admin}

 

 

template.jsp文件里:

<table border=”1”>

<tr>

<td><tiles:insert attribute=”paged”></tiles:insert></td>

</tr>

<tr>

<td><tiles:insert attribute=”pagee”></tiles:insert></td>

</tr>

</table>

原创粉丝点击