[关闭]
@Yano 2016-06-10T05:24:51.000000Z 字数 9255 阅读 3312

Struts1 增删改查

Java-Web


文章说明

本篇文章介绍如何使用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

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

查看表users

  1. 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配置文件中,加入

  1. <servlet>
  2. <servlet-name>action</servlet-name>
  3. <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
  4. </servlet>
  5. <servlet-mapping>
  6. <servlet-name>action</servlet-name>
  7. <url-pattern>*.do</url-pattern>
  8. </servlet-mapping>

add.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <script type="text/javascript">
  8. function validate(form) {
  9. if (validatePhone(form)) {
  10. form.submit();
  11. }
  12. }
  13. function validatePhone(form) {
  14. var regex = /^\d{7,11}$/;
  15. if (!regex.test(form["phone"].value)) {
  16. alert("输入的phone非法!");
  17. return false;
  18. }
  19. return true;
  20. }
  21. </script>
  22. <title>增加用户界面</title>
  23. </head>
  24. <body>
  25. <form action="add.do?action=submit" method="post">
  26. <table>
  27. <tr>
  28. <td>name:</td>
  29. <td><input type="text" name="name"></td>
  30. </tr>
  31. <tr>
  32. <td>sex:</td>
  33. <td><select name="sex">
  34. <option value="1">男</option>
  35. <option value="2">女</option>
  36. </select></td>
  37. </tr>
  38. <tr>
  39. <td>phone:</td>
  40. <td><input type="text" name="phone"></td>
  41. </tr>
  42. <tr>
  43. <td>address:</td>
  44. <td><input type="text" name="address"></td>
  45. </tr>
  46. <tr>
  47. <td><input type="button" value="add"
  48. onclick="validate(this.form);"></td>
  49. </tr>
  50. </table>
  51. </form>
  52. </body>
  53. </html>

8.png-2kB

AddAction.java

  1. package action;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.struts.action.Action;
  5. import org.apache.struts.action.ActionForm;
  6. import org.apache.struts.action.ActionForward;
  7. import org.apache.struts.action.ActionMapping;
  8. import model.DBHelperL;
  9. public class AddAction extends Action {
  10. @Override
  11. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
  12. HttpServletResponse response) throws Exception {
  13. String name = request.getParameter("name");
  14. String sex = request.getParameter("sex");
  15. String phone = request.getParameter("phone");
  16. String address = request.getParameter("address");
  17. String action = request.getParameter("action");
  18. if ("submit".equals(action)) {
  19. if (name == null || name.length() <= 0) {
  20. } else {
  21. // 数据库增加操作
  22. DBHelperL db = new DBHelperL();
  23. db.add(name, sex, phone, address);
  24. db.close();
  25. // 重定向,防止刷新时重复提交表单!
  26. response.sendRedirect("show.do");
  27. }
  28. }
  29. return mapping.getInputForward();
  30. }
  31. }

DB add

  1. public void add(String name, String sex, String phone, String address) throws SQLException {
  2. String sql = "INSERT INTO users (name, sex, phone, address) VALUES(?,?,?,?)";
  3. if (pstm == null) {
  4. pstm = conn.prepareStatement(sql);
  5. }
  6. pstm.setString(1, name);
  7. pstm.setString(2, sex);
  8. pstm.setString(3, phone);
  9. pstm.setString(4, address);
  10. pstm.execute();
  11. }

struts-config.xml DD配置

<action-mappings>中,添加action。

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

show.jsp

  1. <body>
  2. <%
  3. DBHelperL db = new DBHelperL();
  4. List<List<String>> lists = db.queryAll();
  5. db.close();
  6. request.setAttribute("lists", lists);
  7. %>
  8. <form action="show.do" method="post">
  9. <table align="center">
  10. <caption>users表的所有数据</caption>
  11. <tr>
  12. <th>count</th>
  13. <th>id</th>
  14. <th>name</th>
  15. <th>sex</th>
  16. <th>phone</th>
  17. <th>address</th>
  18. <th>delete</th>
  19. <th>update</th>
  20. </tr>
  21. <c:forEach var="list" items="${lists}" varStatus="status">
  22. <tr>
  23. <td>${status.count}</td>
  24. <td>${list.get(0)}</td>
  25. <td>${list.get(1)}</td>
  26. <td>${list.get(2)}</td>
  27. <td>${list.get(3)}</td>
  28. <td>${list.get(4)}</td>
  29. <td><a href="show.do?deleteID=${list.get(0)}">删除</a></td>
  30. <td><a href="update.do?updateID=${list.get(0)}">修改</a></td>
  31. </tr>
  32. </c:forEach>
  33. </table>
  34. </form>
  35. <br>
  36. <a href="add.do">增加用户</a>
  37. </body>

9.png-4.3kB

DB queryByID

  1. public List<String> queryByID(String ID) throws SQLException {
  2. List<String> list = new ArrayList<>();
  3. String sql = "SELECT * FROM users WHERE id = ?";
  4. pstm = conn.prepareStatement(sql);
  5. pstm.setString(1, ID);
  6. ResultSet rs = pstm.executeQuery();
  7. while (rs.next()) {
  8. // 将结果顺序存放到一个list中,作为结果返回
  9. list.add(rs.getString(2));
  10. list.add(rs.getString(3));
  11. list.add(rs.getString(4));
  12. list.add(rs.getString(5));
  13. }
  14. return list;
  15. }

struts-config.xml DD配置

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

DeleteAction.java

  1. package action;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.struts.action.Action;
  5. import org.apache.struts.action.ActionForm;
  6. import org.apache.struts.action.ActionForward;
  7. import org.apache.struts.action.ActionMapping;
  8. import model.DBHelperL;
  9. public class DeleteAction extends Action {
  10. @Override
  11. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
  12. HttpServletResponse response) throws Exception {
  13. String ID = request.getParameter("deleteID");
  14. DBHelperL db = new DBHelperL();
  15. db.deleteByID(ID);
  16. db.close();
  17. return mapping.getInputForward();
  18. }
  19. }

DB deleteByID

  1. public boolean deleteByID(String ID) throws SQLException {
  2. String sql = "DELETE FROM users WHERE id = ?";
  3. pstm = conn.prepareStatement(sql);
  4. pstm.setString(1, ID);
  5. return pstm.execute();
  6. }

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

update.jsp

  1. <form
  2. action="update.do?action=submit&updateID=<%=request.getAttribute("updateID")%>"
  3. method="post">
  4. <table>
  5. <tr>
  6. <td>name:</td>
  7. <td><input type="text" name="name"
  8. value=<%=request.getAttribute("name")%> readonly="readonly"></td>
  9. </tr>
  10. <tr>
  11. <td>sex:</td>
  12. <td><input type="text" name="sex"
  13. value=<%=request.getAttribute("sex")%> readonly="readonly"></td>
  14. </tr>
  15. <tr>
  16. <td>phone:</td>
  17. <td><input type="text" name="phone_new"
  18. value=<%=request.getAttribute("phone_old")%>></td>
  19. </tr>
  20. <tr>
  21. <td>address:</td>
  22. <td><input type="text" name="address_new"
  23. value=<%=request.getAttribute("address_old")%>></td>
  24. </tr>
  25. <tr>
  26. <td><input type="submit" value="update"></td>
  27. </tr>
  28. </table>
  29. </form>

UpdateAction.java

  1. package action;
  2. import java.util.List;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletResponse;
  5. import org.apache.struts.action.Action;
  6. import org.apache.struts.action.ActionForm;
  7. import org.apache.struts.action.ActionForward;
  8. import org.apache.struts.action.ActionMapping;
  9. import model.DBHelperL;
  10. public class UpdateAction extends Action {
  11. @Override
  12. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
  13. HttpServletResponse response) throws Exception {
  14. String ID = request.getParameter("updateID");
  15. String action = request.getParameter("action");
  16. DBHelperL db = new DBHelperL();
  17. List<String> list = db.queryByID(ID);
  18. if (!list.isEmpty()) {
  19. request.setAttribute("updateID", ID);
  20. request.setAttribute("name", list.get(0));
  21. request.setAttribute("sex", list.get(1));
  22. request.setAttribute("phone_old", list.get(2));
  23. request.setAttribute("address_old", list.get(3));
  24. }
  25. if ("submit".equals(action)) {
  26. if (ID != null && ID.length() > 0) {
  27. String phone_new = request.getParameter("phone_new");
  28. String address_new = request.getParameter("address_new");
  29. db.updateByID(ID, phone_new, address_new);
  30. db.close();
  31. response.sendRedirect("show.do");
  32. }
  33. }
  34. db.close();
  35. return mapping.getInputForward();
  36. }
  37. }

struts-config.xml

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

10.png-2.8kB

中文乱码

Filter

  1. package filters;
  2. import java.io.IOException;
  3. import javax.servlet.Filter;
  4. import javax.servlet.FilterChain;
  5. import javax.servlet.FilterConfig;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.ServletRequest;
  8. import javax.servlet.ServletResponse;
  9. public class SetCharacterEncodingFilter implements Filter {
  10. String encoding = null;
  11. @Override
  12. public void init(FilterConfig filterConfig) throws ServletException {
  13. encoding = filterConfig.getInitParameter("encoding");
  14. if (encoding == null || encoding.length() <= 0) {
  15. encoding = "UTF-8";
  16. }
  17. }
  18. @Override
  19. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  20. throws IOException, ServletException {
  21. request.setCharacterEncoding(encoding);
  22. chain.doFilter(request, response);
  23. }
  24. @Override
  25. public void destroy() {
  26. }
  27. }

web.xml DD中配置

  1. <filter>
  2. <filter-name>Set Character Encoding</filter-name>
  3. <filter-class>filters.SetCharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>UTF-8</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>Set Character Encoding</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>

其它问题

防止刷新-重复提交表单

  1. response.sendRedirect("show.do");

表单验证-JavaScript

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

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

JavaScript代码:

  1. <script type="text/javascript">
  2. function validate(form) {
  3. if (validatePhone(form)) {
  4. form.submit();
  5. }
  6. }
  7. function validatePhone(form) {
  8. var regex = /^\d{7,11}$/;
  9. if (!regex.test(form["phone"].value)) {
  10. alert("输入的phone非法!");
  11. return false;
  12. }
  13. return true;
  14. }
  15. </script>

首页跳转到.do

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

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

DEMO 下载链接

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

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注