码迷,mamicode.com
首页 > 其他好文 > 详细

实践Struts2框架

时间:2019-02-11 01:15:07      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:list   HERE   tco   title   ide   oid   信息   sql数据库   insert   

实践目标:Struts2实现学生信息的增删改查操作

问题:如何解决学生信息的增删改查

步骤:

1.连接MySql数据库操作学生信息包含两个类:Tools类和Dao类

2.创建mode类l和Action类

3.配置Struts2

4.学生信息操作的视图显示

连接MySql数据库操作学生信息

Tools类

 1 package com.thxy.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 import java.sql.PreparedStatement;
 6 import java.sql.ResultSet;
 7 import java.sql.SQLException;
 8 
 9 public class Tools {
10 
11     private static String driver = "com.mysql.jdbc.Driver";
12     private static String url = "jdbc:mysql://localhost/stu?useUnicode=true&characterEncoding=utf-8";
13     private static String user = "root";
14     private static String password = "123";
15 
16     public static Connection getConnections() {
17         Connection connection = null;
18         try {
19             Class.forName(driver);
20             try {
21                 connection = DriverManager.getConnection(url, user, password);
22             } catch (SQLException e) {
23                 e.printStackTrace();
24             }
25         } catch (ClassNotFoundException e) {
26             e.printStackTrace();
27         }
28         return connection;
29     }
30 
31     public static void closeCRP(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement) {
32 
33         if (connection != null) {
34             try {
35                 connection.close();
36                 connection = null;
37             } catch (SQLException e) {
38                 e.printStackTrace();
39             }
40         }
41         if (resultSet != null) {
42             try {
43                 resultSet.close();
44                 resultSet = null;
45             } catch (SQLException e) {
46                 e.printStackTrace();
47             }
48         }
49         if (preparedStatement != null) {
50             try {
51                 preparedStatement.close();
52                 preparedStatement = null;
53             } catch (SQLException e) {
54                 e.printStackTrace();
55             }
56         }
57     }
58 
59     public static void closeCP(Connection connection, PreparedStatement preparedStatement) {
60         if (connection != null) {
61             try {
62                 connection.close();
63                 connection = null;
64             } catch (SQLException e) {
65                 e.printStackTrace();
66             }
67         }
68         if (preparedStatement != null) {
69             try {
70                 preparedStatement.close();
71                 preparedStatement = null;
72             } catch (SQLException e) {
73                 e.printStackTrace();
74             }
75         }
76     }
77 }

Dao类

功能:

1.查询所有学生基本信息

 

 1 public ArrayList<Stu> queryStu() {
 2         List<Stu> stus = new ArrayList<>();
 3         Connection connection = Tools.getConnections();
 4         PreparedStatement preparedStatement = null;
 5         ResultSet resultSet = null;
 6         try {
 7             preparedStatement = connection.prepareStatement("select * from query");
 8             resultSet = preparedStatement.executeQuery();
 9             while (resultSet.next()) {
10                 Integer id = resultSet.getInt("id");
11                 String name = resultSet.getString("name");
12                 String gender = resultSet.getString("gender");
13                 Date birth = resultSet.getDate("birth");
14                 String age = resultSet.getString("age");
15                 String city = resultSet.getString("city");
16                 Stu stu = new Stu(id, name, gender, birth, age, city);
17                 stus.add(stu);
18             }
19         } catch (SQLException e) {
20             e.printStackTrace();
21         } finally {
22             Tools.closeCRP(connection, resultSet, preparedStatement);
23         }
24         return (ArrayList<Stu>) stus;
25     }

 

2.删除学生基本信息

 

 1 public void deleteStu(Integer id) {
 2         Connection connection = Tools.getConnections();
 3         PreparedStatement preparedStatement = null;
 4         try {
 5             preparedStatement = connection.prepareStatement("delete from query where id=?");
 6             preparedStatement.setInt(1, id);
 7             preparedStatement.executeUpdate();
 8         } catch (SQLException e) {
 9             e.printStackTrace();
10         } finally {
11             Tools.closeCP(connection, preparedStatement);
12         }
13     }

 

3.添加学生基本信息

 

 1 public void addStu(Stu stu) {
 2         Connection connection = Tools.getConnections();
 3         PreparedStatement preparedStatement = null;
 4         try {
 5             preparedStatement = connection
 6                     .prepareStatement("insert into query(id,name,gender,birth,age,city) values(?,?,?,?,?,?)");
 7             preparedStatement.setInt(1, stu.getId());
 8             preparedStatement.setString(2, stu.getName());
 9             preparedStatement.setString(3, stu.getGender());
10             preparedStatement.setDate(4, stu.getBirth());
11             preparedStatement.setString(5, stu.getAge());
12             preparedStatement.setString(6, stu.getCity());
13             preparedStatement.executeUpdate();
14         } catch (SQLException e) {
15             e.printStackTrace();
16         } finally {
17             Tools.closeCP(connection, preparedStatement);
18         }
19     }

 

4.更改学生基本信息

 

 1 public void editStu(Stu stu) {
 2         Connection connection = Tools.getConnections();
 3         PreparedStatement preparedStatement = null;
 4         try {
 5             preparedStatement = connection
 6                     .prepareStatement("update query set name=?,gender=?,birth=?,age=?,city=? where id=?");
 7             preparedStatement.setString(1, stu.getName());
 8             preparedStatement.setString(2, stu.getGender());
 9             preparedStatement.setDate(3, stu.getBirth());
10             preparedStatement.setString(4, stu.getAge());
11             preparedStatement.setString(5, stu.getCity());
12             preparedStatement.setInt(6, stu.getId());
13             preparedStatement.executeUpdate();
14         } catch (SQLException e) {
15             e.printStackTrace();
16         } finally {
17             Tools.closeCP(connection, preparedStatement);
18         }
19     }

 

5.查询指定学生信息

 1 public Stu updateStu(Integer id) {
 2         Connection connection = Tools.getConnections();
 3         PreparedStatement preparedStatement = null;
 4         ResultSet resultSet = null;
 5         Stu stu = null;
 6         try {
 7             preparedStatement = connection.prepareStatement("select * from query where id=?");
 8             preparedStatement.setInt(1, id);
 9             resultSet = preparedStatement.executeQuery();
10             while (resultSet.next()) {
11                 String name = resultSet.getString("name");
12                 String gender = resultSet.getString("gender");
13                 Date birth = resultSet.getDate("birth");
14                 String age = resultSet.getString("age");
15                 String city = resultSet.getString("city");
16                 stu = new Stu(id, name, gender, birth, age, city);
17             }
18         } catch (SQLException e) {
19             e.printStackTrace();
20         } finally {
21             Tools.closeCRP(connection, resultSet, preparedStatement);
22         }
23         return stu;
24     }

创建model类和Action类

model类(学生基本信息类)

 1 public class Stu {
 2     private Integer id;
 3     private String name;
 4     private String gender;
 5     private Date birth;
 6     private String age;
 7     private String city;
 8 
 9     public Integer getId() {
10         return id;
11     }
12 
13     public void setId(Integer id) {
14         this.id = id;
15     }
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public String getGender() {
26         return gender;
27     }
28 
29     public void setGender(String gender) {
30         this.gender = gender;
31     }
32 
33     public Date getBirth() {
34         return birth;
35     }
36 
37     public void setBirth(Date birth) {
38         this.birth = birth;
39     }
40 
41     public String getAge() {
42         return age;
43     }
44 
45     public void setAge(String age) {
46         this.age = age;
47     }
48 
49     public String getCity() {
50         return city;
51     }
52 
53     public void setCity(String city) {
54         this.city = city;
55     }
56 
57     @Override
58     public String toString() {
59         return "Stu [id=" + id + ", name=" + name + ", gender=" + gender + ", birth=" + birth + ", age=" + age
60                 + ", city=" + city + "]";
61     }
62 
63     public Stu(Integer id, String name, String gender, Date birth, String age, String city) {
64         super();
65         this.id = id;
66         this.name = name;
67         this.gender = gender;
68         this.birth = birth;
69         this.age = age;
70         this.city = city;
71     }
72 
73     public Stu() {
74         super();
75     }
76 }

 

action类

1.查询所有学生基本信息

 1 public class StuAction extends ActionSupport implements RequestAware {
 2     private static final long serialVersionUID = 1L;
 3     private Map<String, Object> request;
 4     private Dao dao = new Dao();
 5 
 6     public String query() {
 7         request.put("stus", dao.queryStu());
 8         return "query";
 9     }
10 }

配置Struts2

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 <struts>
 6     <constant name="struts.action.extension" value="action,do,"></constant>
 7     <package name="stu" namespace="/" extends="struts-default">
 8         <action name="stu-*" class="com.thxy.stu.StuAction"
 9             method="{1}">
10             <result name="{1}" type="dispatcher">/files/stu-{1}.jsp</result>
11         </action>
12     </package>
13 </struts>

学生信息操作的视图显示

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib prefix="s" uri="/struts-tags"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>查询学生基本信息</title>
 9 <style>
10 a {
11     display: block;
12     text-align: center;
13     text-decoration: none
14 }
15 </style>
16 </head>
17 <body>
18     <h1>查询学生基本信息</h1>
19     <s:debug></s:debug>
20     <table cellpadding="10" cellspacing="0" border="2">
21         <thead>
22             <tr>
23                 <td>学号</td>
24                 <td>姓名</td>
25                 <td>性别</td>
26                 <td>出生日期</td>
27                 <td>年龄</td>
28                 <td>居住地</td>
29                 <td>删除</td>
30                 <td>编辑</td>
31             </tr>
32         </thead>
33         <tbody>
34             <s:iterator value="#request.stus">
35                 <tr>
36                     <td><s:property value="id"></s:property></td>
37                     <td><s:property value="name"></s:property></td>
38                     <td><s:property value="gender"></s:property></td>
39                     <td><s:property value="birth"></s:property></td>
40                     <td><s:property value="age"></s:property></td>
41                     <td><s:property value="city"></s:property></td>
42                     <td><a href="stu-delete.do?id=${id}">delete</a></td>
43                     <td><a href="stu-update.do?id=${id}">update</a></td>
44                 </tr>
45             </s:iterator>
46         </tbody>
47     </table>
48     <a href="/Struts2-3/files/stu-add.jsp">添加学生</a>
49 </body>
50 </html>

技术图片

2.删除指定学生基本信息

 

 1 public class StuAction extends ActionSupport {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Integer id;
 5 
 6     public void setId(Integer id) {
 7         this.id = id;
 8     }
 9 
10     public String delete() {
11         dao.deleteStu(id);
12         return "delete";
13     }
14 }

 

配置Struts.xml

1 <result name="delete" type="redirectAction">stu-query</result>

技术图片

3.添加学生基本信息

 1 public class StuAction extends ActionSupport  {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Integer id;
 5     private String name;
 6     private String gender;
 7     private Date birth;
 8     private String age;
 9     private String city;
10 
11     public void setName(String name) {
12         this.name = name;
13     }
14 
15     public void setGender(String gender) {
16         this.gender = gender;
17     }
18 
19     public void setBirth(Date birth) {
20         this.birth = birth;
21     }
22 
23     public void setAge(String age) {
24         this.age = age;
25     }
26 
27     public void setCity(String city) {
28         this.city = city;
29     }
30 
31     public void setId(Integer id) {
32         this.id = id;
33     }
34 
35     public String add() {
36         Stu stu = new Stu(id, name, gender, birth, age, city);
37         dao.addStu(stu);
38         return "add";
39     }
40 }

配置Struts.xml

1 <result name="add" type="redirectAction">stu-query</result>

技术图片

4.查看学生基本信息并修改

 1 public class StuAction extends ActionSupport  {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Integer id;
 5     private String name;
 6     private String gender;
 7     private Date birth;
 8     private String age;
 9     private String city;
10 
11     public void setName(String name) {
12         this.name = name;
13     }
14 
15     public void setGender(String gender) {
16         this.gender = gender;
17     }
18 
19     public void setBirth(Date birth) {
20         this.birth = birth;
21     }
22 
23     public void setAge(String age) {
24         this.age = age;
25     }
26 
27     public void setCity(String city) {
28         this.city = city;
29     }
30 
31     public void setId(Integer id) {
32         this.id = id;
33     }
34     
35     public String update() {
36         Stu stu=dao.updateStu(id);
37         ActionContext.getContext().getValueStack().push(stu);
38         return "update";
39     }
40 
41     public String edit() {
42         Stu stu=new Stu(id, name, gender, birth, age, city);
43         dao.editStu(stu);
44         return "edit";
45     }
46 }

配置struts.xml

1 <result name="{1}" type="dispatcher">/files/stu-{1}.jsp</result>
2 <result name="edit" type="redirectAction">stu-query</result>

技术图片

技术图片

此时可以发现一个问题在删除;查看和修改学生基本信息时Action请求类中的代码和Model类中代码重复,我们不应该在Action类中写重复的Model代码所以我们应该将Action类中与Model中重复代码去掉,此时我们引用ModelDriven接口的技术

Action类

 1 public class StuAction extends ActionSupport implements RequestAware, ModelDriven<Stu> {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Stu stu;
 5 
 6     public String update() {
 7         Stu student = dao.updateStu(stu.getId());
 8         ActionContext.getContext().getValueStack().push(student);
 9         return "update";
10     }
11 
12     public String edit() {
13         dao.editStu(stu);
14         return "edit";
15     }
16 
17     public String add() {
18         dao.addStu(stu);
19         return "add";
20     }
21 
22     public String delete() {
23         dao.deleteStu(stu.getId());
24         return "delete";
25     }
26 
27     private Map<String, Object> request;
28 
29     @Override
30     public void setRequest(Map<String, Object> arg0) {
31         request = arg0;
32     }
33 
34     public String query() {
35         request.put("stus", dao.queryStu());
36         return "query";
37     }
38 
39     @Override
40     public Stu getModel() {
41         stu = new Stu();
42         return stu;
43     }
44 }

通过使用ModelDriven接口把Action类中的Model代码去掉,同时也实现了学生基本信息的增删改查功能,但是在执行修改和查找特定学生基本信息的时候由值栈来看出现了两个Model被压入值栈造成空间浪费,我们是否在执行业务的时候判断是否含有主键id再来执行相关操作避免重复创建对象

技术图片

 

Action类

 1 public class StuAction extends ActionSupport implements RequestAware, ModelDriven<Stu> {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Stu stu;
 5     private Integer id;
 6 
 7     public void setId(Integer id) {
 8         this.id = id;
 9     }
10 
11     public String update() {
12         return "update";
13     }
14 
15     public String edit() {
16         dao.editStu(stu);
17         return "edit";
18     }
19 
20     public String add() {
21         dao.addStu(stu);
22         return "add";
23     }
24 
25     public String delete() {
26         dao.deleteStu(stu.getId());
27         return "delete";
28     }
29 
30     private Map<String, Object> request;
31 
32     @Override
33     public void setRequest(Map<String, Object> arg0) {
34         request = arg0;
35     }
36 
37     public String query() {
38         request.put("stus", dao.queryStu());
39         return "query";
40     }
41 
42     @Override
43     public Stu getModel() {
44         if (id == null) {
45             stu = new Stu();
46         } else {
47             stu = dao.updateStu(id);
48         }
49         return stu;
50     }
51 }

配置struts.xml文件

<default-interceptor-ref
name="paramsPrepareParamsStack">
</default-interceptor-ref>

由上述代码看出在执行学生基本信息的增加删除修改查找的时候判断执行的业务是否有参数如id,若有参数getModel返回由数据库返回的Model对象,若无参数getModel返回Model对象,但是在执行增加;删除和查询的时候,不能指定增加id报空指针的错误,删除的时候直接赋值id即可没有必要从数据库加载一个对象压入值栈,在查询所以学生基本信息的时候也创建了一个对象造成了内存空间的浪费,此时实现Preparable接口对所有的方法执行指定的预处理方法prepare[MethodName]即可

Action类

 1 public class StuAction extends ActionSupport implements RequestAware, ModelDriven<Stu>,Preparable {
 2     private static final long serialVersionUID = 1L;
 3     private Dao dao = new Dao();
 4     private Stu stu;
 5     private Integer id;
 6     public void setId(Integer id) {
 7         this.id = id;
 8     }
 9     public String update() {
10         return "update";
11     }
12     public void prepareUpdate() throws Exception {
13         stu=dao.updateStu(id);    
14     }
15 
16     public String edit() {
17         dao.editStu(stu);
18         return "edit";
19     }
20     public void prepareEdit() throws Exception {
21         stu=new Stu();    
22     }
23     public String add() {
24         dao.addStu(stu);
25         return "add";
26     }
27     public void prepareAdd() throws Exception {
28         stu=new Stu();    
29     }
30 
31     public String delete() {
32         dao.deleteStu(stu.getId());
33         return "delete";
34     }
35     public void prepareDelete() throws Exception {
36         stu=new Stu();    
37     }
38 
39     private Map<String, Object> request;
40 
41     @Override
42     public void setRequest(Map<String, Object> arg0) {
43         request = arg0;
44     }
45 
46     public String query() {
47         request.put("stus", dao.queryStu());
48         return "query";
49     }
50 
51     @Override
52     public Stu getModel() {
53         return stu;
54     }
55 
56     @Override
57     public void prepare() throws Exception {
58         System.out.println("prepare...");
59     }
60 }

上面修改的代码完美解决了在执行删除和修改操作时从数据库中加载了一个对象影响了运行的效率;也解决了查询学生所有基本信息时创建一个对象造成内存空间的浪费,与此同时在实现了Preparable接口的同时每次执行业务逻辑都会实现prepare方法然而我们并不需要他,我们应该使他不执行提高代码的运行效率,提高代码的质量,我们需要在struts.xml中配置拦截器

配值struts.xml文件代码如下

<interceptors>
    <interceptor-stack name="myStack">
        <interceptor-ref name="paramsPrepareParamsStack">
    <param name="prepare.alwaysInvokePrepare">false</param>
        </interceptor-ref>
    </interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"/>

 

此时已经大体完成了对学生基本信息的查询,增加,删除,更改,查找,但是我们还需要关注一下在增加的业务逻辑操作时是否还需要对信息进行验证呢?我们开发的系统都是为了服务用户的,良好的信息验证是解决大部分用户的错误操作导致的不必要的bug

信息验证

配置StuAction.properties文件

invalid.fieldvalue.birth=\u9519\u8BEF\u65E5\u671F\u683C\u5F0F
invalid.fieldvalue.id=\u9519\u8BEF\u5B66\u53F7\u683C\u5F0F
invalid.fieldvalue.name=\u9519\u8BEF\u59D3\u540D\u683C\u5F0F

配置struts.xml文件

<result name="input">/files/error.jsp</result>

显示错误视图

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib prefix="s" uri="/struts-tags"%>
 4 <!DOCTYPE html>
 5 <html>
 6 <head>
 7 <meta charset="UTF-8">
 8 <title>错误页面</title>
 9 <style>
10 a {
11     display: block;
12     text-align: center;
13     text-decoration: none
14 }
15 </style>
16 </head>
17 <body>
18     <s:fielderror fieldName="id"></s:fielderror>
19     <s:fielderror fieldName="name"></s:fielderror>
20     <s:fielderror fieldName="birth"></s:fielderror>
21     <a href="/Struts2-3/files/stu-add.jsp">返回</a>
22 </body>
23 </html>

 

自定义日期转换器

1.配置xwork-conversion.properties文件

com.thxy.stu.Stu=com.thxy.Converter.DateTypeConverter

2.配置类型转换器的类

 1 package com.thxy.Converter;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.Map;
 6 import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
 7 
 8 public class DateTypeConverter extends DefaultTypeConverter {
 9     @Override
10     public Object convertValue(Map<String, Object> context, Object value, Class toType) {
11         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
12         try {
13             if (toType == Date.class) { // 当字符串向Date类型转换时
14                 String[] params = (String[]) value;
15                 return sdf.parseObject(params[0]);
16             } else if (toType == String.class) { // 当Date转换成字符串时
17                 Date date = (Date) value;
18                 return sdf.format(date);
19             }
20         } catch (java.text.ParseException e) {
21             e.printStackTrace();
22         }
23         return null;
24     }
25 }

技术图片

加上信息验证提高用户体验的struts2学生基本信息的增加,删除,查找,查询,更改操作的小项目就完美了。

备注:这是基于struts2框架大体内容形成的学生基本信息的增加,删除,查找,查询,更改操作,本人在校大学生,用小项目自学框架,如果小项目用到的知识点或者思考的思路不正确请指正,我相信经过你们的留言和指教我们都会变得更好,世界将会变得更完美

 

实践Struts2框架

标签:list   HERE   tco   title   ide   oid   信息   sql数据库   insert   

原文地址:https://www.cnblogs.com/KYAOYYW/p/10358113.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!