step1:创建一个动态web应用,配置web.xml文件。导入struts2和连接mysql的架包,并添加到环境变量中。
<display-name>struts2-02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
step2:在mysql中新建一个数据库imooc,准备一个user.sql文件,生成struts_user数据表。
step3:新建一个DBUTil类连接mysql数据库,并返回数据库的连接。
private static String URL="jdbc:mysql://127.0.0.1:8080/imooc";
private static String USER="root";
private static String PASSWORD="2111503016";
private static Connection conn=null;
static {
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2.获得数据库的连接
conn=DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return conn;
}
step4:新建一个实体类,用于映射数据库的user表,如下的User.java
public class User {
public class Goddess {
//创建数据库对应的类,创建模型
private Integer id;
private String user_name;
private Integer sex;
private Integer age;
………………
step 5:新建一个学生管理系统的注册界面register.html
<form id="signupForm" action="register" method="post">
………………
在struts.xml文件中配置相应的action
<action name="register" class="com.gmx.action.RegisterAction">
<result>/login.jsp</result>
<result name="error">/register.jsp</result>
</action>
<link href="resources/style/bootstrap.min.css" rel="stylesheet">
<script src="resources/js/jquery-1.11.1.min.js"></script>
<script src="resources/js/jquery.validate.min.js"></script>
<script src="resources/js/bootstrap.min.js"></script>
引入外部资源时,<script src="/resources/js/bootstrap.min.js"></script>
若前面加了斜杠,则请求的URL为http://localhost:8080/resources/js/jquery.validate.min.js
若不加斜杠,则请求的URL为
http://localhost:8080/struts2-02/resources/js/jquery.validate.min.js
所以前面不能加“/”,否则请求不到struts2-02的资源文件!!
actionname!methodname方式调用action类中的methodname方法时,此方法必须是public且没有参数。
未完待续……