Struts1 增删改查

文章说明

本篇文章介绍如何使用Struts1进行增删改查,仅是对自己学习的记录,并没有深入分析每个模块(不重复造轮子O(∩_∩)O~)。

Tomcat

开源的Web应用服务器,apache-tomcat-8.0.35-windows-x64.zip仅有10.3M。启动服务:bin-startup.bat。

1.png-28.7kB

数据库

MySQL

建立数据库test,并在其中建立表users

CREATE DATABASE test
USE test
CREATE TABLE users (
  id int(10) NOT NULL AUTO_INCREMENT,
  name varchar(10) NOT NULL,
  sex varchar(2) NOT NULL,
  phone varchar(11) DEFAULT NULL,
  address varchar(50) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8;

查看表users

DESC users

2.png-17.1kB

数据库管理工具-Navicat

3.png-37.5kB

JDBC

1.png-28.5kB

Struts 1

采用Java Servlet/JSP,实现了基于Java Web应用的MVC框架,是MVC的经典产品。

MVC

5.png-24.9kB

  1. 模型(Model):DB
  2. 视图(View):JSP
  3. 控制器(Controller):ActionServlet

Struts框架

7.png-25.9kB

struts-config.xml:声明和映射Struts组件。

安装 Struts 1

将lib目录下,所有的jar包复制到工程目录WEB-INF的lib目录中。

4.png-76.9kB

配置 Struts 1

在web.xml DD配置文件中,加入

    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script type="text/javascript">
    function validate(form) {

        if (validatePhone(form)) {
            form.submit();
        }
    }

    function validatePhone(form) {

        var regex = /^\d{7,11}$/;

        if (!regex.test(form["phone"].value)) {
            alert("输入的phone非法!");
            return false;
        }

        return true;
    }
</script>

<title>增加用户界面</title>
</head>

<body>
    <form action="add.do?action=submit" method="post">
        <table>
            <tr>
                <td>name:</td>
                <td><input type="text" name="name"></td>
            </tr>
            <tr>
                <td>sex:</td>
                <td><select name="sex">
                        <option value="1">男</option>
                        <option value="2">女</option>
                </select></td>
            </tr>
            <tr>
                <td>phone:</td>
                <td><input type="text" name="phone"></td>
            </tr>
            <tr>
                <td>address:</td>
                <td><input type="text" name="address"></td>
            </tr>
            <tr>
                <td><input type="button" value="add"
                    onclick="validate(this.form);"></td>
            </tr>
        </table>
    </form>

</body>
</html>

8.png-2kB

AddAction.java

package 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 model.DBHelperL;

public class AddAction extends Action {

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String phone = request.getParameter("phone");
        String address = request.getParameter("address");
        String action = request.getParameter("action");

        if ("submit".equals(action)) {
            if (name == null || name.length() <= 0) {

            } else {
                // 数据库增加操作
                DBHelperL db = new DBHelperL();
                db.add(name, sex, phone, address);
                db.close();
                // 重定向,防止刷新时重复提交表单!
                response.sendRedirect("show.do");
            }
        }

        return mapping.getInputForward();
    }
}

DB add

    public void add(String name, String sex, String phone, String address) throws SQLException {

        String sql = "INSERT INTO users (name, sex, phone, address) VALUES(?,?,?,?)";

        if (pstm == null) {
            pstm = conn.prepareStatement(sql);
        }

        pstm.setString(1, name);
        pstm.setString(2, sex);
        pstm.setString(3, phone);
        pstm.setString(4, address);

        pstm.execute();
    }

struts-config.xml DD配置

<action-mappings>中,添加action。

    <action path="/add" type="action.AddAction" input="/pages/add.jsp">
        <forward name="success" path="/show.do"></forward>
    </action>

show.jsp

<body>
    <%
        DBHelperL db = new DBHelperL();
        List<List<String>> lists = db.queryAll();
        db.close();

        request.setAttribute("lists", lists);
    %>

    <form action="show.do" method="post">
        <table align="center">
            <caption>users表的所有数据</caption>
            <tr>
                <th>count</th>
                <th>id</th>
                <th>name</th>
                <th>sex</th>
                <th>phone</th>
                <th>address</th>
                <th>delete</th>
                <th>update</th>
            </tr>
            <c:forEach var="list" items="${lists}" varStatus="status">
                <tr>
                    <td>${status.count}</td>
                    <td>${list.get(0)}</td>
                    <td>${list.get(1)}</td>
                    <td>${list.get(2)}</td>
                    <td>${list.get(3)}</td>
                    <td>${list.get(4)}</td>
                    <td><a href="show.do?deleteID=${list.get(0)}">删除</a></td>
                    <td><a href="update.do?updateID=${list.get(0)}">修改</a></td>
                </tr>
            </c:forEach>
        </table>
    </form>

    <br>
    <a href="add.do">增加用户</a>

</body>

9.png-4.3kB

DB queryByID

    public List<String> queryByID(String ID) throws SQLException {

        List<String> list = new ArrayList<>();

        String sql = "SELECT * FROM users WHERE id = ?";

        pstm = conn.prepareStatement(sql);
        pstm.setString(1, ID);
        ResultSet rs = pstm.executeQuery();

        while (rs.next()) {
            // 将结果顺序存放到一个list中,作为结果返回
            list.add(rs.getString(2));
            list.add(rs.getString(3));
            list.add(rs.getString(4));
            list.add(rs.getString(5));
        }
        return list;
    }

struts-config.xml DD配置

    <action path="/show" type="action.DeleteAction" input="/pages/show.jsp"
        forward="/pages/show.jsp"></action>

DeleteAction.java

package 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 model.DBHelperL;

public class DeleteAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        
        String ID = request.getParameter("deleteID");
        
        DBHelperL db = new DBHelperL();
        db.deleteByID(ID);
        db.close();
        
        return mapping.getInputForward();
    }
}

DB deleteByID

    public boolean deleteByID(String ID) throws SQLException {

        String sql = "DELETE FROM users WHERE id = ?";

        pstm = conn.prepareStatement(sql);

        pstm.setString(1, ID);

        return pstm.execute();
    }

name和sex不能修改,根据ID更新数据。

update.jsp

    <form
        action="update.do?action=submit&updateID=<%=request.getAttribute("updateID")%>"
        method="post">
        <table>
            <tr>
                <td>name:</td>
                <td><input type="text" name="name"
                    value=<%=request.getAttribute("name")%> readonly="readonly"></td>
            </tr>
            <tr>
                <td>sex:</td>
                <td><input type="text" name="sex"
                    value=<%=request.getAttribute("sex")%> readonly="readonly"></td>
            </tr>
            <tr>
                <td>phone:</td>
                <td><input type="text" name="phone_new"
                    value=<%=request.getAttribute("phone_old")%>></td>
            </tr>
            <tr>
                <td>address:</td>
                <td><input type="text" name="address_new"
                    value=<%=request.getAttribute("address_old")%>></td>
            </tr>
            <tr>
                <td><input type="submit" value="update"></td>
            </tr>
        </table>
    </form>

UpdateAction.java

package action;

import java.util.List;

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 model.DBHelperL;

public class UpdateAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String ID = request.getParameter("updateID");
        String action = request.getParameter("action");

        DBHelperL db = new DBHelperL();

        List<String> list = db.queryByID(ID);
        if (!list.isEmpty()) {
            request.setAttribute("updateID", ID);
            request.setAttribute("name", list.get(0));
            request.setAttribute("sex", list.get(1));
            request.setAttribute("phone_old", list.get(2));
            request.setAttribute("address_old", list.get(3));
        }

        if ("submit".equals(action)) {
            if (ID != null && ID.length() > 0) {
                String phone_new = request.getParameter("phone_new");
                String address_new = request.getParameter("address_new");
                db.updateByID(ID, phone_new, address_new);
                db.close();
                response.sendRedirect("show.do");
            }
        }

        db.close();

        return mapping.getInputForward();
    }
}

struts-config.xml

    <action path="/update" type="action.UpdateAction" input="/pages/update.jsp">
        <forward name="success" path="/show.do"></forward>
    </action>

10.png-2.8kB

中文乱码

Filter

package filters;

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;

public class SetCharacterEncodingFilter implements Filter {

    String encoding = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        encoding = filterConfig.getInitParameter("encoding");

        if (encoding == null || encoding.length() <= 0) {
            encoding = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        request.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

}

web.xml DD中配置

    <filter>
        <filter-name>Set Character Encoding</filter-name>
        <filter-class>filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>Set Character Encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

其它问题

防止刷新-重复提交表单

response.sendRedirect("show.do");

表单验证-JavaScript

button替代submit,在JavaScript中满足条件时,调用form.submit()

<input type="button" value="add" onclick="validate(this.form);">

JavaScript代码:

<script type="text/javascript">
    function validate(form) {

        if (validatePhone(form)) {
            form.submit();
        }
    }

    function validatePhone(form) {

        var regex = /^\d{7,11}$/;

        if (!regex.test(form["phone"].value)) {
            alert("输入的phone非法!");
            return false;
        }

        return true;
    }
</script>

首页跳转到.do

在默认的jsp文件中,转发到指定的URL。

<jsp:forward page="show.do"></jsp:forward>

DEMO 下载链接

http://pan.baidu.com/s/1i5rX6fz

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏进击的程序猿

doctrine缘来 之 造轮子

本系列是读php data persistence with doctrine2 orm的笔记,本文是第一篇:自己造轮子。

771
来自专栏程序员的酒和故事

Go实战--golang中使用RethinkDB(gorethink/gorethink.v3)

生命不止,继续go go go !!! 关于golang中操作数据库,曾经介绍了不少: Go实战–go语言操作sqlite数据库(The way to go) ...

5498
来自专栏Java3y

图书管理系统【部署开发环境、解决分类、图书、前台页面模块】

前言 巩固Servlet+JSP开发模式,做一个比较完整的小项目. 成果图 该项目包含了两个部分,前台和后台。 前台用于显示 ? 后台用于管理 ? 该项目可分为...

6464
来自专栏Hadoop实操

如何使用Flume采集Kafka数据写入Kudu

1.6K2
来自专栏云计算与大数据

研发:jenkins 持续集成如何打tag

uild Timestamp Plugin will be the Best Answer to get the TIMESTAMPS in the Build...

1894
来自专栏【转载】DRF+Vue+Mysql_生鲜超市系统

五、商品列表页

在goods文件夹下面新建view_base.py,为了区分django和django rest framework的view

2150
来自专栏.NET开发者社区

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)

在本系列第一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)》中,我为大家介绍...

29610
来自专栏Spark学习技巧

重要 | mr使用hcatalog读写hive表

企业中,由于领导们的要求,hive中有数据存储格式很多时候是会变的,比如为了优化将tsv,csv格式改为了parquet或者orcfile。那么这个时候假如是m...

1862
来自专栏有趣的django

Django REST framework+Vue 打造生鲜超市(四)

五、商品列表页 5.1.django的view实现商品列表页 (1)goods/view_base.py 在goods文件夹下面新建view_base.py,为...

2.1K9
来自专栏jeremy的技术点滴

SSM项目脚手架

4814

扫码关注云+社区

领取腾讯云代金券