用servlet和jsp做探索数据库
1.建一个web文件,在里面分三层,分别是实体层;DAO层,DAO层里面包含BaseDAO(数据访问层)和DAO层;还有一个servlet层,处理数据逻辑层!
一、实体层,建立两个实体,一个members,和一个product:
package com.chinasoft.jsptest.entity; public class Menbers {
private int id;
private String name;
private String pwd;
private String email;
private String born;
private String sex; public Menbers() {
super();
// TODO Auto-generated constructor stub
} public Menbers(String name, String pwd, String email, String born,
String sex) {
super();
this.name = name;
this.pwd = pwd;
this.email = email;
this.born = born;
this.sex = sex;
} public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public String getBorn() {
return born;
} public void setBorn(String born) {
this.born = born;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPwd() {
return pwd;
} public void setPwd(String pwd) {
this.pwd = pwd;
}
}
package com.chinasoft.jsptest.entity; public class Product {
public int id ;
public String name ;
public String money ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
} }
二、DAO层
1.BaseDAO
package com.chinasofti.jsptest.dao; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; public class BaseDAO {
//1.链接数据库
String className="com.microsoft.sqlserver.jdbc.SQLServerDriver";
String connectionString="jdbc:sqlserver://127.0.0.1;DatabaseName=JspTest";
String username="sa";
String userpwd="123456"; private Connection conn;
private PreparedStatement pst;
private ResultSet rst; //2. 链接上表
public BaseDAO(){
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getconnection(){
try {
conn=DriverManager.getConnection(connectionString,username,userpwd);
} catch (SQLException e) {
e.printStackTrace();
}
} public ResultSet ExecuteQuest(String sql){
getconnection();
return ExecuteQuest(sql,new Object[]{});
}
public ResultSet ExecuteQuest(String sql, Object[] params) {
getconnection();
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<params.length;i++){
try { pst.setObject(i+1, params[i]);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
rst=pst.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rst;
} public int ExecuteUpdate(String sql){
getconnection();
return ExecuteUpdate(sql,new Object[]{});
}
public int ExecuteUpdate(String sql,Object[] params){
getconnection();
int result=0;
try {
pst=conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
for(int i=0;i<params.length;i++){
try {
pst.setObject(i+1, params[i]);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
result=pst.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
} public void CloseAll(){
try{
if(!rst.isClosed()){
rst.close();
}
if(!pst.isClosed()){
pst.close();
}
if(!conn.isClosed()){
conn.close();
}
}catch(Exception e){
System.out.println(e.getMessage());
}
} }
2.DAO
package com.chinasofti.jsptest.dao; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.chinasoft.jsptest.entity.Menbers; public class MenbersDAO {
//1.new一个
private BaseDAO dao = new BaseDAO();
//2.增加ExecuteUpdate;
public void Add(Menbers meb){
String sql = "insert into [test]([id],[name],[pwd],[email],[born],[sex]) values (?,?,?,?,?,?)";
Object[] params=new Object[]{meb.getId(),meb.getName(),meb.getPwd(),meb.getEmail(),meb.getBorn(),meb.getSex()};
dao.ExecuteUpdate(sql,params);
}
//3.删除ExecuteUpdate;
public void Delete(Menbers meb){
String sql = "delete from [test] where [id]=?";
Object[] params = new Object[]{meb.getId()};
dao.ExecuteUpdate(sql,params);
}
//4.修改ExecuteUpdate;
public void Update(Menbers meb){
String sql="update [tset] set [name]=?,[pwd]=? WHERE [id]=?";
Object [] params=new Object[]{meb.getName(),meb.getPwd(),meb.getId()};
dao.ExecuteUpdate(sql,params);
}
//5.查找全部ExecuteQuest;
public List<Menbers> getselect(){
List<Menbers> result=new ArrayList<Menbers>();
String sql="SELECT [id],[name],[pwd] ,[email],[sex]FROM [test]";
ResultSet rst=dao.ExecuteQuest(sql);
try{
while(rst.next()){
Menbers temp=new Menbers();
temp.setId(rst.getInt(1));
temp.setName(rst.getString(2));
temp.setPwd(rst.getString(3));
temp.setEmail(rst.getString(4));
temp.setSex(rst.getString(5));
result.add(temp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.CloseAll();
return result;
}
//6.按照ID查找ExecuteQuest;
public Menbers getSelectid(int id){
Menbers result=null;
String sql="SELECT [id],[name],[pwd] FROM [test] WHERE [id]=?";
Object[] params=new Object[]{id};
ResultSet rst=dao.ExecuteQuest(sql,params);
try {
if(rst.next()){
result = new Menbers();
result.setId(rst.getInt(1));
result.setName(rst.getString(2));
result.setPwd(rst.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.CloseAll();
return result;
}
//7.按照name查找ExecuteQuest;
public Menbers getSelectname(String name){
Menbers result=null;
String sql="SELECT [id],[name],[pwd] FROM [test] WHERE [name]=?";
Object[] params=new Object[]{name};
ResultSet rst=dao.ExecuteQuest(sql,params);
try {
if(rst.next()){
result = new Menbers();
result.setId(rst.getInt(1));
result.setName(rst.getString(2));
result.setPwd(rst.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.CloseAll();
return result;
} }
MembersDAO
package com.chinasofti.jsptest.dao; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import com.chinasoft.jsptest.entity.Product; public class ProductDAO {
private BaseDAO dao = new BaseDAO();
//1.增加
public void Add(Product put){
String sql ="insert into [Product]([name],[money]) values(?,?)";
Object[] params = new Object[]{put.getName(),put.getMoney()};
dao.ExecuteUpdate(sql, params);
}
//2.删除
public void delete(int id){
String sql ="delete [Product] where [id]=?";
Object[] params = new Object[]{id};
dao.ExecuteUpdate(sql, params);
}
//3.更改
public void Update (Product put){
String sql ="update [Product] set [name]=?,[money]=? where [id]=?";
Object[] params = new Object[]{put.getName(),put.getMoney(),put.getId()};
dao.ExecuteUpdate(sql, params);
}
//4.查找全部
public List <Product > getSelect(){
List <Product> result=new ArrayList<Product>();
String sql ="select [id] ,[name],[money] from [Product] ";
ResultSet rst = dao.ExecuteQuest(sql);
try {
while (rst.next()){
Product pro = new Product();
pro.setId(rst.getInt(1));
pro.setName(rst.getString(2));
pro.setMoney(rst.getString(3));
result.add(pro);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.CloseAll();
return result;
}
//5.根据name查找
public Product getname(String name){
Product pro = null;
Object [] params = new Object[]{name};
String sql ="select [name],[money],[id] from [Product] where[name]=? ";
ResultSet rst = dao.ExecuteQuest(sql,params);
try {
while (rst.next()){
pro = new Product();
pro.setId(rst.getInt(1));
pro.setName(rst.getString(2));
pro.setMoney(rst.getString(3));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dao.CloseAll();
return pro; } }
ProductDAO
三、servlet层 需要建servlet类,里面会直接生成servlet/xxxx地址。这样在访问的时候,就直接访问这个地址
1.登录注册的逻辑判断层,主要注意request的用法;还有就是跳转jsp以后,jsp用post方法提交到的action地址,是servlet映射的地址!这个在WebRoot-web-inf-web.hml可以找到
package com.chinasofti.jsptest.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.chinasoft.jsptest.entity.Menbers;
import com.chinasofti.jsptest.dao.MenbersDAO; @SuppressWarnings("serial")
public class goset extends HttpServlet { /**
* Constructor of the object.
*/
public goset() {
super();
} /** */
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} /**
*
*
* 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 {
request.getRequestDispatcher("../go30-1.jsp").forward(request, response);//指向你要过去的JSP,进行逻辑判断以后,以post方法,进行下面的逻辑判断
} /**
*
*
* 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 {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
String emai = request.getParameter("email");
String born = request.getParameter("born");
String sex = request.getParameter("sex");
String type = request.getParameter("type");
if ("login".equals(type)) {
MenbersDAO dao = new MenbersDAO();
Menbers m = dao.getSelectname(name);
if (m != null && m.getPwd().equals(pwd)) {
request.setAttribute("title", "登陆成功");
request.setAttribute("retn", "欢迎你," + name + "。");
request.getRequestDispatcher("../go30-2.jsp").forward(request,
response);//指向你要过去的JSP
} else if (m != null && !m.getPwd().endsWith(pwd)) {
request.setAttribute("title", "登陆失败");
request.setAttribute("retn", "用户名或密码错误!请重新登录 ");
request.getRequestDispatcher("../go30-3.jsp").forward(request,
response);//指向你要过去的JSP
} else {
request.setAttribute("retn", "你不是公司员工,请入职以后再登入");
request.getRequestDispatcher("../go30-4.jsp").forward(request,
response);//指向你要过去的JSP
}
} else if ("register".equals(type)) {
Menbers m = new Menbers(name, pwd, emai, born, sex);
MenbersDAO dao = new MenbersDAO();
dao.Add(m);
request.getRequestDispatcher("../go30-4.jsp").forward(request,
response);//指向你要过去的JSP
} } /**
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
goset.java
package com.chinasofti.jsptest.servlet; import java.io.IOException;
import java.io.PrintWriter;
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.chinasoft.jsptest.entity.Product;
import com.chinasofti.jsptest.dao.ProductDAO; public class ProductSevlet extends HttpServlet { /**
* Constructor of the object.
*/
public ProductSevlet() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ProductDAO dao = new ProductDAO();
List<Product> ms= dao.getSelect();
request.setAttribute("Model", ms);
request.getRequestDispatcher("../Product.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 { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
ProducAction.java
package com.chinasofti.jsptest.servlet; import java.io.IOException;
import java.io.PrintWriter;
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.chinasoft.jsptest.entity.Menbers;
import com.chinasofti.jsptest.dao.MenbersDAO; public class UserList extends HttpServlet { /**
* Constructor of the object.
*/
public UserList() {
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 { MenbersDAO dao= new MenbersDAO();
List <Menbers> ms = dao.getselect();
request.setAttribute("Model", ms);
request.getRequestDispatcher("../UserList.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 { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }
UserList.java
jsp界面,所有的显示界面
<form method="post" action="<%=request.getContextPath() %>/servlet/goset">
<input type="hidden" name="type" value="login">
<table border="0" align="center">
<tr>
<td>用户名</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pwd"></td>
</tr> <tr>
<td colspan="2" align="center"><input type="submit" value="登录" /> <input type="reset" value="取消" /></td>
</tr>
</table>
</form>
go30-1.jsp
<h1 align="center"> <%=title%> </h1>
<h3 align="center"> <%=retn%> </h3>
go30-2.jsp
<h1 align="center"> <%=retn%> </h1>
<form method="post">
<table border="0" align="center" >
<tr> <td>用户名</td><td> <input type="text" name="name"></td></tr>
<tr><td>密码</td><td > <input type="password" name="pwd"> </td></tr> <tr><td colspan="2" align="center">
<input type="submit" value="登录" /> <input type="reset" value="取消" />
</td></tr>
</table>
</form>
go30-3.jsp
<h1 align="center">
<%=retn%>
</h1>
<form method="post" action="<%=request.getContextPath() %>/servlet/goset">
<input type="hidden" name="type" value="register">
<table border="0" align="center">
<tr>
<td>用户名</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td>邮箱</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>出生日期</td>
<td><input type="text" name="born"></td>
</tr>
<tr>
<td>性别</td>
<td>男<input type="radio" name="sex" value="男"> 女<input
type="radio" name="sex" value="女"></td>
</tr> <tr>
<td colspan="2" align="center"><input type="submit" value="注册" /> <input type="reset" value="取消" /></td>
</tr>
</table>
</form>
go30-4.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <table>
<tr width="300">
<td width="100">id</td>
<td width="100">name</td>
<td width="100">money</td>
</tr>
<c:forEach var="m" items= "${Model}">
<tr>
<td>${m.id}</td>
<td>${m.name}</td>
<td>${m.email}</td> </tr>
</c:forEach> </table>
Product.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <table>
<tr width="500">
<td width="100">id</td>
<td width="100">name</td>
<td width="100">pwd</td>
<td width="100">email</td>
<td width="100">born</td>
<td width="100">sex</td>
</tr>
<c:forEach var="m" items= "${Model}">
<tr>
<td >${m.id}</td>
<td >${m.name}</td>
<td >${m.pwd}</td>
<td >${m.email}</td>
<td >${m.born}</td>
<td >${m.sex}</td> </tr>
</c:forEach> </table>
UserLise.jsp
用servlet和jsp做探索数据库的更多相关文章
- myEclipse6.5与数据库(SQL Server2008)连接遇到的问题(自己总结的干货)<用SSH框架的时候,用servlet+javabean+jsp的时候>
昨天因为学习SSH框架的搭建,时隔一年又重新遇到了myEclipse连接数据库的问题.废话不多说,上干货 (以下全部按照我遇到的问题的顺序,也就是没有顺序,就是任性) 请注意:这是在myEclipse ...
- Servlet、JSP选择题(2)
Java EE软件工程师认证考试 试题库-选择题 一. 选择题(包括单选和双选) 1.B 编写一个Filter,需要( ) A. 继承Filter 类 B. 实现Filter 接口 C. 继承 ...
- 基于Servlet、JSP、JDBC、MySQL的一个简单的用户注冊模块(附完整源代码)
近期看老罗视频,做了一个简单的用户注冊系统.用户通过网页(JSP)输入用户名.真名和password,Servlet接收后通过JDBC将信息保存到MySQL中.尽管是个简单的不能再简单的东西,但麻雀虽 ...
- Servlet与Jsp的结合使用实现信息管理系统一
PS:1:先介绍一下什么是Servlet? Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地 ...
- SpringMVC内容略多 有用 熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器、过滤器等Web组件以及MVC架构模式进行Java Web项目开发的经验。
熟悉基于JSP和Servlet的Java Web开发,对Servlet和JSP的工作原理和生命周期有深入了解,熟练的使用JSTL和EL编写无脚本动态页面,有使用监听器.过滤器等Web组件以及MVC架构 ...
- Servlet、Jsp
一.Servlet 1.什么是Servlet? (1)由sun公司(被oracle公司收购)制定的一种用来扩展web服务器功能的组件规范.简单的讲就是一种用来开发动态Web的技术. 扩展web服务器功 ...
- Servlet,jsp,JSP技术 ,JSP编程
一.Servlet 思考 1 浏览器可以直接打开JAVA/class文件吗? 不可以 2浏览器可以打开HTML.JS 文件吗? 可以 3 JAVA程序可以生成HTML文件吗?可以的,用IO流. 4 ...
- 基于JQuery+JSP的无数据库无刷新多人在线聊天室
JQuery是一款非常强大的javascript插件,本文就针对Ajax前台和JSP后台来实现一个无刷新的多人在线聊天室,该实现的数据全部存储在服务端内存里,没有用到数据库,本文会提供所有源程序,需要 ...
- Servlet和JSP读书笔记(二)
一. GenericServlet 1. 前面写的 Servlet和JSP学习笔记(一) 中的实例都是通过实现Servlet接口编写的,这样存在的问题就是:你必须实现Servlet中的所有方法,而不管 ...
随机推荐
- Generate SQL from Excel
Tips: SUBSTITUTE(D4,"'","''")---if D4 contain ', this function will convert ' ...
- scala-类
---恢复内容开始--- 随笔记录scala中,有哪些类,如何定义一个类,有哪些注意点. 一,scala中有哪些类? 1,简单类 class 2,单例模式 object 3,伴生类 4,case cl ...
- Spring pom配置详解
转载至http://blog.csdn.net/ithomer/article/details/9332071# 原博主注释的很详细 <project xmlns="http://ma ...
- c#判断闰年
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- inotifywait命令
[命令格式]: inotifywait [ options ] file1 [ file2 ] [ file3 ] [ ... ][命令原意]: inote file system wait[命令路径 ...
- 需要交互的shell编程——EOF(转载)
在shell编程中,”EOF“通常与”<<“结合使用,“<<EOF“表示后续的输入作为子命令或子shell的输入,直到遇到”EOF“, 再次返回到主调shell,可将其理解为分 ...
- Linux驱动学习之什么是驱动?
一.什么是驱动? 1: 驱动一词的字面意思 2: 物理上的驱动 3: 硬件中的驱动 4: linux内核驱动.软件层面上的驱动广义上是指:这一段代码操作了硬件去动,所以这一段代码就叫硬件的驱动程序. ...
- 在Action 中访问web资源
1.什么是web资源: HttpServletRequest,HttpSession,ServletContext等原生的Servlet API. 2.为什么要访问web资源? B/S应用的Contr ...
- oracle 创建database Link
当两台不同的数据库服务器想要共享一部分数据的时候,可以通过创建database Link的方式实现. 创建全局database links ,则必须使用systm或sys用户,在database前加p ...
- redis原理分析
基本全是参考http://blog.csdn.net/a600423444/article/details/8944601 redis的使用大家都很熟悉,可能除了watch 锁,pipelin ...