Struts2连接Mysql的Crud使用

Posted huangting

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Struts2连接Mysql的Crud使用相关的知识,希望对你有一定的参考价值。

今天分享的是struts2框架中增删改查的用法:

  一:利用Struts2框架

   1.1在pom.xml中导入相关依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.ht</groupId>
    <artifactId>T224_struts</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>T224_struts Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.struts</groupId>
            <artifactId>struts2-core</artifactId>
            <version>2.5.13</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!-- 5.4、tomcat-jsp-api -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jsp-api</artifactId>
            <version>8.0.47</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>T224_struts</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

  二:导入分页相关的通用pageBean类,z.tld,并且配置web.xml

  2.1 导入pageBean类

package com.crud.tag;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import com.crud.util.PageBean;
/**
 * 分页通用类
 * @author Administrator
 */
public class PageTag extends BodyTagSupport 

    private static final long serialVersionUID = 1L;
    private PageBean pageBean;
    public PageBean getPageBean() 
        return pageBean;
    
    public void setPageBean(PageBean pageBean) 
        this.pageBean = pageBean;
    
    @Override
    public int doStartTag() throws JspException 
        JspWriter out = pageContext.getOut();
        try 
            out.print(tohtml());
         catch (IOException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        return super.doStartTag();
    
    private String toHTML() 
        StringBuffer sb = new StringBuffer();
        /*
         * 拼接向后台提交数据的form表单
         *     注意:拼接的form表单中的page参数是变化的,所以不需要保留上一次请求的值
         */
        sb.append("<form id=‘pageBeanForm‘ action=‘"+pageBean.getUrl()+"‘ method=‘post‘>");
        sb.append("<input type=‘hidden‘ name=‘page‘>");
        Map<String, String[]> parameterMap = pageBean.getParameterMap();
        if(parameterMap != null && parameterMap.size() > 0) 
            Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) 
                if(!"page".equals(entry.getKey())) 
                    String[] values = entry.getValue();
                    for (String val : values) 
                        sb.append("<input type=‘hidden‘ name=‘"+entry.getKey()+"‘ value=‘"+val+"‘>");
                    
                
            
        
        sb.append("</form>");
        
        /*
         * 展示的分页条
         */
        sb.append("<div style=‘text-align: right; font-size: 12px;‘>");
        sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页&nbsp;&nbsp;<a href=‘javascript:gotoPage(1)‘>首页</a>&nbsp;&nbsp;<a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.previousPage()+")‘>上一页</a>&nbsp;&nbsp;<a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.nextPage()+")‘>下一页</a>&nbsp;&nbsp;<a");
        sb.append(" href=‘javascript:gotoPage("+pageBean.getMaxPage()+")‘>尾页</a>&nbsp;&nbsp;<input type=‘text‘");
        sb.append(" id=‘skipPage‘");
        sb.append(" style=‘text-align: center; font-size: 12px; width: 50px;‘>&nbsp;&nbsp;<a");
        sb.append(" href=‘javascript:skipPage()‘>Go</a>");
        sb.append("</div>");
        
        /*
         * 给分页条添加与后台交互的js代码
         */
        sb.append("<script type=‘text/javascript‘>");
        sb.append("        function gotoPage(page) ");
        sb.append("            document.getElementById(‘pageBeanForm‘).page.value = page;");
        sb.append("            document.getElementById(‘pageBeanForm‘).submit();");
        sb.append("        ");
        sb.append("        function skipPage() ");
        sb.append("            var page = document.getElementById(‘skipPage‘).value;");
        sb.append("            if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+")");
        sb.append("                alert(‘请输入1~N的数字‘);");
        sb.append("                return;");
        sb.append("            ");
        sb.append("            gotoPage(page);");
        sb.append("        ");
        sb.append("</script>");
        return sb.toString();
    

  2.2  z.tld文件

<?xml version="1.0" encoding="UTF-8" ?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    version="2.0">
    
  <description>zking 1.1 core library</description>
  <display-name>zking core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>z</short-name>
  <uri>/zking</uri>

 <tag>
    <name>page</name>
    <tag-class>com.crud.tag.PageTag</tag-class>
    <body-content>JSP</body-content>
    <attribute>
        <name>pageBean</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  
</taglib>

  2.3 配置web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    version="3.1">

    <display-name>Archetype Created Web Application</display-name>
    <filter>
        <filter-name>encodingFiter</filter-name>
        <filter-class>com.crud.util.EncodingFiter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encodingFiter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>struts</filter-name>
        <!-- 相对于中央控制器,过滤请求 -->
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
</web-app>

三:在Mysql中设计数据库

技术图片

   3.1 在项目中配置与mysql数据库连接

 数据库用户名和密码是不一样的看你们自己怎么设置的

  技术图片

 

四:编写Dao层去访问数据库

package com.crud.dao;
import java.sql.SQLException;
import java.util.List;
import com.crud.entity.Class;
import com.crud.util.BaseDao;
import com.crud.util.EntityBaseDao;
import com.crud.util.PageBean;
import com.crud.util.StringUtils;
/**
 * 班级dao方法类
 * @author Administrator
 */
public class ClassDao extends EntityBaseDao<Class>
/**
 * 查询分页方法,查询数据公用方法
 * @param c
 * @param paBean
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws SQLException
 */
    public List<Class> list(Class c,PageBean paBean) throws InstantiationException, IllegalAccessException, SQLException
        String sql="select * from struts_class where true ";
        String classname=c.getClassname();
        int cid=c.getCid();
        if (cid!=0) 
            sql +=" and cid = "+cid;
        
        if (StringUtils.isNotBlank(classname)) 
            sql+=" and classname like ‘%"+classname+"%‘";
        
        return super.executeQuery(sql,paBean,Class.class);
    
    
    /**
     * 新增方法
     * @param c
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public int add(Class c) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException 
        String sql="insert into struts_class values(?,?,?)";
        return super.executeUpdate(sql, new String[] "classname","cname","upload",c);
    
    /**
     * 删除方法
     * @param c
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public int del(Class c) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException 
        String sql="delete from struts_class where cid=?";
        return super.executeUpdate(sql, new String[] "cid",c);
    
    /**
     * 修改方法
     * @param c
     * @return
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public int edit(Class c) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException 
        String sql="update struts_class set classname=?,cname=?,upload=? where cid=?";
        return super.executeUpdate(sql, new String[] "cid","classname","cname","upload",c);
    

 五:编写web层去调用dao层的方法返回数据给前台

ClassAction
package com.crud.web;
import java.sql.SQLException;
import java.util.List;
import com.crud.dao.ClassDao;
import com.crud.entity.Class;
import com.crud.util.PageBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
 * 班级web层
 * @author Administrator
 */
public class ClassAction extends BaseAction implements ModelDriven<Class>

    private ClassDao cldao=new ClassDao();
    private Class cls=new Class();
    
    public String list() 
        PageBean pageBean=new PageBean();
        pageBean.setRequest(request);
        try 
            List<Class> list = this.cldao.list(cls, pageBean);
            request.setAttribute("mylist", list);
            request.setAttribute("pageBean", pageBean);
         catch (InstantiationException | IllegalAccessException | SQLException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        return "list";
    
    /**
     * 跳转新增修改页面的公用方法
     * @return
     * @throws SQLException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    public String preSave() throws InstantiationException, IllegalAccessException, SQLException 
        if (cls.getCid()!=0) 
            Class cl = this.cldao.list(cls, null).get(0);
            request.setAttribute("cls",cl);
        
        return "preSave";
    
    /**
     * 新增
     * @return
     */
    public String add() 
        try 
            result = this.cldao.add(cls);
         catch (Exception e) 
            // TODO: handle exception
            e.printStackTrace();
        
        return "toList";
    
    /**
     * 删除
     * @return
     */
    public String del() 
        try 
            this.cldao.del(cls);
         catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        return "toList";
    
    /**
     * 修改
     * @return
     */
    public String edit() 
        try 
            this.cldao.edit(cls);
         catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        return "toList";
    
    @Override
    public Class getModel() 
        // TODO Auto-generated method stub
        return null;
    

  这里实现了一个BaseAction 类

package com.crud.web;

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

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

/**
 * 每一个开发的子控制器要用的属性都定义在通用的action中。
 * @author Administrator
 *
 */
public class BaseAction implements ServletRequestAware, ServletResponseAware
    /**
     * 为了传值使用
     */
    protected HttpServletResponse response;
    protected HttpServletRequest request;
    protected HttpSession session;
    protected ServletContext application;
    
    /**
     * 为了配置跳转页面所用
     */
    protected final static String SUCCESS = "success";
    protected final static String FAIL = "fail";
    protected final static String LIST = "list";
    protected final static String ADD = "add";
    protected final static String EDIT = "edit";
    protected final static String DETAIL = "detail";
    
    /**
     * 具体传值字段    后端向jsp页面传值所用字段
     */
    protected Object result;
    protected Object msg;
    protected int code;

    public Object getResult() 
        return result;
    

    public Object getMsg() 
        return msg;
    

    public int getCode() 
        return code;
    

    @Override
    public void setServletResponse(HttpServletResponse arg0) 
        this.response = arg0;
        
    
    @Override
    public void setServletRequest(HttpServletRequest arg0) 
        this.request = arg0;
        this.session = arg0.getSession();
        this.application = arg0.getServletContext();
    

  六:配置struts_sy.xml文件

    <!-- *代表你要调用的方法 -->
        <action name="/cls_*"  class="com.crud.web.ClassAction" method="1">
            <result name="list">/clsList.jsp</result>
            <result name="preSave">/clsupdate.jsp</result>
            <result name="toList" type="redirectAction">/cls_list</result>
        </action>

  七:连接前端显示数据并且调用实现效果

  ClsList.jsp(显示数据并且调用Crud)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="z" uri="/zking" %>
<!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">
<title>Insert title here</title>
</head>
<body>
<h2>班级</h2><br>
    <form action="$pageContext.request.contextPath /sy/cls_list.action" method="post">
        班级名:<input type="text" name="classname">
              <input type="submit" value="确定">
    </form>
    <a href="$pageContext.request.contextPath /sy/cls_preSave.action">新增</a>
    <table border="1" width="100%">
        <tr>
            <td>编号</td>
            <td>班级名</td>
            <td>学生名</td>
            <td>图片</td>
            <td>操作</td>
        </tr>    
        <c:forEach items="$mylist " var="c">
        <tr>
            <td>$c.cid </td>
            <td>$c.classname </td>
            <td>$c.cname</td>
            <td>$c.upload </td>
            <td>
                <a href="$pageContext.request.contextPath /sy/cls_preSave.action?cid=$c.cid">修改</a>&nbsp;&nbsp;
                <a href="$pageContext.request.contextPath /sy/cls_del.action?cid=$c.cid">删除</a>&nbsp;&nbsp;
                 <a href="$pageContext.request.contextPath /sy/cls_upload.action?cid=$c.cid">图片上传</a>&nbsp;&nbsp;
            </td>
        </tr>    
        </c:forEach>
    </table>
    <z:page pageBean="$pageBean "></z:page>
</body>
</html>

  Clsupdate.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">
<title>Insert title here</title>
</head>
<body>
<form action="$pageContext.request.contextPath$cls.classname ==null ? ‘/sy/cls_add.action‘ :‘/sy/cls_edit.action‘" method="post">
    cid:<input type="text" name="cid" value="$cls.cid"><br>
    classname:<input type="text" name="classname" value="$cls.classname "><br>
    cname:<input type="text" name="cname" value="$cls.cname "><br>
    upload:<input type="text" name="upload" value="$cls.upload "><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

  最后:展示效果

技术图片

 

 

 谢谢观看!今天的分享到此结束!

以上是关于Struts2连接Mysql的Crud使用的主要内容,如果未能解决你的问题,请参考以下文章

JDBC,连接池及CRUD操作

MySQL单表的CRUD及多表查询

Node.js实现对mysql数据库的crud时报加密方式错误解决方案

MySQL中使用连接查询

MySQL-进阶CRUD

strace 解决 mysql 连接数据库总是定位/tmp/mysql.sock的问题