用Eclipse开发Struts实例-GuestBook(2)

 
五、加入 commons-dbutils-1.1,便于对数据库进行操作
1 、下载地址
     [url]http://commons.apache.org/downloads/download_dbutils.cgi[/url]
2 、下载页面
 
3、下载后解压,将类库文件加载到项目的buildPath中
 
六、加入对表单内容进行效验
1、在struts-config.xml文件中加入输入验证
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
  <form-beans>
    <form-bean name="inputForm"
      type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="title" type="java.lang.String" />
      <form-property name="content" type="java.lang.String" />
      <form-property name="url" type="java.lang.String" />
      <form-property name="email" type="java.lang.String" />
      <form-property name="name" type="java.lang.String" />
    </form-bean>

  </form-beans>

  <global-exceptions />
  <global-forwards />
  <action-mappings>
    <action attribute="inputForm" input="/form/input.jsp"
      name="inputForm" path="/input" scope="request"
      type="com.meixin.struts.action.InputAction" />

  </action-mappings>

  <message-resources
    parameter="com.meixin.struts.ApplicationResources" />
  <!-- 加入Struts的一个插件,对表单进行验证,这里只能手动添加 -->
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
      value="/org/apache/struts/validator/validator-rules.xml,/WEB-INF/validations.xml" />
  </plug-in>
</struts-config>
2 、建立 validations.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC
                    "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN"
                    "http://jakarta.apache.org/commons/dtds/validator_1_1.dtd">
<!-- 新建form验证 -->
<form-validation>
  <formset>
    <!-- form的名称 -->
    <form name="inputForm">
      <!-- 设定name是必需的,若没有输入,则输出msg中的信息 -->
      <field property="name" depends="required">
        <msg name="required" key="guestbook.inputForm.name" />
      </field>
      <field property="title" depends="required">
        <msg name="required" key="guestbook.inputForm.title" />
      </field>
      <field property="content" depends="required">
        <msg name="required" key="guestbook.inputForm.content" />
      </field>
    </form>
  </formset>
</form-validation>
七、编辑 Action 文件,用于保存记录
1 input.jsp 文件
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>    
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
<html>    
  <head>
    <title>JSP for DynaValidatorForm form</title>
  </head>
    
  <body>
    <!-- 转到查看留言Action页面用此两种方法 -->
    <a href="/guestbook2/read.do">查看留言</a>
    <a href="<c:url value='/read.do' />">查看留言</a>
    
    <html:form action="/input">
      title : <html:text property="title"/><html:errors property="title"/><br/>
      content : <html:textarea property="content"/><html:errors property="content"/><br/>
      url : <html:text property="url"/><html:errors property="url"/><br/>
      email : <html:text property="email"/><html:errors property="email"/><br/>
      name : <html:text property="name"/><html:errors property="name"/><br/>
      <html:submit/><html:cancel/>
    </html:form>
  </body>
</html>
2 InputAction
 
package com.meixin.struts.action;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
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.validator.DynaValidatorForm;

public class InputAction extends Action
{

  public ActionForward execute(ActionMapping mapping, ActionForm form,
      HttpServletRequest request, HttpServletResponse response)
  {
    DynaValidatorForm inputForm = (DynaValidatorForm) form;
    // 在guestbook中都是建立记录操作
    String sql = "insert into guestbook(name,email,url,title,content,time) values(?,?,?,?,?,?)";
    // 创建String数组,这里将所有表单中的数据都放入数组中
    String[] params = { (String) inputForm.get("name"),
        (String) inputForm.get("email"), (String) inputForm.get("url"),
        (String) inputForm.get("title"),
        (String) inputForm.get("content"),
        new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date()) };

    try
    {
      // 建立上下文对象,初始化
      Context context = new InitialContext();
      // 获取数据源,在Tomcat中的context.xml中设置的数据源名字要一样
      DataSource ds = (DataSource) context
          .lookup("java:/comp/env/jdbc/mssqlds");
      // 获取数据库的连接
      // ds.getConnection();
      // 用QueryRunner封装数据源,这个类完成了许多数据库的操作
      QueryRunner qr = new QueryRunner(ds);
      // 执行SQL语句,传入?所对应的参数,这里传入数组
      qr.update(sql, params);
    }
    catch (NamingException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    catch (SQLException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //保存后自动转向到读取留言页面
    return mapping.findForward("guestbook.read");
  }
}
八、编写过滤器类文件,在 web.xml 文件中配置过滤器,解决中文乱码问题
1 、编写过滤器文件
package com.meixin.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//编写过滤器,需要实现javax.servlet.Filter接口
public class CharactorEncodingFilter implements Filter
{
  public void destroy()
  {
  }
  //在doFilter方法中处理
  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException
  {
    //将所有request内的对象设置字符集为UTF-8
    request.setCharacterEncoding("UTF-8");
    //用chain的doFilter处理过滤
    chain.doFilter(request, response);
  }
  public void init(FilterConfig arg0) throws ServletException
  {
  }
}
2 、在 web.xml 文件中的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     [url]http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd[/url]">

  <!-- 在web.xml文件中增加对Filter的设置 -->
  <filter>
    <!-- filter的名称 -->
    <filter-name>charactorEncoding</filter-name>
    <!-- filter对应的类 -->
    <filter-class>
      com.meixin.filter.CharactorEncodingFilter
    </filter-class>
  </filter>
  <!-- 设置过滤器调用的映射 -->
  <filter-mapping>
    <!-- filter的名称,和设置中的名称要一致 -->
    <filter-name>charactorEncoding</filter-name>
    <!-- 设置对当前的request,response请求都进行过滤 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
      org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 
九、建立用于读取留言信息的 Action Forward JSP 页面,用于读取留言信息
1 、建立 Action
2、建立Forward
3、struts-config.xml文件如下
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
  <form-beans>
    <form-bean name="inputForm"
      type="org.apache.struts.validator.DynaValidatorForm">
      <form-property name="title" type="java.lang.String" />
      <form-property name="content" type="java.lang.String" />
      <form-property name="url" type="java.lang.String" />
      <form-property name="email" type="java.lang.String" />
      <form-property name="name" type="java.lang.String" />
    </form-bean>
  </form-beans>
  <global-exceptions />
  <global-forwards>
    <forward name="guestbook.display" path="/form/display.jsp" />
  </global-forwards>
  <action-mappings>
    <action attribute="inputForm" input="/form/input.jsp"
      name="inputForm" path="/input" scope="request"
      type="com.meixin.struts.action.InputAction" />
    <action path="/read" type="com.meixin.struts.action.ReadAction" />
  </action-mappings>
  <message-resources
    parameter="com.meixin.struts.ApplicationResources" />
  <!-- 加入Struts的一个插件,对表单进行验证,这里只能手动添加 -->
  <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
    <set-property property="pathnames"
      value="/org/apache/struts/validator/validator-rules.xml,/WEB-INF/validations.xml" />
  </plug-in>
</struts-config>

你可能感兴趣的:(struts,职场,休闲)