简单的实现web项目《一》 查询数据库页面 java 代码

分为这几个包

cn.dao包

package cn.itcast.itcaststore.dao; 
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.utils.C3p0Utils;
public class UserDao {
// 查询所有,返回List集合
public List findAll() throws SQLException {
//获取C3P0数据源
DataSource dataSource = C3p0Utils.getDataSource();
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(dataSource);
// 写SQL语句
String sql = "select id,username,PASSWORD from user";
// 查询语句所以调用query方法  
List list = (List) runner.query(sql, 
new BeanListHandler(User.class));
return list;
}
// 查询单个元素
public User findOne(int id) throws SQLException {
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
// SQL语句
String sql = "select id,username,PASSWORD from user where id=?";
// 查询语句所以调用query方法 ,这里sql中出现了?即参数占位符,    object[]中的元素 对其进行赋值
User user = (User) runner.query(sql,
new BeanHandler(User.class), new Object[] { id });
return user;
}
// 添加用户的操作
public Boolean insert(User user) throws SQLException {
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
//  写SQL语句
String sql = "insert into user (username,password) values (?,?)";
// insert语句所以调用update方法 
int num = runner.update(sql,new Object[] { user.getUsername(), user.getPassword() });
if (num > 0)
return true;
return false;
}
// 修改用户的操作
public Boolean update(User user) throws SQLException {
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "update  user set username=?,password=? where id=?";
//  调用方法
int num = runner.update(sql, new Object[] { user.getUsername(), user.getPassword(),user.getId() });
if (num > 0)
return true;
return false;
}
// 删除用户的操作
public Boolean delete(int id) throws SQLException {
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "delete from user where id=?";
//调用方法
int num = runner.update(sql, id);
if (num > 0)
return true;
return false;
}

//登录
public Boolean login(String username,String password) throws SQLException{
// 创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "select count(*) from user where username=? and password=?";
 
   // int count =Integer.parseInt( runner.query(sql, new ScalarHandler(),new Object[] {username,password}).toString());
int count = ((Long)runner.query(sql, new ScalarHandler(),new Object[] {username,password})).intValue();
if(count==1){
    return true;
   }else{
    return false;
   }
}
}

cn.domain包

package cn.itcast.itcaststore.domain;
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;
}  
}

cn.service包

package cn.itcast.itcaststore.service;
import java.sql.SQLException;
import java.util.List;
import cn.itcast.itcaststore.dao.*;
import cn.itcast.itcaststore.domain.*;
public class UserService {
UserDao userDao=new UserDao();
public List findAll()throws SQLException{
return userDao.findAll();
}
public User findOne(int d)throws SQLException{
return (User) userDao.findOne(d);
}
public Boolean delete(int id)throws SQLException{
return userDao.delete(id);
}
public Boolean insert(User user)throws SQLException{
return userDao.insert(user);
}
public Boolean login(String username,String password)throws SQLException{
return userDao.login(username, password);
}
public Boolean update(User user) throws SQLException {
return userDao.update(user);
}
}

cn.servlet包

package cn.itcast.itcaststore.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.itcast.itcaststore.domain.User;
import cn.itcast.itcaststore.service.*;
/**
 * Servlet implementation class userServlet
 */
@WebServlet("/userServlet")
public class userServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public userServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");  
PrintWriter out = response.getWriter(); 
UserService userService =new UserService();
//获取对应的请求参数
        String method = request.getParameter("method");
        //根据请求参数去调用对应的方法。
        if ("query".equals(method)) {
        try {
    List userList = userService.findAll();
    request.setAttribute("userList", userList);
    request.getRequestDispatcher("/WEB-INF/user/showUsers.jsp").
    forward(request, response);  
    //response.sendRedirect("WEB-INF/user/ShowAllUser.jsp");//测试重定向是否能转到WEB-INF
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
        }
          else if ("queryById".equals(method)) {
            int id = Integer.parseInt(request.getParameter("id"));
             try {
User user= (User)userService.findOne(id);
ObjectMapper mapper = new ObjectMapper();  
   String userJSON = mapper.writeValueAsString(user);//将user对象转换为JSON字符串
   out.print(userJSON);
 } catch (SQLException e) {
 
 e.printStackTrace();
}
        } 
        else if ("delete".equals(method)) {
            int id = Integer.parseInt(request.getParameter("id"));
            try {
            if(userService.delete(id)){
            out.println("");
            response.sendRedirect("userServlet?method=query");
            }else{
            out.println("");
            }

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();

        } 
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");  
PrintWriter out = response.getWriter(); 
UserService userService =new UserService();
//获取对应的请求参数
        String method = request.getParameter("method");
        int id=0;
        if(request.getParameter("user_id")!=null&&request.getParameter("user_id")!=""){
         id =Integer.parseInt(request.getParameter("user_id"));
        } 
        String username =request.getParameter("user_name");
        String password=request.getParameter("user_password");
        User user =new User();
        user.setId(id);
        user.setUsername(username);
        user.setPassword(password); 
        
        //根据请求参数去调用对应的方法
        if ("insert".equals(method)) {
        try {  
if( userService.insert(user)){
ObjectMapper mapper = new ObjectMapper();  
   String userJSON = mapper.writeValueAsString(user);//将user对象转换为JSON字符串
   out.print(userJSON);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }else if("update".equals(method)){
        try {
if(userService.update(user)){
ObjectMapper mapper = new ObjectMapper();  
   String userJSON = mapper.writeValueAsString(user);//将user对象转换为JSON字符串
   out.print(userJSON);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        } else if("login".equals(method)){
        try {
if(userService.login(username, password)){ 
            response.sendRedirect("userServlet?method=query");
}else{  
response.sendRedirect("login.jsp?loginInfo=wrong");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
}



}


cn.utils包

package cn.itcast.itcaststore.utils;
import java.sql.SQLException;


import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Utils {
private static DataSource ds=null;//定义数据源
static {
ComboPooledDataSource coda= new ComboPooledDataSource();//创建数据源
     ds=coda;
//用 ComboPooledDataSource(String name)方法向 c3p0-config.xml
//的named-config中的节点name传值
//如果需要更改数据源,则改变name值即可!
//如果传入值为空或者没有传入值,则使用默认配置去创建数据源!
    }
public static DataSource getDataSource() {//返回数据源
 return ds;
                                        }

}

你可能感兴趣的:(简单的实现web项目《一》 查询数据库页面 java 代码)