Java web:整合servlet,反射,万能DAO,增加功能,解决404报错,时间戳【诗书画唱】



万能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','北京市朝阳区','SSHC1@163. com'),
("诗书画唱2",'男','20','北京市朝阳区','SSHC2@163. com'),
("诗书画唱3",'男','30','北京市朝阳区','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不是一个具体的java类,他是一个泛型参数
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>();
//通过反射技术获取表的名字,表的名字刚好和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()) {
//通过反射创建出cls对象的实例
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);
//将属性对应的set方法名拼接出来
//取出属性名的首字母,将它变成大写
String methodName = "set" + fname.substring(0,1).toUpperCase()
+ fname.substring(1);
//System.out.println(methodName);
//通过反射调用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对象中的所有的属性名
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());
//调用t对象中所有的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);
//取出需要调用的方法
Method m = t.getClass().getDeclaredMethod(methodName);
//反射调用get方法
Object val = m.invoke(t);
System.out.println("新增的数据是:" + val);
//设置占位符
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> {
//这个方法只是用来进行代码的对比,当有了BaseDao以后,这个方法就可以删除了
// 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();
}
}
//获取数据库连接对象的方法
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;
}
//关闭资源的方法
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
//接收到操作信号
//ps?method=login
//ps?method=reg
//ps?method=modifyPwd
String method = request.getParameter("method");
// if("login".equals(method)) {
// System.out.println("执行登录");
// } else if("reg".equals(method)) {
// System.out.println("执行注册");
// } else if("modifyPwd".equals(method)) {
// System.out.println("修改密码");
// }
//获取当前servlet的Class对象
Class cls = this.getClass();
try {
//获取指定的方法对象
Method m = cls.getDeclaredMethod(method);
//反射调用
m.invoke(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void login(){
System.out.println("执行登录");
}
private void reg(){
System.out.println("执行注册");
}
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="注册" />
</form>
</body>
</html>






反射调用的实例:

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");
//通过类类来使用反射技术
//获取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);
}
}



获取后缀名,给下载的文件等添加时间戳的关键的部分:

package houZhuiMing;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
//生成一个时间戳
//获取到当前的日期
Date now = new Date();
//将当前日期转换成时间戳
SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss-SSS");
String stamp = sdf.format(now);
System.out.println("时间戳是:" + stamp);
//UUID:全球唯一标识符
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);
//添加时间戳
String fname = f1 + "-" + stamp + f2;
System.out.println("处理以后的文件名是:" + fname);
}
}



