前言
由于現在互聯網后端開發,已經出現了各種各樣的新技術,如SSM,SpringBoot,Cloud等,本人也已經很久很久沒有寫過純粹的Servlet+HTML+JDBC的專案了,于是今天就突然想寫一個純粹的底層專案,但是由于HTML是靜態頁面,而我又不想用JSP,更不想用什么什么模板,什么什么框架,這該怎么辦呢?于是,我就想到了Json,
代碼實作
Servlet和HTML,實作List傳值
@WebServlet("/personnel/dept")
public class DeptController extends BaseServlet {
private DeptService deptService = new DeptServiceImpl();
public void DeptList(HttpServletRequest request, HttpServletResponse response) throws IOException {
//獲取資料庫傳來的資料
List<Dept> list = deptService.selectList();
//將資料庫傳來的List轉化成Json格式
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(list);
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.write(json);
writer.flush();
writer.close();
}
}
<script type="text/javascript">
$(function () {
$.ajax({ type:"post",
url:"/OA/personnel/dept?method=DeptList",
success:function (result) {
//用來疊加資料 var no = "",name="",place="";
var tableTemp = "";
//方便等下動態繪制表格 for(var i = 0; i < result.length; i++){
//動態資料 no = result[i].dept_no; name = result[i].dept_name; place = result[i].dept_place; //動態表格,必須放在回圈內,否則 no 就不會被視為變數而是被視為空字串 var temp = "<tr>\n" +
" <td><input name=\"\" type=\"checkbox\" value=https://www.cnblogs.com/"\" /></td>\n" +
" <td >" + no + "</td>\n" +
" <td >" + name + "</td>\n" +
" <td >" + place + "</td>\n" +
" <td> <a href=https://www.cnblogs.com/"deptUpdate.html\" class=\"tablelink\">修改</a> \n" +
" <a href=https://www.cnblogs.com/"#\" class=\"tablelink click\"> 洗掉</a>\n" +
" </td>\n" +
" </tr>";
/* 動態表格,每次回圈累加 */ tableTemp += temp; $("#tableBody").html(tableTemp);
} },fail:function (result) {
alert("error");
} }) }); </script>
頁面效果
需要更多好玩的代碼資料,可以關注好友并私信“資料”給我哦~~
不過從剛剛的代碼,可能已經有人看出了問題,因為,正常的Servlet,不應該是用service方法,或者doGet,和doPost嗎?為什么我剛剛連HttpServlet都沒有繼承,博主你是騙我的吧?
然而事實是,并沒有,因為,為了把Servlet盡量做到最簡,博主這里已經準備好了很多工具類使用~
為了讓Servlet用起來更接近SpringMVC,我會先寫一個BaseServlet來替代HttpServlet,使用的時候,只需要繼承BaseServlet,然后直接寫方法,并不用每次都要一個Service,達到類似SpringMVC的效果,
BaseServlet
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//呼叫方法的引數 -- method值必須和呼叫的方法名保持一致
String method = request.getParameter("method");
//獲得本類物件
Class clazz = this.getClass();
System.out.println(clazz + "---" + method);
//使用反射進行方法呼叫
try {
Method declaredMethod = clazz.getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
declaredMethod.setAccessible(true);
declaredMethod.invoke(this,request,response);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
這個時候訪問它只需要路徑+方法名就可以了~
/OA/personnel/dept?method=DeptList
jdbc我們都知道,他們非常的繁瑣,為了讓它操作起來,只需要一兩行代碼,甚至用起來更像Mybatis,于是我們可以寫一個工具類,用來對JDBC的很多操作進行封裝
以下代碼曾出現在兩篇JDBC的文章里,以下兩個連接就是
JDBC(Java Database Connectivity) 資料庫連接技術
再談JDBC?
查詢方法
public static <T> List<T> baseQuery(T t, String sql, Object ... args){
// 獲取list集合中要裝的物件的位元組碼
Class aClass = t.getClass(); Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List<T> list = null; try { connection = JdbcUtil.getConnection(); statement = connection.prepareStatement(sql); // 設定引數的程序
for (int i = 0; i < args.length; i++) {
statement.setObject(i + 1, args[i]);
} resultSet = statement.executeQuery(); // 獲取全部的欄位
Field[] fs = aClass.getDeclaredFields(); // 先設定屬性可以訪問
for(Field f:fs){
f.setAccessible(true);
} list=new ArrayList<>(); while(resultSet.next()){
// 創建物件
T element = (T)aClass.newInstance(); // 從結果集的一條資料中取出每個欄位的資訊,放入element物件上去
// 遍歷fs 通過屬性名 去結果集中獲取資料
for(Field f:fs){
String name = f.getName();
Object value=https://www.cnblogs.com/kkkfff/p/null;
// 判斷物體類屬性的資料型別,選擇對應的get方法
if(f.getType()==int.class){
value = https://www.cnblogs.com/kkkfff/p/resultSet.getInt(name);
}else if(f.getType()==double.class){
value = https://www.cnblogs.com/kkkfff/p/resultSet.getDouble(name);
}else if(f.getType()==boolean.class){
value = https://www.cnblogs.com/kkkfff/p/resultSet.getBoolean(name);
}else{
value= https://www.cnblogs.com/kkkfff/p/resultSet.getObject(name);
}
f.set(element,value);
}
list.add(element);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeAll(resultSet,statement,connection);
}
return list;
}
插入方法
public static int executeUpdate(String sql,Object []params){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//默認添加失敗
int flag = 0;
try {
//建立資料庫連接
connection = getConnection();
//創建一個SQL命令發送器
preparedStatement = connection.prepareStatement(sql);
//準備好SQL陳述句,通過SQL命令發送器發送給資料庫,并得到結果
for(int i = 0; i < params.length; i++){
preparedStatement.setObject(i + 1, params[i]);
}
flag = preparedStatement.executeUpdate();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return flag;
}
這個時候我們Dao層真的就只需要一行代碼就可以了~
public List<Dept> selectList(){
return JdbcUtil.baseQuery(new Dept(),"select * from dept where or_delete = 0");
}123
所以經過了層層封裝,最后到了Controller層,就會給人一種好像是在使用SpringMVC的效果(事實上,這個頁面還有東西可以封裝,但是博主有點懶,就覺得沒必要了...),但是在這里還是要提醒一下,平時自己私下玩玩可以,真正的作業中,還是要根據公司的規范來哦~
需要更多好玩的代碼資料,可以關注好友并私信“資料”給我哦~~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/3016.html
標籤:Java
