用myeclipse做一个增删改查的小程序
时间:2014-08-09 23:57 点击:次
整个程序如下:用户登录--进入用户文章页面--可对文章进行增删改
数据库还是用SQL2005
create database Test use Test create table UserInfo ( id int primary key identity(1,1), username varchar(20), password varchar(20) ) create table Article ( id int primary key identity(1,1), title varchar(50), content varchar(100), uid int FOREIGN KEY REFERENCES UserInfo(id) ) insert into UserInfo values('test','123')
新建web项目 名称为MyTest
建4个包
com.test.util
com.test.entity
com.test..service
com.test.servlet
com.test.util 只有一个类
DBcon.java
package com.test.util; import java.sql.*; public class DBcon { private Connection con = null; public DBcon() { try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); String url="jdbc:sqlserver://localhost:1433; DatabaseName=Test"; con= DriverManager.getConnection(url,"sa","123456"); System.out.println("数据库成功连接"); } catch (ClassNotFoundException e) { e.printStackTrace(); }catch (SQLException e) { e.printStackTrace(); } } public Connection getCon() { return con; } public void close() { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
com.test.entity
User.java
package com.test.entity; public class User { private int id; private String username; private String password; 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; } } Article.java package com.test.entity; public class Article { private int id; private String title; private String content; private int uid; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } }
com.test.service
TestService.java
package com.test.service; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.test.entity.Article; import com.test.entity.User; import com.test.util.DBcon; public class TestService { public User userLogin(String name,String password) { User user = new User(); PreparedStatement ps = null; ResultSet rs = null; DBcon mycon = null; String sql ="select * from UserInfo where username=?"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setString(1, name); rs=ps.executeQuery(); if(rs.next()) { if(password.equals(rs.getString("password"))) { //登录成功 user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); return user; }else{ return null; } }else{ return null; } }catch (SQLException e) { e.printStackTrace(); }finally { try { ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return user; } public List<Article> GetList(int userid) { List<Article> list=new ArrayList<Article>(); PreparedStatement ps = null; ResultSet rs = null; DBcon mycon = null; String sql ="select * from Article where uid=?"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setInt(1, userid); rs=ps.executeQuery(); while(rs.next()) { Article article=new Article(); article.setId(rs.getInt("id")); article.setTitle(rs.getString("title")); article.setContent(rs.getString("content")); article.setUid(rs.getInt("uid")); list.add(article); } }catch (SQLException e) { e.printStackTrace(); }finally { try { rs.close(); ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return list; } public boolean Add(Article article){ boolean flag = false; PreparedStatement ps=null; DBcon mycon=null; String sql="insert into Article values(?,?,?)"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setString(1, article.getTitle()); ps.setString(2, article.getContent()); ps.setInt(3, article.getUid()); int i=ps.executeUpdate(); if(i!=0){ flag=true; } }catch (SQLException e) { e.printStackTrace(); }finally { try { ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return flag; } public Article GetArticle(int id) { Article article=null; PreparedStatement ps=null; DBcon mycon=null; ResultSet rs=null; String sql="select * from Article where id=?"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setInt(1, id); rs=ps.executeQuery(); if(rs.next()) { article=new Article(); article.setId(rs.getInt("id")); article.setTitle(rs.getString("title")); article.setContent(rs.getString("content")); article.setUid(rs.getInt("uid")); } }catch (SQLException e) { e.printStackTrace(); }finally { try { ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return article; } public boolean Update(Article article){ boolean flag = false; PreparedStatement ps=null; DBcon mycon=null; String sql="update Article set title=?,content=? where id=?"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setString(1, article.getTitle()); ps.setString(2, article.getContent()); ps.setInt(3, article.getId()); int i=ps.executeUpdate(); if(i!=0){ flag=true; } }catch (SQLException e) { e.printStackTrace(); }finally { try { ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return flag; } public boolean Delete(int id){ boolean flag = false; PreparedStatement ps=null; DBcon mycon=null; String sql="delete from Article where id=?"; try{ mycon=new DBcon(); ps=mycon.getCon().prepareStatement(sql); ps.setInt(1, id); int i=ps.executeUpdate(); if(i!=0){ flag=true; } }catch (SQLException e) { e.printStackTrace(); }finally { try { ps.close(); mycon.close(); } catch (SQLException e) { e.printStackTrace(); } } return flag; } }
com.test.servlet
要建6个servlet
package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.entity.Article; import com.test.service.TestService; public class AddServlet extends HttpServlet { /** * Constructor of the object. */ public AddServlet() { 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 { request.setCharacterEncoding("GBK"); response.setCharacterEncoding("GBK"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); int uid=0; String title=request.getParameter("title"); String content=request.getParameter("content"); String s_id=request.getParameter("id"); if(s_id!=null) uid=Integer.parseInt(s_id); Article article=new Article(); article.setTitle(title); article.setContent(content); article.setUid(uid); TestService ts=new TestService(); if(ts.Add(article)) out.print("<script>alert('添加成功');location.href='list?id="+uid+"'</script>"); else out.print("<script>alert('添加失败');</script>"); } /** * 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 { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.service.TestService; public class DeleteServlet extends HttpServlet { /** * Constructor of the object. */ public DeleteServlet() { 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 { int id=0,uid=0; String s_id=request.getParameter("id"); String s_uid=request.getParameter("uid"); if(s_id!=null&&s_uid!=null){ id=Integer.parseInt(s_id); uid=Integer.parseInt(s_uid); } TestService ts=new TestService(); if(ts.Delete(id)) response.sendRedirect("list?id="+uid); } /** * 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 } }
package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.entity.Article; import com.test.service.TestService; public class GetArticleServlet extends HttpServlet { /** * Constructor of the object. */ public GetArticleServlet() { 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 { this.doPost(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 { int id=0; String s_id=request.getParameter("id"); if(s_id!=null) id=Integer.parseInt(s_id); TestService ts=new TestService(); Article article=ts.GetArticle(id); request.setAttribute("article", article); // response.sendRedirect("update.jsp"); request.getRequestDispatcher("update.jsp").forward(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package com.test.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.test.entity.Article; import com.test.service.TestService; public class ListServlet extends HttpServlet { /** * Constructor of the object. */ public ListServlet() { 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 { int userid=0; String id=request.getParameter("id"); if(id!=null) userid=Integer.parseInt(id); TestService ts=new TestService(); List<Article> list = ts.GetList(userid); request.getSession().setAttribute("list", list); response.sendRedirect("list.jsp"); } /** * 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 } }
package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.entity.User; import com.test.service.TestService; public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { 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 { request.setCharacterEncoding("GBK"); response.setCharacterEncoding("GBK"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); TestService ts=new TestService(); String username=request.getParameter("username"); String password=request.getParameter("password"); User user=ts.userLogin(username, password); if(user==null) out.print("<script>alert('登录失败');location.href='login.jsp'</script>"); else{ request.getSession().setAttribute("user", user); out.print("<script>alert('登录成功');location.href='list?id="+user.getId()+"'</script>"); } } /** * 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 { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package com.test.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.test.entity.Article; import com.test.service.TestService; public class UpdateServlet extends HttpServlet { /** * Constructor of the object. */ public UpdateServlet() { 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 { request.setCharacterEncoding("GBK"); response.setCharacterEncoding("GBK"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); int id=0; String title=request.getParameter("title"); String content=request.getParameter("content"); String s_id=request.getParameter("id"); if(s_id!=null) id=Integer.parseInt(s_id); TestService ts=new TestService(); Article article=ts.GetArticle(id); article.setTitle(title); article.setContent(content); if(ts.Update(article)) out.print("<script>alert('修改成功');location.href='list?id="+article.getUid()+"'</script>"); } /** * 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 { this.doGet(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
接下来是jsp
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ page import="com.test.util.*" %>
<%
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 'login.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>
<% DBcon db=new DBcon(); %>
<form action="login" method="post">
username:<input type="text" name="username" /><br/>
password:<input type="text" name="password" /><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
<%@ 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 'add.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>
<form action="add" method="post">
<p>添加文章</p>
标题:<input name="title" type="text"><br/>
内容:<textarea name="content" cols="50" rows="20"></textarea> <br/>
<input name="id" type="hidden" value="${user.id}">
<input name="" type="submit" value="添加">
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.test.entity.*" %>
<%
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 'list.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>
<p>用户名:${user.username }</p>
文章标题<br/>
<%
List<Article> list=(List<Article>)session.getAttribute("list");
if(list!=null)
for(int i=0;i<list.size();i++){
%>
<a href="get?id=<%=list.get(i).getId() %> "> <%=list.get(i).getTitle() %> </a> ---<a href="delete?id=<%=list.get(i).getId() %>&uid=${user.id}">删除</a><br/>
<%} %>
<a href="add.jsp">添加</a>
</body>
</html>
<%@ 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 'update.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>
<form action="update" method="post">
<p>修改文章</p>
标题:<input name="title" type="text" value="${article.title}"><br/>
内容:<textarea name="content" cols="50" rows="20" >${article.content}</textarea> <br/>
<input name="id" type="hidden" value="${article.id}">
<input name="" type="submit" value="修改">
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.test.servlet.LoginServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>ListServlet</servlet-name> <servlet-class>com.test.servlet.ListServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>AddServlet</servlet-name> <servlet-class>com.test.servlet.AddServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>GetArticleServlet</servlet-name> <servlet-class>com.test.servlet.GetArticleServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>UpdateServlet</servlet-name> <servlet-class>com.test.servlet.UpdateServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>DeleteServlet</servlet-name> <servlet-class>com.test.servlet.DeleteServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ListServlet</servlet-name> <url-pattern>/list</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>AddServlet</servlet-name> <url-pattern>/add</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>GetArticleServlet</servlet-name> <url-pattern>/get</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>UpdateServlet</servlet-name> <url-pattern>/update</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DeleteServlet</servlet-name> <url-pattern>/delete</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
OK,完~
顶一下
(1)
16.7%
踩一下
(5)
83.3%
上一篇:什么是java?
下一篇:JAVA在线教程
相关内容:
- QQ群
-
微信
- 返回首页
- 返回顶部