struts2完成简单的增删改查
action包
添加
package action; import bean.Bean; import com.opensymphony.xwork2.ActionSupport; import dao.Dao; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; //import utils.MD5Util; public class AddAction extends ActionSupport { private Bean bean; public String add() throws Exception{ Dao dao = new Dao(); HttpServletRequest request = ServletActionContext.getRequest(); int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String sex = request.getParameter("sex"); String grade = request.getParameter("grade"); String State = request.getParameter("State"); bean = new Bean(id,name,sex,grade,State); System.out.println(bean); if(dao.insert(bean)) { return "success"; } return "error"; } public void setBean(Bean bean) { this.bean = bean; } public Bean getBean() { return bean; } }
删除
package action; import dao.Dao; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; public class DeleteAction { private String name; public String execute() throws Exception { Dao dao = new Dao(); HttpServletRequest request = ServletActionContext.getRequest(); name = request.getParameter("name"); // System.out.println(name); if(dao.delete(name)){ return "delete"; } return "error"; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
查询
package action; import bean.Bean; import dao.Dao; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.List; public class ListAction { public String execute() throws Exception { Dao dao = new Dao(); HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); List<Bean> list = null; list = dao.list(); request.setAttribute("list", list); // System.out.println(list.size()); request.getRequestDispatcher("list.jsp").forward(request,response); return "queryAll"; }
修改
package action; import bean.Bean; import dao.Dao; import org.apache.struts2.ServletActionContext; import javax.servlet.http.HttpServletRequest; public class UpdataAction { private Bean bean; public String execute() throws Exception { Dao dao = new Dao(); HttpServletRequest request = ServletActionContext.getRequest(); int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String sex = request.getParameter("sex"); String grade = request.getParameter("grade"); String State = request.getParameter("state"); bean = new Bean(id,name,sex,grade,State); System.out.println(bean); if(dao.update(bean)){ return "updata"; } return "error"; } public Bean getBean() { return bean; } public void setBean(Bean bean) { this.bean = bean; } }
bean包
package bean; public class Bean { private int id; private String name; private String sex; private String grade; private String State; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getState() { return State; } public void setState(String state) { State = state; } @Override public String toString() { return "Bean{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", grade='" + grade + '\'' + ", State='" + State + '\'' + '}'; } public Bean(int id, String name, String sex, String grade, String state) { this.id = id; this.name = name; this.sex = sex; this.grade = grade; this.State = state; } }
dao包
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import bean.Bean; import db.DBUtil; public class Dao {//dao层 private DBUtil dbutil=new DBUtil(); public Dao() { // TODO Auto-generated constructor stub } //注册 public boolean insert(Bean bean) {//插入数据的方法 boolean f=false; String sql="insert into personinfo(id,name,sex,grade,state) values('"+bean.getId()+"','"+bean.getName()+"','"+bean.getSex()+"','"+bean.getGrade()+"','"+bean.getState()+"')"; Connection conn=DBUtil.getConnection();//数据库连接,加载驱动 Statement state=null; try { state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作 System.out.println(conn); state.executeUpdate(sql); f=true; //执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句, //例如CREATETABLE和DROPTABLE,(创建表和删除表) }catch(Exception e)//当try语句中s出现异常时,会执行catch中的语句 { e.printStackTrace();//捕获异常的语句 } finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。 { DBUtil.close(conn); } return f; } //用户登入 public int check(String username,String password) throws SQLException { DBUtil db=new DBUtil(); String sql="select * from personinfo where id ="+username+" and name ="+password; Connection con=db.getConnection(); PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); int s=0; if(rs.next()) { s=1; } return s; } //查询 public List<Bean> list(){//查询所有方法 String sql="select * from personinfo order by id ASC"; Connection conn=DBUtil.getConnection(); Statement st=null; List<Bean> list=new ArrayList<>(); ResultSet rs=null; Bean bean=null; try { st=conn.createStatement(); st.executeQuery(sql); rs=st.executeQuery(sql); while(rs.next()) { int id=rs.getInt("id"); String name = rs.getString("name"); String sex = rs.getString("sex"); String grade = rs.getString("grade"); String state = rs.getString("state"); bean=new Bean(id,name,sex,grade,state); list.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return list; } public List<Bean> searchByUsername(String str) throws SQLException{//查询条件方法 String sql="select * from personinfo where(name like '%"+str+"%')"; Connection conn=DBUtil.getConnection(); Statement st=null; PreparedStatement pt = conn.prepareStatement(sql); List<Bean> search=new ArrayList<>(); ResultSet rs=null; Bean bean=null; try { pt=conn.prepareStatement(sql); rs=pt.executeQuery(); while(rs.next()) { int id=rs.getInt("id"); String name = rs.getString("name"); String sex = rs.getString("sex"); String grade = rs.getString("grade"); String state = rs.getString("state"); bean=new Bean(id,name,sex,grade,state); search.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return search; } public List<Bean> searchById(String str) throws SQLException{//查询条件方法 String sql="select * from personinfo where(id like '%"+str+"%')"; Connection conn=DBUtil.getConnection(); Statement st=null; PreparedStatement pt = conn.prepareStatement(sql); List<Bean> search=new ArrayList<>(); ResultSet rs=null; Bean bean=null; try { pt=conn.prepareStatement(sql); rs=pt.executeQuery(); while(rs.next()) { int id=rs.getInt("id"); String name = rs.getString("name"); String sex = rs.getString("sex"); String grade = rs.getString("grade"); String state = rs.getString("state"); bean=new Bean(id,name,sex,grade,state); search.add(bean); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { DBUtil.close(rs, st, conn); } return search; } //删除 public boolean delete(String name) {//删除方法 String sql="delete from personinfo where name='"+name+"'"; boolean f=false; Connection conn =DBUtil.getConnection(); Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ DBUtil.close(st, conn); } return f; } //修改 public boolean update(Bean bean) {//更新方法 String sql="update personinfo set id='"+bean.getId()+"',name='"+bean.getName()+"',sex='"+bean.getSex()+"',grade='"+bean.getGrade()+"',state='"+bean.getState()+"'where id='"+bean.getId()+"'"; Connection conn=DBUtil.getConnection(); boolean f=false; Statement st=null; try { st=conn.createStatement(); st.executeUpdate(sql); f=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return f; } public int admin(String username,String password)throws SQLException { if((username).equals(1)&& (password).equals(1)) { return 0; } return 1; } }
数据库连接
package db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBUtil { private static String jdbcName = "com.mysql.cj.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/test?serverTimezone=GMT&useSSL=false"; private static String user = "root"; private static String password = "Akko"; private Connection con=null; public static Connection getConnection() { Connection con=null; try { Class.forName(jdbcName); con=DriverManager.getConnection(url, user, password); //System.out.println("数据库连接成功"); } catch (Exception e) { // TODO Auto-generated catch block //System.out.println("数据库连接失败"); e.printStackTrace(); } try { con = DriverManager.getConnection(url,user,password); System.out.println("连接成功"); } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } return con; } public static void main(String[] args)throws SQLException { Connection conn = getConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sql ="select * from personinfo"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); System.out.println(getConnection()); while(rs.next()){ System.out.println("成功"); } } // return con; public static void close(Connection con) { if(con!=null) try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(Statement state, Connection conn) { if(state!=null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(ResultSet rs, Statement state, Connection conn) { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(state!=null) { try { state.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
jsp页面
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% Object message = request.getAttribute("message"); Object grade_list = request.getAttribute("grade_list"); if(message!=null && !"".equals(message)){ %> <script type="text/javascript"> alert("<%=request.getAttribute("message")%>"); </script> <%} %> <div align="center"> <h1 >信息列表</h1> <h1> <form action="list.action" method="post"> <%-- <select name="cxfs">--%> <%-- <option id="cxfs"value ="1">状态</option>--%> <%-- <option id="cxfs" value ="2">容纳人数</option>--%> <%-- </select>--%> <input type="text" id="value" name="value" placeholder="请输入条件"> <input type="submit" id="select" name="select" value="查询" /> </form> </h1> <a href="add.jsp">添加</a> <table > <tr> <td>学号</td> <td>姓名</td> <td>性别</td> <td>学级</td> <td>状态</td> <td align="center" colspan="2">操作</td> </tr> <c:forEach items="${list}" var="item"> <tr> <td>${item.id}</td> <td>${item.name}</td> <td>${item.sex}</td> <td>${item.grade}</td> <td>${item.state}</td> <td><a href="updata.jsp?id=${item.id}&name=${item.name}&sex=${item.sex}&grade=${item.grade}&State=${item.state}">修改</a></td> <td><a href="delete.action?name=${item.name}">删除</a></td> </tr> </c:forEach> </table> </div> </body> </html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>添加</title> </head> <body> <div align="center"> <h1>添加学生</h1> <a href="list.jsp">返回</a> <form action="Add.action" method="post"> <table id="addTable" class="table table-bordered "> <tr class="text-center row"> <tr> <td class="col-sm-2"> 学号 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="id" id="id" > </td> <tr class="text-center row"> <td class="col-sm-2"> 姓名 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="name" id="name" > </td></tr> <tr> <td class="col-sm-2"> 性别 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="sex" id="sex" > </td> </tr> <tr> <td class="col-sm-2"> 学级 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="grade" id="grade" > </td> </tr> <tr> <td class="col-sm-2"> 状态 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="State" id="State" > </td> </tr> </table> <input type="submit" value="添加" onclick= "return check()" /> </form> </div> </body> </html>
updata.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>修改</title> </head> <body> <div align="center"> <h1>修改</h1> <a href="list.jsp">返回主页</a> <form action="updata.action" method="get"> <table id="addTable" class="table table-bordered "> <tr class="text-center row"> <tr> <td class="col-sm-2"> 学号 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="id" id="id" > </td> <tr class="text-center row"> <td class="col-sm-2"> 姓名 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="name" id="name" > </td></tr> <tr> <td class="col-sm-2"> 性别 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="sex" id="sex" > </td> </tr> <tr> <td class="col-sm-2"> 学级 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="grade" id="grade" > </td> </tr> <tr> <td class="col-sm-2"> 状态 </td> <td class="col-sm-4"> <input type="text" class="form-control" name="state" id="state" > </td> </tr> </table> <div> <input type="submit" value="修改" onclick= "return check()" /> </div> </form> </div> </body> </html>
struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8"/> <constant name="struts.action.excludePattern" value="/static/.*?" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.action.extension" value="action,do,,xhtml,xml,json"/> <package name="strutsBean" extends="struts-default" namespace="/"> <action name="Add" class="action.AddAction" method="add"> <!-- <result name="success">/loginSuccess.jsp</result>--> <!-- <result name="fail">/loginFail.jsp</result>--> <result name="success">/add.jsp</result> <result name="error">/error.jsp</result> <allowed-methods>add</allowed-methods> </action> <action name="list" class="action.ListAction" > <result name="queryAll">/list.jsp</result> </action> <action name="delete" class="action.DeleteAction"> <result name="delete">/list.jsp</result> <result name="error">/error.jsp</result> </action> <action name="updata" class="action.UpdataAction"> <result name="updata">/updata.jsp</result> <result name="error">/error.jsp</result> </action> </package> </struts>
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <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_4_0.xsd" version="4.0"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>add.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
Object grade_list = request.getAttribute("grade_list");
if(message!=null && !"".equals(message)){
%>
<script type="text/javascript">
alert("<%=request.getAttribute("message")%>");
</script>
<%} %>
<div align="center">
<h1 >信息列表</h1>
<h1>
<form action="list.action" method="post">
<%-- <select name="cxfs">--%>
<%-- <option id="cxfs"value ="1">状态</option>--%>
<%-- <option id="cxfs" value ="2">容纳人数</option>--%>
<%-- </select>--%>
<input type="text" id="value" name="value" placeholder="请输入条件">
<input type="submit" id="select" name="select" value="查询" />
</form>
</h1>
<a href="add.jsp">添加</a>
<table >
<tr>
<td>学号</td>
<td>姓名</td>
<td>性别</td>
<td>学级</td>
<td>状态</td>
<td align="center" colspan="2">操作</td>
</tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.sex}</td>
<td>${item.grade}</td>
<td>${item.state}</td>
<td><a href="updata.jsp?id=${item.id}&name=${item.name}&sex=${item.sex}&grade=${item.grade}&State=${item.state}">修改</a></td>
<td><a href="delete.action?name=${item.name}">删除</a></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>