java可以做什么简单的项目_一个简单的java web 项目

本文实现一个简单的 java web 项目,包括以下5个功能:

1. 登录

用户默认主页index.jsp , 可选择登录功能,输入用户名和密码,若登录成功,则进入产品管理总页面main.jsp。若不成功仍退回index.jsp

98fcad4bcec8ce6e2e0840b263a97142.png

2. 注册

用户默认主页index.jsp ,  可选择注册功能 ,若注册,则进入 register.jsp

b7c58905bf4875ab281beeb630ba02f4.png

3. 管理产品(增加,删除,查看)

登录成功后,进入产品管理总页面main.jsp。第一次进入main.jsp,默认显示所有产品列表。在此页面上更实现 查询某个产品记录,添加产品,批量删除,选中一项产品查看详情,实现分页功能。

22d3c4e59ad1450eb0379f4c6d008fd1.png

3.1 添加产品

742744946da22cda31805e8282215015.png

3.2 查询"圣女果"

0f20ee41ecc3d99d6b6cf6cea49ea5ed.png

3.3 选择“香蕉” ,点击 “查看”

941708829c99959b9b547083e6ae82ae.png

4. 退出

用户点击“退出”时,清除session,退回主页面index.jsp

25909f8cb58583c2aed8bc747d01f482.png

5. 过滤器

若用户没有登录成功,而直接访问 main.jsp 或 addProduct.jsp ,则被过滤器过滤到 index.jsp . 因为有成功登录,验证其身份后,才有权利访问产品和管理产品。否则将被过滤到默认主页index.jsp.

例如:在地址栏直接输入:http://192.168.0.103:8080/xianfengProject/main.jsp,则被过滤到index.jsp

25909f8cb58583c2aed8bc747d01f482.png

-------------------------------------------------------------------------------

项目环境:

操作系统:win7

实现技术:jsp+servlet

数据库: mysql5.5.20 , Navicat_for_MySQL_11.0.10

服务器:apache-tomcat-7.0.40

开发平台: MyEclipse10

--------------------------------------------------------------------------------

说明:

1. 数据库

数据库名:mydb , 共两张表.

表一:userinfo (id , username , pswd)

表二:product (proid , proname, proprice , proaddress , proimage)

119356a5565edb79d34590dcdde8802c.png

product (proid , proname, proprice , proaddress , proimage)表结构:

5bbc506a3fd1bd0cfbcf6acbabb13969.png

userinfo (id , username , pswd)表结构如下:

6e9b46a2cdd4e4d20c18a2c787aac9f8.png

2. MyEclipse 工程目录

5eae270ac2778cd40f50b6d3f4acf56d.png

10b7e11a902e4d734f804823ae25a742.png

----------------------------------------------------------------------------------------------------------------------

1. index.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

先锋管理系统欢迎您

function login(){

var th = document.form1;

if(th.username.value==""){

alert("用户名不能为空!");

th.username.focus();

return;

}

if(th.pswd.value==""){

alert("密码不能为空!");

th.pswd.focus();

return;

}

th.action = "/servlet/LoginAction";

th.submit();

}

先锋管理系统欢迎你!

用户名:
密码:

登录

注册

2. register.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

注册新用户

function dosubmit(){

var th = document.form1;

if(th.username.value==""){

alert("用户名不能为空!");

th.username.focus();

return;

}

if(th.pswd.value==""){

alert("密码不能为空!");

th.pswd.focus();

return;

}

th.action="/servlet/RegisterAction";

th.submit();

}

function back(){

alert("退回主页!");

th = document.form1;

th.acton="/index.jsp";

th.submit;

}

用户注册

用户名:必须填写!
密 码:必须填写!

确定

返回

3.main.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

//获取 session 中的 username;

String username = (String)session.getAttribute("username");

//获取从 servlet ProductActiion 中 传递的参数(数据库查询的结果)

List> list =(List>) request.getAttribute("listProduct");

// 获取 分页对象

DividePage dividePage = (DividePage) request.getAttribute("dividePage");

// 获取查询的关键词

String productName = (String) request.getAttribute("productName");

if(list==null){

//第一次进 main.jsp页面,默认加载所有的产品

ProductService service = new ProductDao();

int totalRecord = service.getItemCount("");

dividePage = new DividePage(5,totalRecord,1);

int start = dividePage.fromIndex();

int end = dividePage.toIndex();

list = service.listProduct("", start, end);

}

%>

产品管理

function searchProduct(){

var th = document.form2;

th.action="/servlet/ProductAction?action_flag=search";

th.submit();

}

function first(){

window.location.href = "/servlet/ProductAction?action_flag=search&pageNum=1";

}

function next(){

window.location.href = "/servlet/ProductAction?action_flag=search&pageNum=";

}

function forward(){

window.location.href = "/servlet/ProductAction?action_flag=search&pageNum=";

}

function end(){

window.location.href = "/servlet/ProductAction?action_flag=search&pageNum=";

}

function changePage(currentPage){

window.location.href = "/servlet/ProductAction?action_flag=search&pageNum="+currentPage;

}

function selectAll(flag){

var ids = document.getElementsByName("ids");

for(var i = 0 ; i < ids.length ; i++){

ids[i].checked = flag;

}

}

function getSelectedCount(){

var ids = document.getElementsByName("ids");

var count = 0;

for(var i = 0 ; i < ids.length ; i++)

{

ids[i].checked==true?count++:0;

}

return count;

}

function del(){

if(getSelectedCount()==0){

alert("至少选择一个删除项!");

return;

}

var th = document.form1;

th.action="/servlet/ProductAction?action_flag=del";

th.submit();

}

function getSelectedValue(){

var ids = document.getElementsByName("ids");

for(var i = 0 ; i < ids.length ; i++)

{

if(ids[i].checked){

return ids[i].value;

}

}

}

function view(){

if(getSelectedCount()<1){

alert("至少选择一个查看项!");

return;

}else if(getSelectedCount()>1){

alert("只能选择一个查看项!");

return;

}

var th = document.form1;

th.action="/servlet/ProductAction?action_flag=view&proid="+getSelectedValue();

th.submit();

}

function logout(){

window.location.href="/servlet/LogoutAction?action_flag=logout";

}

欢迎您的光临,退出
产品信息查询
产品名称"/>

查询

添加

查询结果
产品名称产品产地产品价格

if(list!=null && !list.isEmpty()){

for(Map map :list){%>

"/>

}else{%>

}

%>

删除

查看

共页

首页

上一页

下一页

尾页

跳转到

int pageCount = dividePage.getPageCount();

if(pageCount>0){

for(int i = 1 ; i<=pageCount;i++){%>

>

}

}else{// 无记录

%>

1

%>

4.addProduct.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

新增产品

function dosubmit(){

var th = document.form1;

th.action="/servlet/ProductAction?action_flag=add";

th.submit();

}

产品信息添加
产品名称产品价格
产品产地
产品图片

确定

返回

5. viewProduct.jsp

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

Map map = (Map)request.getAttribute("productMap");

%>

查看产品

产品信息

产品名称产品价格
产品产地
产品图片<%=map.get(">

确定

返回

6.LoginAction.java

package com.login;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class LoginAction extends HttpServlet {

private LoginService service;

/**

* Constructor of the object.

*/

public LoginAction() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* 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.

*

* 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;charset=utf-8");

PrintWriter out = response.getWriter();

String path = request.getContextPath();

String username = request.getParameter("username");

String pswd = request.getParameter("pswd");

List params = new ArrayList();

params.add(username);

params.add(pswd);

boolean flag = service.login(params);

if (flag) {

request.getSession().setAttribute("username", username);

response.sendRedirect(path+"/main.jsp");

}else{

response.sendRedirect(path+"/index.jsp");

}

out.flush();

out.close();

}

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

service = new LoginDao();

}

}

7.LoginDao.java

package com.login;

import java.sql.SQLException;

import java.util.List;

import java.util.Map;

import javax.mail.Flags.Flag;

import com.jdbc.JdbcUtils;

public class LoginDao implements LoginService {

private JdbcUtils jdbcUtils;

public LoginDao() {

// TODO Auto-generated constructor stub

jdbcUtils = new JdbcUtils();

}

@Override

public boolean login(List params) {

// TODO Auto-generated method stub

boolean flag = false;

try {

jdbcUtils.getConnection();

String sql = "select * from userinfo where username = ? and pswd = ?";

Map map = jdbcUtils.findSimpleResult(sql, params);

flag = !map.isEmpty()?true:false;

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

//关闭数据库

jdbcUtils.releaseConn();

}

return flag;

}

}

8.LoginService.java

package com.login;

import java.util.List;

public interface LoginService {

public boolean login(List params);

}

9. MyFilter.java

package com.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class MyFilter implements Filter {

public MyFilter() {

// TODO Auto-generated constructor stub

}

@Override

public void destroy() {

// TODO Auto-generated method stub

}

@Override

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain filterChain) throws IOException, ServletException {

// 过滤用户请求,判断是否登录

HttpServletRequest httpServletRequest = (HttpServletRequest)request;

HttpServletResponse httpServletResponse = (HttpServletResponse)response;

httpServletRequest.setCharacterEncoding("utf-8");

httpServletResponse.setCharacterEncoding("utf-8");

String username = (String)httpServletRequest.getSession().getAttribute("username");

if (username == null) {

String path = httpServletRequest.getContextPath();

httpServletResponse.sendRedirect(path+"/index.jsp");

}

filterChain.doFilter(httpServletRequest, httpServletResponse);

}

@Override

public void init(FilterConfig arg0) throws ServletException {

// TODO Auto-generated method stub

}

}

10.RegisterAction.java

package com.register;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class RegisterAction extends HttpServlet {

private RegisterService service;

/**

* Constructor of the object.

*/

public RegisterAction() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* 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.

*

* 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;charset=utf-8");

PrintWriter out = response.getWriter();

String path = request.getContextPath();

String username = request.getParameter("username");

String pswd = request.getParameter("pswd");

List params = new ArrayList();

params.add(username);

params.add(pswd);

boolean flag = service.registerUser(params);

if (flag) {

response.sendRedirect(path+"/index.jsp");

}

out.flush();

out.close();

}

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

service = new RegisterDao();

}

}

11. RegisterDao.java

package com.register;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import com.jdbc.JdbcUtils;

public class RegisterDao implements RegisterService {

private JdbcUtils jdbcUtils;

public RegisterDao() {

// TODO Auto-generated constructor stub

jdbcUtils = new JdbcUtils();

}

/* 完成对用户注册的dao的编写

* @see com.register.service.RegisterService#registerUser(java.util.List)

*/

@Override

public boolean registerUser(List params) {

// TODO Auto-generated method stub

boolean flag = false;

try {

jdbcUtils.getConnection();

String sql = "insert into userinfo(username,pswd) values(?,?)";

flag = jdbcUtils.updateByPreparedStatement(sql, params);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

//关闭数据库连接

jdbcUtils.releaseConn();

}

return flag;

}

}

12. RegisterService.java

package com.register;

import java.util.List;

public interface RegisterService {

//完成用户注册功能

public boolean registerUser(List params);

}

13. ProductAction.java

package com.product;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.util.DividePage;

import com.util.UUIDTools;

public class ProductAction extends HttpServlet {

private ProductService service;

/**

* Constructor of the object.

*/

public ProductAction() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* 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.

*

* 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;charset=utf-8");

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

PrintWriter out = response.getWriter();

String action_flag = request.getParameter("action_flag");

if (action_flag.equals("add")) {

addProduct(request,response);

}else if (action_flag.equals("search")) {

listProduct(request,response);

}else if (action_flag.equals("del")) {

delProduct(request,response);

}else if (action_flag.equals("view")) {

viewProduct(request,response);

}

out.flush();

out.close();

}

private void viewProduct(HttpServletRequest request,

HttpServletResponse response) {

// TODO Auto-generated method stub

String proid = request.getParameter("proid");

Map map = service.viewProduct(proid);

request.setAttribute("productMap", map);

try {

request.getRequestDispatcher("/viewProduct.jsp").forward(request, response);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**批量删除产品

* @param request

* @param response

*/

private void delProduct(HttpServletRequest request,

HttpServletResponse response) {

// TODO Auto-generated method stub

System.out.println("进入del");

//获得复选框的值

String[] ids = request.getParameterValues("ids");

for (int i = 0; i < ids.length; i++) {

System.out.println("ids["+i+"]="+ids[i]);

}

boolean flag = service.delProduct(ids);

System.out.println("删除flag:"+flag);

if (flag) {

try {

request.getRequestDispatcher("/main.jsp").forward(request, response);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

private void listProduct(HttpServletRequest request,

HttpServletResponse response) {

// TODO Auto-generated method stub

String productName = request.getParameter("proname");

String pageNum = request.getParameter("pageNum");

System.out.println("参数 pageNum :"+pageNum);

if (productName == null) {

productName = "";

}

int totalRecord = service.getItemCount(productName); //获取总的记录数

int currentPage = 1;

DividePage dividePage = new DividePage(5, totalRecord);//默认第一页开始

if (pageNum != null) {

currentPage = Integer.parseInt(pageNum);

dividePage.setCurrentPage(currentPage);

}

//记录从第几行开始

int start = dividePage.fromIndex();

//显示几条记录

int end = dividePage.toIndex();

System.out.println("currentPageNum :"+ dividePage.getCurrentPage() +", start = "+start +", end = "+end);

List> list = null;

try {

list = service.listProduct(productName , start , end);

request.setAttribute("listProduct", list);

request.setAttribute("dividePage", dividePage);

request.setAttribute("productName",productName );

request.getRequestDispatcher("/main.jsp").forward(request, response);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

private void addProduct(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException{

//表单含有文件要提交

String path = request.getContextPath();

DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

servletFileUpload.setFileSizeMax(3*1024*1024);//单个文件大小限制3M

servletFileUpload.setSizeMax(6*1024*1024);//上传文件总大小

List list = null;

List params = new ArrayList();

params.add(UUIDTools.getUUID()); // 参数传 product表的主键

try {

//解析request的请求

list = servletFileUpload.parseRequest(request);

//取出所有表单的值,判断非文本字段和文本字段

for(FileItem fileItem : list){

if (fileItem.isFormField()) {//是文本字段

String fileItemName = fileItem.getFieldName(); //获取 控件的 名称

String fileItemValue = fileItem.getString("utf-8");//获取控件的值

if (fileItemName.equals("proname")) {

params.add(fileItemValue); //参数传入 proname

}else if (fileItemName.equals("proprice")) {

params.add(fileItemValue);//参数传入 proprice

}else if (fileItemName.equals("proaddress")) {

params.add(fileItemValue);参数传入 proaddress

}

}else{ //非文本字段

String imageName = fileItem.getName(); //获取文件名称

params.add(imageName);//参数传入 proimage

//String path = request.getRealPath("/upload");

String upload_dir = request.getServletContext().getRealPath("/upload");//获取服务器端 /upload 路径

File uploadFile = new File(upload_dir+"/"+imageName);

System.out.println("---upload_dir--->>"+uploadFile);

fileItem.write(uploadFile);

}

}

// 把产品加入数据库

boolean flag = service.addProduct(params);

if (flag) {

response.sendRedirect(path+"/main.jsp");

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

service = new ProductDao();

}

}

package com.product;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import com.jdbc.JdbcUtils;

public class ProductDao implements ProductService {

private JdbcUtils jdbcUtils;

public ProductDao() {

// TODO Auto-generated constructor stub

jdbcUtils = new JdbcUtils();

}

@Override

public boolean addProduct(List params) {

boolean flag = false;

try {

jdbcUtils.getConnection();

String sql = "insert into product(proid,proname,proprice,proaddress,proimage) values(?,?,?,?,?)";

flag = jdbcUtils.updateByPreparedStatement(sql, params);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}finally{

// 关闭数据库连接

jdbcUtils.releaseConn();

}

return flag;

}

@Override

public List> listProduct(String proname ,int start ,int end) {

// TODO Auto-generated method stub

List> list = new ArrayList>();

List params = new ArrayList();

try {

jdbcUtils.getConnection();

String sql = "select * from product where 1=1 and proname like ? limit ? ,?";

if(proname.equals("")){

sql = "select * from product limit ? ,?";

params.add(start);

params.add(end);

}else{

params.add("%"+proname+"%");

params.add(start);

params.add(end);

}

list = jdbcUtils.findMoreResult(sql, params);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally{

jdbcUtils.releaseConn();

}

return list;

}

//查询总记录数

@Override

public int getItemCount(String proname) {

// TODO Auto-generated method stub

int count = 0;

Map map = null;

List params = null;

try {

jdbcUtils.getConnection();

String sql = "select count(*) totalCount from product where 1=1 and proname like ?";

if(proname.equals("")){

sql = "select count(*) totalCount from product";

}else{

params = new ArrayList();

params.add("%"+proname+"%");

}

map = jdbcUtils.findSimpleResult(sql, params);

count = Integer.parseInt(map.get("totalCount").toString());

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally{

// 关闭数据库连接

jdbcUtils.releaseConn();

}

return count;

}

@Override

public boolean delProduct(String[] ids) {

boolean flag = false;

try {

jdbcUtils.getConnection();

if (ids!=null) {

String[] sql = new String[ids.length];

for(int i = 0 ; i< ids.length; i++){

sql[i] = "delete from product where proid = '"+ids[i]+"'";

System.out.println(sql[i]);

}

flag = jdbcUtils.deleteByBatch(sql);

}

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally{

// 关闭数据库连接

jdbcUtils.releaseConn();

}

return flag;

}

@Override

public Map viewProduct(String proid) {

// TODO Auto-generated method stub

Map map = null;

try {

jdbcUtils.getConnection();

List params = new ArrayList();

params.add(proid);

String sql = "select * from product where proid = ?";

map = jdbcUtils.findSimpleResult(sql, params);

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

} finally{

// 关闭数据库连接

jdbcUtils.releaseConn();

}

return map;

}

}

15. ProductService.java

package com.product;

import java.util.List;

import java.util.Map;

public interface ProductService {

public boolean addProduct(List params);

//列出产品,为了分页,加上参数 start,end

public List> listProduct(String proname , int start , int end);

//获取总的记录数

public int getItemCount(String proname);

//批处理删除产品

public boolean delProduct(String[] ids);

//查询单个产品

public Map viewProduct(String proid);

}

16. JdbcUtils.java

package com.jdbc;

import java.lang.reflect.Field;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import com.mysql.jdbc.Driver;

public class JdbcUtils {

// 定义数据库的用户名

private final String USERNAME = "root";

// 定义数据库的密码

private final String PASSWORD = "123456";

// 定义数据库的驱动信息

private final String DRIVER = "com.mysql.jdbc.Driver";

// 定义访问数据库的地址

private final String URL = "jdbc:mysql://localhost:3306/mydb";

// 定义访问数据库的连接

private Connection connection;

// 定义sql语句的执行对象

private PreparedStatement pstmt;

// 定义查询返回的结果集合

private ResultSet resultSet;

// 实现批处理的功能

private Statement stmt;

public JdbcUtils() {

// TODO Auto-generated constructor stub

try {

Class.forName(DRIVER);

System.out.println("注册驱动成功!!");

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

System.out.println("注册驱动失败!!");

}

}

// 定义获得数据库的连接

public Connection getConnection() {

try {

connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

} catch (Exception e) {

// TODO: handle exception

System.out.println("Connection exception !");

}

return connection;

}

/** 实现批处理删除

* @param sql

* @return

* @throws SQLException

*/

public boolean deleteByBatch(String[] sql) throws SQLException{

boolean flag = false;

stmt = connection.createStatement();

if (sql!=null) { //判断数组是否为空,不能用length来判断,否则可能会报空指针异常。

for(int i = 0 ; i

stmt.addBatch(sql[i]);

}

int[] count = stmt.executeBatch();

if (count!=null) {

flag = true;

}

}

return flag;

}

/**

* 完成对数据库标的增加删除和修改的操作

*

* @param sql

* @param params

* @return

* @throws SQLException

*/

public boolean updateByPreparedStatement(String sql, List params)

throws SQLException {

boolean flag = false;

int result = -1;// 表示当用户执行增加删除和修改的操作影响的行数

int index = 1; // 表示 占位符 ,从1开始

pstmt = connection.prepareStatement(sql);

if (params != null && !params.isEmpty()) {

for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i)); // 填充占位符

}

}

result = pstmt.executeUpdate();

flag = result > 0 ? true : false;

return flag;

}

/**

* 查询返回单条记录

*

* @param sql

* @param params

* @return

* @throws SQLException

*/

public Map findSimpleResult(String sql, List params)

throws SQLException {

Map map = new HashMap();

pstmt = connection.prepareStatement(sql);

int index = 1;

if (params != null && !params.isEmpty()) {

for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet = pstmt.executeQuery(); // 返回查询结果

ResultSetMetaData metaData = pstmt.getMetaData(); // 获取 结果中,一行所有列的结果

int cols_len = metaData.getColumnCount(); // 获得列的总数

while (resultSet.next()) {

for (int i = 0; i < cols_len; i++) {

String col_name = metaData.getColumnName(i + 1); // 获得第i列的字段名称

Object col_value = resultSet.getObject(col_name);// 返回 第i列的内容值

if (col_value == null) {

col_value = "";

}

map.put(col_name, col_value);

}

}

return map;

}

/**

* 查询返回多条记录

*

* @param sql

* @param params

* @return

* @throws SQLException

*/

public List> findMoreResult(String sql,

List params) throws SQLException {

List> list = new ArrayList>();

pstmt = connection.prepareStatement(sql);

int index = 1; // 表示占位符

if (params != null && !params.isEmpty()) {

for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet = pstmt.executeQuery(); // 返回查询结果集合

ResultSetMetaData metaData = resultSet.getMetaData(); // 获得列的结果

while (resultSet.next()) {

Map map = new HashMap();

int cols_len = metaData.getColumnCount(); // 获取总的列数

for (int i = 0; i < cols_len; i++) {

String col_name = metaData.getColumnName(i + 1); // 获取第 i列的字段名称

// ,列计算从1开始

Object col_value = resultSet.getObject(col_name); // 获取第i列的内容值

if (col_value == null) {

col_value = "";

}

map.put(col_name, col_value);

}

list.add(map);

}

return list;

}

/**

* 查询返回单个JavaBean(使用java反射机制)

*

* @param sql

* @param params

* @param cls

* @return

* @throws Exception

*/

public T findSimpleRefResult(String sql, List params,

Class cls) throws Exception {

T resultObject = null;

int index = 1; // 占位符

pstmt = connection.prepareStatement(sql);

if (params != null && !params.isEmpty()) {

for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i)); // 填充占位符

}

}

resultSet = pstmt.executeQuery(); // 获取查询结果

ResultSetMetaData metaData = resultSet.getMetaData(); // 获取列的信息

int cols_len = metaData.getColumnCount(); // 获取总的列数

while (resultSet.next()) {

// 通过反射机制创建实例

resultObject = cls.newInstance(); // java反射机制

for (int i = 0; i < cols_len; i++) {

String col_name = metaData.getColumnName(i + 1); // 获取第i列的名称

Object col_value = resultSet.getObject(col_name); // 获取第i列的值

if (col_value == null) {

col_value = "";

}

Field field = cls.getDeclaredField(col_name);

field.setAccessible(true);// 打开 JavaBean的访问 private权限

field.set(resultObject, col_value);

}

}

return resultObject;

}

/** 查询返回多个JavaBean(通过java反射机制)

* @param sql

* @param params

* @param cls

* @return

* @throws Exception

*/

public List findMoreRefResult(String sql, List params,

Class cls) throws Exception {

List list = new ArrayList();

int index = 1; //占位符

pstmt = connection.prepareStatement(sql);

if (params != null && !params.isEmpty()) {

for (int i = 0; i < params.size(); i++) {

pstmt.setObject(index++, params.get(i));

}

}

resultSet = pstmt.executeQuery(); // 返回查询结果集合

ResultSetMetaData metaData = resultSet.getMetaData(); // 返回列的信息

int cols_len = metaData.getColumnCount(); // 结果集中总的列数

while (resultSet.next()) {

// 通过反射机制创建一个java实例

T resultObject = cls.newInstance();

for (int i = 0; i < cols_len; i++) {

String col_name = metaData.getColumnName(i + 1); // 获得第i列的名称

Object col_value = resultSet.getObject(col_name); // 获得第i列的内容

if (col_value == null) {

col_value = "";

}

Field field = cls.getDeclaredField(col_name);

field.setAccessible(true); // 打开JavaBean的访问private权限

field.set(resultObject, col_value);

}

list.add(resultObject);

}

return list;

}

/**关闭数据库访问

* @throws SQLException

*/

public void releaseConn(){

if (resultSet!=null) {

try {

resultSet.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

if(stmt!=null){

try {

stmt.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

if (pstmt!=null) {

try {

pstmt.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

if (connection!=null) {

try {

connection.close();

} catch (Exception e) {

// TODO: handle exception

e.printStackTrace();

}

}

}

}

17. DividePage.java

package com.util;

public class DividePage {

private int pageSize ; //每一页的记录数

private int totalRecord;//总记录数

private int currentPage;//当前第几页

public DividePage(int pageSize, int totalRecord, int currentPage) {

this.pageSize = pageSize;

this.totalRecord = totalRecord;

setCurrentPage(currentPage);

}

public DividePage(int pageSize, int totalRecord) {

this(pageSize,totalRecord,1);

}

//获取总页数

public int getPageCount(){

int pageCount = totalRecord/pageSize;

int mod = totalRecord%pageSize;

if (mod!=0) {

pageCount++;

}

return pageCount;

}

// mysql : select * from product limit 5,10 表示查询记录行 第6到15行。

//起始记录从第几行开始(mysql 记录默认从第0行开始)

public int fromIndex(){

return (currentPage-1)*pageSize;

}

//要查询的的尾记录相对于起始记录的偏移量,即一页的记录数

public int toIndex(){

return pageSize;

}

public void setCurrentPage( int currentPage){

if (getPageCount()!=0) {//有记录

int validPage = currentPage<1?1:currentPage;

validPage = validPage>getPageCount()?getPageCount():validPage;

this.currentPage = validPage;

} else{ // 0条记录

this.currentPage = 1;

}

}

public int getPageSize() {

return pageSize;

}

public void setPageSize(int pageSize) {

this.pageSize = pageSize;

}

public int getTotalRecord() {

return totalRecord;

}

public void setTotalRecord(int totalRecord) {

this.totalRecord = totalRecord;

}

public int getCurrentPage() {

return currentPage;

}

}

18. UUIDTools.java

package com.util;

import java.util.UUID;

public class UUIDTools {

public UUIDTools() {

// TODO Auto-generated constructor stub

}

/**返回一个 6位的字符串

* @return

*/

public static String getUUID(){

UUID uuid = UUID.randomUUID();

return uuid.toString().replaceAll("-", "").substring(0, 6);

}

}

20. LogoutAction.java

package com.logout;

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;

public class LogoutAction extends HttpServlet {

/**

* Constructor of the object.

*/

public LogoutAction() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* 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.

*

* 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;charset=utf-8");

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

String path = request.getContextPath();

String action_flag = request.getParameter("action_flag");

if (action_flag.equals("logout")) {

request.getSession().removeAttribute("username");

response.sendRedirect(path+"/index.jsp");

}

}

/**

* Initialization of the servlet.

*

* @throws ServletException if an error occurs

*/

public void init() throws ServletException {

// Put your code here

}

}

21. web.xml

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_3_0.xsd">

This is the description of my J2EE component

This is the display name of my J2EE component

RegisterAction

com.register.RegisterAction

This is the description of my J2EE component

This is the display name of my J2EE component

LoginAction

com.login.LoginAction

This is the description of my J2EE component

This is the display name of my J2EE component

ProductAction

com.product.ProductAction

This is the description of my J2EE component

This is the display name of my J2EE component

LogoutAction

com.logout.LogoutAction

RegisterAction

/servlet/RegisterAction

LoginAction

/servlet/LoginAction

ProductAction

/servlet/ProductAction

LogoutAction

/servlet/LogoutAction

MyFilter

com.filter.MyFilter

MyFilter

/main.jsp

MyFilter

/addProduct.jsp

index.jsp

注意:

1. 使用过滤器,要引入jar包:servlet-2_5-api.jar

2. 使用jdbc连接mysql , 要引入jar包:mysql-connector-java-5.1.7-bin.jar

3. 文件上传,要引入2个jar包:

commons-fileupload-1.3.1.jar 和

commons-io-2.4.jar









  • 5
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值