一个简单的servletJDBCweb项目

来源:互联网 发布:火龙果软件培训 编辑:程序博客网 时间:2024/06/10 20:18

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

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




下面依次贴出代码 


首先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;}@Overridepublic String toString() {return "StudentBean [id=" + id + ", name=" + name + ", sex=" + sex + "]";}}

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

 xml文件  

<?xml version="1.0" encoding="UTF-8"?> <db>  
<!-- dbXml.xml --><driver>com.mysql.jdbc.Driver</driver><url>jdbc:mysql://localhost:3306/test</url><user>root</user><password>123456</password></db>

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<StudentBean> 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();@Overridepublic List<StudentBean> getAllStudent() {Connection conn = dbUtil.connectionSql();String sql = "SELECT t_student.sex,t_student.name,t_student.id FROM t_student";List<StudentBean> students = new ArrayList<StudentBean>();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 blocke.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<StudentBean> 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();@Overridepublic List<StudentBean> getAllStudent() {// TODO Auto-generated method stubreturn 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<StudentBean> 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 stubdoGet(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 + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.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"><script type="text/javascript" src="js/jquery-3.1.0.min.js"></script><script type="text/javascript" src="js/bootstrap.min.js"></script><script>$(function() {$.ajax({url : "/Servlet/StudentServlet",type : "post",dataType : "json",success : function(date) {var htmlStr = "";$.each(date,function(i){htmlStr += "<tr><td>"+date[i].id+"</td><td>"+date[i].name+"</td><td>"+date[i].sex+"</td></tr>";});$("tbody").html(htmlStr);}});});</script></head><body><br><table><thead><tr><th>编号</th><th>名字</th><th>性别</th></tr></thead><tbody><tr><td></td><td></td><td></td></tr></tbody></table></body></html>

最后是web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>Servlet</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>    </web-app>

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

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

// 将gbk转化为utf-8String 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}}



0 0
原创粉丝点击