数据库连接是一个项目非常重要,不可缺少的一环。在学习了Struts框架之后,将数据库也专门研究了一下。
首先我们需要在数据库中建一张表用来存储我们的数据,这里就以用户登录注册为例
1.建表
设置好它的每一项属性值,并要勾选“自动递增”,否则不能向数据库中写入多条记录。
2.建立连接_Dbutil.java
package com.mysql.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Dbutil {
private final String DBURL ="jdbc:mysql://localhost:3306/db";
private final String DBUSER = "root";
private final String DBPASSWORD = "123456";
private Connection con = null;
private PreparedStatement stmt = null;
private ResultSet rs = null;
public Dbutil(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public ResultSet executeQuery(String sql,Object... params) {//可变参数
try {
stmt = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
this.stmt.setObject(i+1, params[i]);
}
rs = stmt.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
return rs;
}
public int executeUpdate(String sql,Object... params){
int result = 0;
try {
stmt = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
this.stmt.setObject(i+1, params[i]);
}
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
3.书写类_Person.java
package com.mysql.pojo;
public class Person {
private String name;
private String password;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
4.为对象书写方法
1)登录action_LoginAction.java
package com.mysql.action;
import java.sql.ResultSet;
import com.mysql.pojo.Person;
import com.mysql.util.Dbutil;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private Person persona = new Person();
public Person getPersona() {
return persona;
}
public void setPersona(Person persona) {
this.persona = persona;
}
@Override
public String execute() throws Exception {
Dbutil dButil = new Dbutil();
ResultSet rs = null;
String sql = "select * from person p where p.name=? and p.password=?";
rs = dButil.executeQuery(sql, persona.getName(),persona.getPassword());
if(rs.next()){
dButil.close();
return SUCCESS;
}else{
dButil.close();
return ERROR;
}
}
}
2)注册action_RegisterAction.java
package com.mysql.action;
import com.mysql.pojo.Person;
import com.mysql.util.Dbutil;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport{
private Person persona = new Person();
public Person getPersona() {
return persona;
}
public void setPersona(Person persona) {
this.persona = persona;
}
@Override
public String execute() throws Exception {
Dbutil dbutil = new Dbutil();
String sql="insert into person(name,password,email) values(?,?,?)";
int executeUpdate = dbutil.executeUpdate(sql,persona.getName(),persona.getPassword(),persona.getEmail());
if(executeUpdate==1){
dbutil.close();
return SUCCESS;
}else {
dbutil.close();
return ERROR;
}
}
}
5.输入界面
1)登录界面_login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<s:form action="login">
<s:textfield name="persona.name" label="姓名"/>
<s:password name="persona.password" label="密码"/>
<s:submit value="登陆"/>
</s:form>
<a href="<s:url action="register"/>">注册</a>
<s:debug></s:debug>
</body>
</html>
2)注册界面_register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'register.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:form action="register">
<s:textfield name="persona.name" label="姓名"/>
<s:password name="persona.password" label="密码"/>
<s:textfield name="persona.email" label="邮箱" />
<s:submit value="注册"/>
</s:form>
</body>
</html>
6.返回界面
1)登录成功_success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'success.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<h1>Welcome</h1>
<body>
<s:property value="person.name"/>
</body>
</html>
2)登录失败_error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'error.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
error!
</body>
</html>
6.Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="strutsLogin" extends="struts-default">
<action name="register" class="com.mysql.action.RegisterAction">
<result name="success">/login.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="login" class="com.mysql.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
7.web.xml
<?xml version="1.0" encoding="GBK"?>
<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">
<!-- 定义Struts 2的核心Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- 让Struts 2的核心Filter拦截所有请求 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
#运行结果