之前一段时间一直忙于毕业设计,也没有空学习了,本篇继续学习。
本篇将开始学习java web下使用servlet下来操作数据库,并展示到界面上的使用方法。
新建工程ServletMvc001。
目录结构如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>ServletMvc001</display-name>
<welcome-file-list>
<welcome-file>logon.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>logOnServlet</servlet-name>
<servlet-class>com.dx.javamvc.servlets.LogOnServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logOnServlet</servlet-name>
<url-pattern>/LogOnServlet</url-pattern>
</servlet-mapping>
</web-app>
logon.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form name="form1" id="form1" method="get" action="LogOnServlet">
<input type="submit" id="btnOk" name="btnOk" value="提交" />
</form>
</body>
</html>
showPerfileInfo.jsp
<%@page import="com.mysql.fabric.Response"%>
<%@page import="java.util.List" %>
<%@page import="com.dx.javamvc.entity.User" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% List<User> userItem= (List<User>)request.getAttribute("UserItems"); %>
<%for(User user :userItem){
out.write("llddd");
%>
<%=user.getId() %><br/>
<%=user.getUserName() %><br/>
<%=user.getPassword() %><br/>
<%
} %>
</body>
</html>
jdbc.properties
DriverClass=com.mysql.jdbc.Driver JdbcUrl=jdbc:mysql://localhost:3306/servletmvc001 UserName=root Password=123456
DbConfiguration.java
package com.dx.javamvc.configuration; import java.io.*;
import java.net.URISyntaxException;
import java.util.*; public class DbConfiguration {
private static final String FILENAME = "jdbc.properties";
private static String userName = null;
private static String password = null;
private static String jdbcUrl = null;
private static String driverClass = null; public DbConfiguration() {
Properties property = new Properties(); try {
String path = this.getClass().getClassLoader().getResource("").toURI().getPath();
FileInputStream inStream = new FileInputStream(new File(path + FILENAME));
property.load(inStream);
setUserName(property.getProperty("UserName"));
setPassword(property.getProperty("Password"));
setJdbcUrl(property.getProperty("JdbcUrl"));
setDriverClass(property.getProperty("DriverClass"));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public String getUserName() {
return userName;
} private void setUserName(String userName) {
DbConfiguration.userName = userName;
} public String getPassword() {
return password;
} private void setPassword(String password) {
DbConfiguration.password = password;
} public String getJdbcUrl() {
return jdbcUrl;
} private void setJdbcUrl(String jdbcUrl) {
DbConfiguration.jdbcUrl = jdbcUrl;
} public String getDriverClass() {
return driverClass;
} private void setDriverClass(String driverClass) {
DbConfiguration.driverClass = driverClass;
} }
SexType.java
package com.dx.javamvc.entity; public enum SexType {
Mail(0), Femail(1); private int value; private SexType(int value) {
setValue(value);
} public int getValue() {
return value;
} public void setValue(int value) {
this.value = value;
} public static SexType valueOf(int value) {
SexType sexType;
switch (value) {
case 1:
sexType = SexType.Femail;
break;
default:
sexType = SexType.Mail;
break;
} return sexType;
}
}
User.java
package com.dx.javamvc.entity; import java.util.Date; public class User {
private int id;
private String userName;
private String password;
private SexType sex;
private Date createDate; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public SexType getSex() {
return sex;
} public void setSex(SexType sex) {
this.sex = sex;
} public Date getCreateDate() {
return createDate;
} public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
DbUtil.java
package com.dx.javamvc.utils; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import com.dx.javamvc.configuration.DbConfiguration;
import com.dx.javamvc.types.IExecuteQueryAction;
import com.dx.javamvc.types.IPreparedStatementAction; public class DbUtil {
public static void executeQuery(String sql, IPreparedStatementAction preparedStatementAction,
IExecuteQueryAction executeQueryAction) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null; DbConfiguration configuration=new DbConfiguration();
String driverClass = configuration.getDriverClass();
String jdbcUrl = configuration.getJdbcUrl();
String userName = configuration.getUserName();
String password = configuration.getPassword(); try {
Class.forName(driverClass); connection = DriverManager.getConnection(jdbcUrl, userName, password);
preparedStatement = connection.prepareStatement(sql); if (preparedStatementAction != null) {
preparedStatementAction.action(preparedStatement);
} resultSet = preparedStatement.executeQuery(); if (executeQueryAction != null) {
executeQueryAction.action(resultSet);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} } }
IExecuteQueryAction.java
package com.dx.javamvc.types; import java.sql.ResultSet;
import java.sql.SQLException; public interface IExecuteQueryAction {
void action(ResultSet result) throws SQLException;
}
IPreparedStatementAction.java
package com.dx.javamvc.types; import java.sql.PreparedStatement;
import java.sql.SQLException; public interface IPreparedStatementAction {
void action(PreparedStatement preparedStatement) throws SQLException;
}
UserDao.java
package com.dx.javamvc.domain; import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.dx.javamvc.entity.SexType;
import com.dx.javamvc.entity.User;
import com.dx.javamvc.types.IPreparedStatementAction;
import com.dx.javamvc.types.IExecuteQueryAction;
import com.dx.javamvc.utils.DbUtil; public class UserDao {
public List<User> getUserByUserName(final String userName) {
final List<User> userItems = new ArrayList<User>(); String sql = "Select * From User Where Name=?"; IPreparedStatementAction preparedStatementAction = new IPreparedStatementAction() {
@Override
public void action(PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setString(1, userName);
}
}; IExecuteQueryAction executeQueryAction = new IExecuteQueryAction() {
@Override
public void action(ResultSet result) throws SQLException {
try {
while (result.next()) {
User user = new User(); user.setId(result.getInt("Id"));
user.setUserName(result.getString("Name"));
user.setPassword(result.getString("Password"));
user.setSex(SexType.valueOf(result.getInt("Sex")));
user.setCreateDate(result.getDate("CreateDate")); userItems.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}; DbUtil.executeQuery(sql, preparedStatementAction, executeQueryAction); return userItems; }
}
LogOnServlet.java
package com.dx.javamvc.servlets; import java.io.IOException;
import java.util.List; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.dx.javamvc.domain.UserDao;
import com.dx.javamvc.entity.User; public class LogOnServlet extends HttpServlet {
private static final long serialVersionUID = -8807878351076369807L;
private static final UserDao userDao = new UserDao(); @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> userItems = userDao.getUserByUserName("yy3b2007com");
req.setAttribute("UserItems", userItems);
req.getRequestDispatcher("/showPerfileInfo.jsp").forward(req, resp);
}
}