1.在mysql数据库中创建student数据库,创建studentInfo表(id,name,age)其中id是自动增加的键。
2.创建web工程后,将java连接mysql的驱动粘贴至图中所示位置,同时在src下创建配置文件connectDB.properties
connectDB.properties文件的内容为(根据自己的账号密码情况修改):
url jdbc:mysql://localhost:3306/student
driver com.mysql.jdbc.Driver
username root
password 123
src下创建包com.amaker.util,在util包下创建DBUtil类,以实现java对mysql数据库的连接和关闭
package com.amaker.util;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
public Connection openConnection()
{
String url=null;
String driver=null;
String username=null;
String password=null;
Connection conn=null;
Properties prop=new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("connectDB.properties"));
url=prop.getProperty("url");
driver=prop.getProperty("driver");
username=prop.getProperty("username");
password=prop.getProperty("password");
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void closeConnection(Connection conn)
{
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
3. src下创建包com.amaker.bean,com.amaker.Dao,com.amaker.daoImpl
bean包下创建Student类
package com.amaker.bean;
public class Student {
String id;
String name;
int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Dao包下创建接口StuDao
package com.amaker.Dao;
import java.util.List;
import com.amaker.bean.Student;
public interface StuDao {
public boolean save(Student s);
public List list();
}
daoImpl包下创建实现接口StuDao的StuDaoImpl类
package com.amaker.daoImpl;
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 com.amaker.Dao.StuDao;
import com.amaker.bean.Student;
import com.amaker.util.DBUtil;
public class StuDaoImpl implements StuDao {
/*
public static void main(String args[])
{
Student s=new Student();
s.setName("sunxuejiao");
s.setAge(24);
StuDaoImpl stuDao=new StuDaoImpl();
stuDao.save(s);
List list=stuDao.list();
for(int i=0;i<list.size();i++)
{
Student s1=(Student)list.get(i);
System.out.println(s1.getId());
System.out.println(s1.getName());
System.out.println(s1.getAge());
}
}*/
public List list() {
List list=new ArrayList();
DBUtil util=new DBUtil();
Connection conn=util.openConnection();
String sql=" select id,name,age from studentInfo ";
try {
Statement statement=conn.createStatement();
ResultSet rs=statement.executeQuery(sql);
while(rs.next())
{
String id=rs.getString("id");
String name=rs.getString("name");
int age=rs.getInt("age");
Student s=new Student();
s.setId(id);
s.setName(name);
s.setAge(age);
list.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
util.closeConnection(conn);
}
return list;
}
public boolean save(Student s) {
boolean successful=true;
String sql=" insert into studentInfo(name,age) values (?,?) ";
DBUtil util=new DBUtil();
Connection conn=util.openConnection();
try {
PreparedStatement statement=conn.prepareStatement(sql);
statement.setString(1, s.getName());
statement.setString(2, new Integer(s.getAge()).toString());
statement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
successful=false;
e.printStackTrace();
}
finally{
util.closeConnection(conn);
return successful;
}
}
}
4.在web-root下创建文件夹pages,在pages下创建MyJsp.jsp,提供输入学生信息的页面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String myPath=path+"/servlet/StudentServlet";
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 'MyJsp.jsp' starting page</title>
</head>
<body>
<form name="f1" id="f1" action=<%= myPath%> method="post">
<table border="0">
<tr>
<td>name:</td>
<td><input type="text" name="name" ></td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" name="age" ></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="save"></td>
</tr>
</table>
</form>
</body>
</html>
5.在src下创建包com.amaker.servlet,创建StudentServlet类
package com.amaker.servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.amaker.bean.Student;
import com.amaker.daoImpl.StuDaoImpl;
public class StudentServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public StudentServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
int age=new Integer(request.getParameter("age")).intValue();
Student s=new Student();
s.setName(name);
s.setAge(age);
StuDaoImpl sd=new StuDaoImpl();
boolean successful=sd.save(s);
request.setAttribute("successful", successful);
System.out.println("succussful!");
request.getRequestDispatcher("/pages/result.jsp").forward(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
6.web.xml中配置该servlet
<servlet>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>com.amaker.servlet.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/servlet/StudentServlet</url-pattern>
</servlet-mapping>
7.在web-root下创建包pages,在pages下创建保存学生信息成功后的界面,查询出所有学生的信息result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.amaker.daoImpl.StuDaoImpl" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String myPath=path+"/servlet/StudentServlet";
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
StuDaoImpl sd=new StuDaoImpl();
List list=sd.list();
request.setAttribute("stuList",list);
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'result.jsp' starting page</title>
</head>
<body>
<form name="f1" id="f1" action=<%= myPath%> method="post">
<table border="0">
<tr>
<td> </td>
<td><input type="text" name="name" ></td>
</tr>
<tr>
<td>age:</td>
<td><input type="text" name="age" ></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="save"></td>
</tr>
</table>
</form>
<hr/>
<c:if test="${requestScope.successful}">
save successful!
</c:if>
<br/>
<c:forEach var="stu" items="${stuList}">
${stu.id}
${stu.name}
${stu.age}
<br/>
</c:forEach>
</body>
</html>
8.开启tomcat,部署该工程后,在浏览器输入localhost:8080/studentInfoManage/pages/MyJsp.jsp
保存成功后显示的页面:
注:本人还是菜鸟一个,第一次写web程序,很多疏漏不足之处,还请海涵。