一个简单的servletJDBCweb项目

这个项目会用到webDom4j解析xml ,   数据库  , junit  ,3层架构 

首先看一下这次项目的目录结构  


一个简单的servletJDBCweb项目_第1张图片一个简单的servletJDBCweb项目_第2张图片


下面依次贴出代码 


首先bean

package com.my.servlet.bean;

import java.io.Serializable;

public class StudentBean implements Serializable{
	private int id; 
	private String name;
	private String 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 getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	@Override
	public String toString() {
		return "StudentBean [id=" + id + ", name=" + name + ", sex=" + sex + "]";
	}
	
	
}

工具类  主要使用dom4j解析xml连接数据库 

 xml文件  

 
  
	
	com.mysql.jdbc.Driver
	jdbc:mysql://localhost:3306/test
	root
	123456


DBUtil类

package com.my.servlet.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class DBUtil {
	// 加载驱动 
	static{
		try {
			Class.forName(dom4jDemo("driver"));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * 连接数据库   
	 * @return   返回数据库连接  
	 */
	public static Connection connectionSql(){
		Connection conn = null;
		try {
			conn =  DriverManager.getConnection(dom4jDemo("url"), dom4jDemo("user"), dom4jDemo("password"));
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("数据库连接错误 ");
		}
		return conn;
	}
	
	/**
	 * 解析xml   将数据保存在xml文件中  通过解析xml来获得  
	 * @param element   需要得到的对象 
	 * @return   返回这个对象在xml中的值 
	 */
	public static String dom4jDemo(String element){
		// 创建saxReader对象  
        SAXReader reader = new SAXReader();  
        // 通过read方法读取一个文件 转换成Document对象  
        Document document;
        String result = "";
		try {
			// 因为要使用web  所以使用ClassLoader来读取
			ClassLoader classs = DBUtil.class.getClassLoader();
			InputStream io = classs.getResourceAsStream("dbXml.xml");
			document = reader.read(io);
			//获取根节点元素对象  
	        Element node = document.getRootElement();  
	        result = node.element(element).getText();
		} catch (DocumentException e) {
			System.out.println("文件找不到");
			e.printStackTrace();
		}  
		return result;
	}

}


dao层(持久层)

接口  

package com.my.servlet.dao.idao;

import java.util.List;

import com.my.servlet.bean.StudentBean;

public interface IStudentDao {
	/**
	 * 查询所有的学生  
	 * @return   
	 */
	public List getAllStudent();

}											

实现类 

package com.my.servlet.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.my.servlet.bean.StudentBean;
import com.my.servlet.dao.idao.IStudentDao;
import com.my.servlet.util.DBUtil;

public class StudentBeanDao implements IStudentDao{
	
	private DBUtil dbUtil = new DBUtil();
	@Override
	public List getAllStudent() {
		Connection conn = dbUtil.connectionSql();
		String sql = "SELECT t_student.sex,t_student.name,t_student.id FROM t_student";
		List students = new ArrayList();
		try {
			// 使用预编译    防止注入  
			PreparedStatement prepatedStatement=conn.prepareStatement(sql);
			ResultSet rs = prepatedStatement.executeQuery();
			//循环结果集  
			while(rs.next()){
				// 将值封装到对象中 
				StudentBean stu = new StudentBean();
				stu.setId(rs.getInt("t_student.id"));
				stu.setName(rs.getString("t_student.name"));
				stu.setSex(rs.getString("t_student.sex"));
				// 将对象添加到集合中 
				students.add(stu);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return students;
	}
	
}

server(服务层)

package com.my.servlet.server.iserver;

import java.util.List;

import com.my.servlet.bean.StudentBean;

public interface IStudentServerDao {
	/**
	 * 查询所有的学生  
	 * @return   
	 */
	public List getAllStudent();

}	


实现

package com.my.servlet.server;

import java.util.List;

import com.my.servlet.bean.StudentBean;
import com.my.servlet.dao.StudentBeanDao;
import com.my.servlet.dao.idao.IStudentDao;
import com.my.servlet.server.iserver.IStudentServerDao;

public class StudentServer implements IStudentServerDao{
	private IStudentDao isd = new StudentBeanDao();
	@Override
	public List getAllStudent() {
		// TODO Auto-generated method stub
		return isd.getAllStudent();
	}
}


servlet


package com.my.servlet.servlet;

import java.io.IOException;
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.google.gson.Gson;
import com.my.servlet.bean.StudentBean;
import com.my.servlet.server.StudentServer;
import com.my.servlet.server.iserver.IStudentServerDao;

/**
 * Servlet implementation class StudentServlet  因为版本3.0 所以采用的是注释  
 */
@WebServlet("/StudentServlet")
public class StudentServlet extends HttpServlet {
	
	private IStudentServerDao is = new StudentServer();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("=====");
		// 查询所有学生
		List stus = is.getAllStudent();
		// 使用Gson将值转换成json字符串  方便前台取值 
		Gson gson = new Gson();
		// 将数据响应回界面  
		response.getWriter().print(gson.toJson(stus));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


index.jsp


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>




My JSP 'index.jsp' starting page











	
编号 名字 性别

最后是web.xml



  Servlet
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  

还有一个防止乱码的过滤器  (针对post)

如果是get的话需要采用字符串转码的格式  

// 将gbk转化为utf-8
		String a = "4";
		String b = new String(a.getBytes("ISO8859-1"), "utf-8");

过滤器

package com.my.servlet.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.annotation.WebFilter;

/**
 * Servlet Filter implementation class EncodingFilter
 */
@WebFilter("/EncodingFilter")
public class EncodingFilter implements Filter {

    /**
     * Default constructor. 
     */
    public EncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}



你可能感兴趣的:(java)