Java web:整合servlet,反射,萬能DAO,增加功能,解決404報(bào)錯(cuò),時(shí)間戳【詩書畫唱】



萬能DAO的添加功能的例子:


create table Userinfo(
id? int primary key auto_increment,
act varchar(100) not null,
?pwd varchar(100) not null);
insert into Userinfo(
act ,
pwd?
) values ("詩書畫唱用戶名1","888"),
("詩書畫唱用戶名2","666"),
("詩書畫唱用戶名3","777");
select * from Userinfo
___
create table Product(
id int primary key auto_increment,
pname varchar(100) not null,
price double);
insert into Product(
pname,
price?
) values ("詩書畫唱商品1",1.1),
("詩書畫唱商品2",1.2),
("詩書畫唱商品3",1.3);
select * from Product
————————
create table Game(
id int primary key auto_increment,
?gname? varchar(100) not null,
?gtype? varchar(100) not null,
gcomp? varchar(100) not null,
?gyear int)
insert into Game(
gname ,
?gtype ,
gcomp,
?gyear
) values ("詩書畫唱游戲名1","詩書畫唱游戲類型名1","詩書畫唱公司名1",2020),
("詩書畫唱游戲名2","詩書畫唱游戲類型名2","詩書畫唱公司名2",2021),
("詩書畫唱游戲名3","詩書畫唱游戲類型名3","詩書畫唱公司名3",2022);
select * from? Game
drop table? Game
————————
create table studentInfo(
sid int primary key auto_increment,
sname varchar(100) not null,
sgender varchar(100)? default '男' not null,
sage int not null,
saddress varchar(100) ,
semail? varchar(100) );
insert into? studentInfo(
sname ,
sgender ,
sage ,
saddress ,
semail?
) values ("詩書畫唱1",'男','19','北京市朝陽區(qū)','SSHC1@163. com'),
("詩書畫唱2",'男','20','北京市朝陽區(qū)','SSHC2@163. com'),
("詩書畫唱3",'男','30','北京市朝陽區(qū)','SSHC3@163. com');
--drop table studentInfo
--select * from studentInfo
——————————————————————





package com.Sshc.bean;
public class Game {
? ? private Integer id;
? ? private String gname;
? ? private String gtype;
? ? private String gcomp;
? ? private Integer gyear;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public String getGtype() {
return gtype;
}
public void setGtype(String gtype) {
this.gtype = gtype;
}
public String getGcomp() {
return gcomp;
}
public void setGcomp(String gcomp) {
this.gcomp = gcomp;
}
public Integer getGyear() {
return gyear;
}
public void setGyear(Integer gyear) {
this.gyear = gyear;
}
}

package com.Sshc.bean;
public class Product {
? ? private Integer id;
? ? private String pname;
? ? private Double price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
}

package com.Sshc.bean;
public class Userinfo {
? ? private Integer id;
? ? private String act;
? ? private String pwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAct() {
return act;
}
public void setAct(String act) {
this.act = act;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}


package com.Sshc.dao;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
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.Sshc.bean.Game;
import com.Sshc.bean.Product;
import com.Sshc.bean.Userinfo;
import com.Sshc.util.DbUtil;
//萬能Dao
//T不是一個(gè)具體的java類,他是一個(gè)泛型參數(shù)
public class BaseDao<T> {
? ? public<T> List<T>selectAll(Class cls) throws Exception{
? ? Connection conn = null;
? ? PreparedStatement pstm = null;
? ? ResultSet rs = null;
? ? List<T>list = new ArrayList<T>();
? ? //通過反射技術(shù)獲取表的名字,表的名字剛好和bean的名字一樣
? ? //獲取類的類名
? ? String tableName = cls.getSimpleName();
? ? String sql = "select * from " + tableName;
? ? System.out.println(sql);
? ?
? ? conn = DbUtil.getConn();
? ? pstm = conn.prepareStatement(sql);
? ? rs = pstm.executeQuery();
? ? //獲取bean中的所有屬性名
Field []fs = cls.getDeclaredFields();
? ? while(rs.next()) {
? ? //通過反射創(chuàng)建出cls對(duì)象的實(shí)例
? ? Object obj = cls.newInstance();
? ? for(int i = 0;i < fs.length;i ++) {
? ? //bean中的屬性名
? ? String fname = fs[i].getName();
? ? //獲取bean中的屬性的類型
? ? Class type = fs[i].getType();
? ? Object o = rs.getObject(fname);
? ? //System.out.println(o);?
? ? //將屬性對(duì)應(yīng)的set方法名拼接出來
? ? //取出屬性名的首字母,將它變成大寫
? ? String methodName = "set" + fname.substring(0,1).toUpperCase()?
? ? + fname.substring(1);
? ? //System.out.println(methodName);
? ? //通過反射調(diào)用set方法
? ? Method m = cls.getDeclaredMethod(methodName, type);
? ? System.out.println(m);
? ? m.invoke(obj, o);? ?
? ? }
list.add((T)obj);
? ? }
? ? return list;
? ? }
? ? public Integer add(T t) throws Exception{
? ? Connection conn = null;
? ? PreparedStatement pstm = null;
? ? Integer count = -1;
? ? String tableName = t.getClass().getSimpleName();
? ? //System.out.println(tableName);
? ? StringBuilder sql = new StringBuilder("insert into " + tableName + " (");
? ? //取出t對(duì)象中的所有的屬性名
? ? Field []fs = t.getClass().getDeclaredFields();
? ? String dot = "";
? ? for(int i = 0;i < fs.length;i ++) {
? ? sql.append(dot);
? ? String fname = fs[i].getName();
? ? sql.append(fname);
? ? dot = ",";
? ? }
? ? sql.append(")values(");
? ? String dot1 = "";
? ? for(int i = 0;i < fs.length;i ++) {
? ? sql.append(dot1);
? ? sql.append("?");
? ? dot1 = ",";
? ? }
? ? sql.append(")");
? ? //System.out.println(sql);
? ?
? ? conn = DbUtil.getConn();
? ? pstm = conn.prepareStatement(sql.toString());
? ? //調(diào)用t對(duì)象中所有的get方法
? ? for(int i = 0;i < fs.length;i ++) {
? ? //取出屬性名
? ? String fname = fs[i].getName();
? ? //拼接get方法
? ? String methodName = "get" + fname.substring(0,1).toUpperCase()
? ? + fname.substring(1);
? ? //取出需要調(diào)用的方法
? ? Method m = t.getClass().getDeclaredMethod(methodName);
? ? //反射調(diào)用get方法
? ? Object val = m.invoke(t);
? ? System.out.println("新增的數(shù)據(jù)是:" + val);
? ? //設(shè)置占位符
? ? pstm.setObject(i + 1, val);
? ? }
? ? count = pstm.executeUpdate();
? ? return count;
? ? }
? ? public Integer update(T t){
? ? return 0;
? ? }
? ? public Integer delete(Integer id){
? ? return 0;
? ? }
? ??
? ?
}


package com.Sshc.dao;
import com.Sshc.bean.Game;
public class GameDao extends BaseDao<Game> {
}

package com.Sshc.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.Sshc.bean.Product;
import com.Sshc.util.DbUtil;
public class ProductDao extends BaseDao<Product> {? ?
//這個(gè)方法只是用來進(jìn)行代碼的對(duì)比,當(dāng)有了BaseDao以后,這個(gè)方法就可以刪除了
//? ? public Integer add(Product p){
//? ? Connection conn = null;
//? ? PreparedStatement pstm = null;
//? ? Integer count = -1;
//? ? String sql = "insert into product (id,pname,price)values(?,?,?)";? ?
//? ? try {
//? ? conn = DbUtil.getConn();
// pstm = conn.prepareStatement(sql);
// pstm.setInt(1, p.getId());
// pstm.setString(2, p.getPname());
// pstm.setDouble(3, p.getPrice());
// count = pstm.executeUpdate();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } finally {
// DbUtil.close(null, pstm, conn);
// }
//? ? return count;
//? ? }
}

package com.Sshc.dao;
import java.util.List;
import com.Sshc.bean.Userinfo;
public class UserinfoDao extends BaseDao<Userinfo> {
}

package com.Sshc.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class DbUtil {
private static String driverName;
private static String url;
private static String userName;
private static String userPwd;
? ? static {
? ? Properties prop = new Properties();
? ? InputStream is = DbUtil.class.getClassLoader()
? ? .getResourceAsStream("db.properties");
? ? try {
prop.load(is);
driverName = prop.getProperty("dn");
url = prop.getProperty("url");
userName = prop.getProperty("un");
userPwd = prop.getProperty("up");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
? ? }
? ? //獲取數(shù)據(jù)庫連接對(duì)象的方法
? ? public static Connection getConn(){
? ? Connection conn = null;
? ? try {
Class.forName(driverName);
conn = DriverManager.getConnection(url,userName,userPwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
? ? return conn;
? ? }
? ? //關(guān)閉資源的方法
? ? public static void close(ResultSet rs,PreparedStatement pstm
? ? ,Connection conn){
? ? try {
? ? if(rs != null) {
? ? rs.close();
? ? }
? ? if(pstm != null) {
? ? pstm.close();
? ? }
? ? if(conn != null) {
? ? conn.close();
? ? }
? ? } catch(Exception e) {
? ? e.printStackTrace();
? ? }
? ? }
}

package DiaoYong;
import com.Sshc.bean.Game;
import com.Sshc.dao.GameDao;
public class DiaoYongG {
public static void main(String[] args) throws Exception {
? ? GameDao gd = new GameDao();
? ? Game g = new Game();
// ? ? g.setId(8);
? ? g.setGname("死亡鬼屋");
? ? g.setGtype("打字");
? ? g.setGyear(1999);
? ? g.setGcomp("詩書畫唱公司");
? ? gd.add(g);
}
}

package DiaoYong;
import com.Sshc.bean.Product;
import com.Sshc.dao.ProductDao;
public class DiaoyongP {
public static void main(String[] args) throws Exception {
ProductDao pd = new ProductDao();
Product p = new Product();
// p.setId(2);
p.setPname("詩書畫唱巧克力");
p.setPrice(6.6);
pd.add(p);
}
}

package DiaoYong;
import com.Sshc.bean.Userinfo;
import com.Sshc.dao.UserinfoDao;
public class DiaoYongU {
public static void main(String[] args) throws Exception {
UserinfoDao ud = new UserinfoDao();
Userinfo u = new Userinfo();
// u.setId(2);
u.setAct("詩書畫唱");
u.setPwd("666666");
ud.add(u);
}
}



整合servlet:



package com.Sshc.controller;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
?* Servlet implementation class PubServlet
?*/
@WebServlet("/ps")
public class PubServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
? ? ? ?
? ? /**
? ? ?* @see HttpServlet#HttpServlet()
? ? ?*/
? ? public PubServlet() {
? ? ? ? super();
? ? ? ? // TODO Auto-generated constructor stub
? ? }
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//接收到操作信號(hào)
//ps?method=login
//ps?method=reg
//ps?method=modifyPwd
String method = request.getParameter("method");
// if("login".equals(method)) {
// System.out.println("執(zhí)行登錄");
// } else if("reg".equals(method)) {
// System.out.println("執(zhí)行注冊(cè)");
// } else if("modifyPwd".equals(method)) {
// System.out.println("修改密碼");
// }
//獲取當(dāng)前servlet的Class對(duì)象
Class cls = this.getClass();
try {
//獲取指定的方法對(duì)象
Method m = cls.getDeclaredMethod(method);
//反射調(diào)用
m.invoke(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}?
}
? ? private void login(){
? ? System.out.println("執(zhí)行登錄");
? ? }
? ? private void reg(){
? ? System.out.println("執(zhí)行注冊(cè)");
? ? }
? ? private void modifyPwd(){
? ? System.out.println("修改密碼");
? ? }
}


<%@ page language="java" contentType="text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
? ? ? ? <title></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">
? ? </head>
? ? <body>
? ? ? ? <form action="ps?method=login" method="post">
? ? ? ? ? ? <input type="submit" value="登錄" />
? ? ? ? </form>
? ? ? ? <form action="ps?method=modifyPwd" method="post">
? ? ? ? ? ? <input type="submit" value="修改密碼" />
? ? ? ? </form>
? ? </body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8" 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 hreff="<%=basePath%>">
? ? ? ? <title></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">
? ? </head>
? ? <body>
? ? ? ? <form action="ps?method=reg" method="post">
? ? ? ? ? ? <input type="submit" value="注冊(cè)" />
? ? ? ? </form>
? ? </body>
</html>






反射調(diào)用的實(shí)例:

package fanSheDiaoYong;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import com.Sshc.bean.Product;
public class Demo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
? ? ? ? //獲取類類(類的使用說明書)
//方法一:
//Class c1 = Product.class;
//方法二:
//Product p = new Product();
//Class c2 = p.getClass();
//方法三:
Class c3 = Class.forName("com.Sshc.bean.Product");
//通過類類來使用反射技術(shù)
//獲取Product類中所有的屬性
Field []fs = c3.getDeclaredFields();
for(int i = 0;i < fs.length;i ++) {
//依次取出屬性
Field f = fs[i];
//獲取屬性名
String name = f.getName();
//獲取屬性類型
Class type = f.getType();
System.out.println("屬性名:" + name);
System.out.println("屬性類型是:" + type.getName());
//拼接get方法
//將屬性名的首字母變成大寫
String methodName = "get" +?
name.substring(0,1).toUpperCase()?
+ name.substring(1);
System.out.println(methodName);
}
//獲取指定方法名的方法
// String methodName = "getId";
// //獲取methodName字符串指定的方法
// Method m = c3.getDeclaredMethod(methodName);
// System.out.println(m);
//
// String mn = "setId";
// Method m1 = c3.getDeclaredMethod(mn, Integer.class);
// System.out.println(m1);
}
}



獲取后綴名,給下載的文件等添加時(shí)間戳的關(guān)鍵的部分:

package houZhuiMing;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
//生成一個(gè)時(shí)間戳
//獲取到當(dāng)前的日期
Date now = new Date();
//將當(dāng)前日期轉(zhuǎn)換成時(shí)間戳
SimpleDateFormat sdf =?
new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");
String stamp = sdf.format(now);
System.out.println("時(shí)間戳是:" + stamp);
//UUID:全球唯一標(biāo)識(shí)符
String fileName = "abc.png";
//找到文件中.的位置
int index = fileName.lastIndexOf('.');
String f1 = fileName.substring(0,index);
System.out.println("文件的前半部分是:" + f1);
String f2 = fileName.substring(index);
System.out.println("文件的后半部分是:" + f2);
//添加時(shí)間戳
String fname = f1 + "-" + stamp + f2;
System.out.println("處理以后的文件名是:" + fname);
}
}



