框架原理反射的应用
来源:互联网 发布:c语言最大公约数流程图 编辑:程序博客网 时间:2024/05/19 14:19
企业级开发
企业级应用需要解决:并发,交互,事务,集群,安全,分布式,WEB的一系列问题。
EJB
由EJB(企业级javabean)服务主要提供生命周期管理、代码产生、持续性管理、安全、事务管理、锁和并发行管理等服务。 EJB提供会话BEAN。消息驱动BEAN和实体BEAN。
J2EE
是一套设计、开发、汇编和部署企业级应用程序的规范。
J2EE提供了企业级程序的开发平台,提供了多层结构、分布式、基于组件、松耦合、安全可靠、独立于平台且反应迅速的应用程序环境。
J2EE包含的组件技术
JSP:J2EE的Web层核心技术
Servlet:J2EEd Web层核心技术
JDBC:数据库访问技术
XML:跨平台的可扩展标记语言
EJB:J2EE的业务层核心技术
JNDI:JAVA命名和目录接口
JMS:JAVA消息服务
JTA和JTS:用于分布式事务管理的一套约定或规范
JavaMail:提供给开发者处理电子邮件相关的编程接口
RMI:远程方法调用
IDL:接口描述语言
EJB缺陷
WEB容器提供WEB服务。其他的支持由EJB容器解决。提供EJB组件使用服务器,核心是EJB服务。
EJB组件离开EJB容器无法使用,所以很重(重是指依赖性很强)
面向过程方式实现。
EJB编码冗长,测试困难等
三层架构各框架
表现层:Struts1,Struts2,springMVC,webWork
持久层:hibernate,mybatis,jdo,EJB实体BEAN 业务层:变化度太大,无规律可循。
spring是整个框架管理。
以下代码诠释框架原理中反射的应用
建立实体类
package com.lovo.bean;
import java.sql.Date;
public class StudentBean {
private int id;
private String studentName;
private Date birthday;
private String edu;
private String info;
private int money;
public StudentBean(String studentName, Date birthday, String edu,
String info, int money) {
super();
this.studentName = studentName;
this.birthday = birthday;
this.edu = edu;
this.info = info;
this.money = money;
}
public StudentBean() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getEdu() {
return edu;
}
public void setEdu(String edu) {
this.edu = edu;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
@Override
public String toString() {
return "StudentBean [id=" + id + ", studentName=" + studentName
+ ", birthday=" + birthday + ", edu=" + edu + ", info=" + info
+ ", money=" + money + "]";
}
}
数据库操作
方法接口
package com.lovo.dao;
import java.util.List;
import com.lovo.bean.StudentBean;
public interface IStudentDao {
public void add(StudentBean bean);
public void del(int id);
public void update(int id,int money);
public List<StudentBean> findAll();
public List<StudentBean> findByName(String name);
public StudentBean findById(int id);
}
建立连接的父类
package com.lovo.dao.impl;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.sql.ResultSetMetaData;
public class BaseDao {
protected Connection con;
protected PreparedStatement ps;
protected ResultSet rs;
//建立连接
public void setConnection(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8","root","123456789");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//关闭连接
public void closeConnection(){
try{
if(rs != null){
rs.close();
}
if(ps != null){
ps.close();
}
if(con != null){
con.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* 更新数据(增、删、改)
* @param sql SQL语句
* @param valueObj 占位符值列表
*/
public void updateData(String sql,Object[] valueObj){
this.setConnection();
try {
ps = con.prepareStatement(sql);
for(int i=0;i<valueObj.length;i++){
ps.setObject(i+1, valueObj[i]);
}
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
this.closeConnection();
}
}
public List find(String sql,Object[] valueObj,Class beanClass){
List list = new ArrayList();
this.setConnection();
try {
ps = con.prepareStatement(sql);
if(valueObj != null){
for(int i=0;i<valueObj.length;i++){
ps.setObject(i+1, valueObj[i]);
}
}
rs = ps.executeQuery();
//第一种方法
// Field[] fs = beanClass.getDeclaredFields();
//
// while(rs.next()){
// Object obj = beanClass.newInstance();
//
// for(Field f : fs){
// f.setAccessible(true);
// try{
// //得到属性对象的属性名
// String fieldName = f.getName();
// f.set(obj, rs.getObject(fieldName));
// }catch(Exception e){
// continue;//此举可让其不打印异常信息,直接进行下一步操作,效率低
// }
// }
// list.add(obj);
// }
//第二种方法
//得到结果集审核对象
ResultSetMetaData meta = rs.getMetaData();
//得到结果集查询的总列数
int columns = meta.getColumnCount();
while(rs.next()){
Object obj = beanClass.newInstance();
for(int i=1;i<=columns;i++){
//查询指定列的名称
String columnName = meta.getColumnName(i);
//得到指定列对应的属性对象
Field f = beanClass.getDeclaredField(columnName);
f.setAccessible(true);
f.set(obj, rs.getObject(columnName));
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
this.closeConnection();
}
return list;
}
//测试
public static void main(String[] args) {
BaseDao dao = new BaseDao();
dao.setConnection();
System.out.println(dao.con);
}
}
数据库实现类
package com.lovo.dao.impl;
import java.sql.Date;
import java.util.List;
import com.lovo.bean.StudentBean;
import com.lovo.dao.IStudentDao;
public class StudentDaoImpl extends BaseDao implements IStudentDao{
@Override
public void add(StudentBean bean) {
this.updateData("INSERT INTO t_student(studentName,birthday,edu,money,info) values(?,?,?,?,?)",
new Object[]{bean.getStudentName(),bean.getBirthday(),bean.getEdu(),bean.getMoney(),bean.getInfo()});
}
@Override
public void del(int id) {
this.updateData("delete from t_student where id=?", new Object[]{id});
}
@Override
public void update(int id, int money) {
this.updateData("update t_student set money=? where id=?", new Object[]{money,id});
}
@Override
public List<StudentBean> findAll() {
// TODO Auto-generated method stub
return this.find("select * from t_student", null, StudentBean.class);
}
@Override
public List<StudentBean> findByName(String name) {
// TODO Auto-generated method stub
return this.find("select * from t_student where studentName like ?",
new Object[]{"%"+name+"%"}, StudentBean.class);
}
@Override
public StudentBean findById(int id) {
// TODO Auto-generated method stub
List list = this.find("select * from t_student where id=?", new Object[]{id}, StudentBean.class);
return (StudentBean)list.get(0);
}
public static void main(String[] args) {
IStudentDao dao = new StudentDaoImpl();
// dao.add(new StudentBean("王五",Date.valueOf("1980-02-02"),"高中","全优",3000));
// dao.update(3, 4500);
// dao.del(3);
// System.out.println(dao.findAll());
// System.out.println(dao.findByName("李"));
// System.out.println(dao.findById(1));
}
}
逻辑方法接口
package com.lovo.service;
public interface IStudentService {
public void update(int id,int money);
}
逻辑方法实现类
package com.lovo.service.impl;
import com.lovo.dao.IStudentDao;
import com.lovo.dao.impl.StudentDaoImpl;
import com.lovo.service.IStudentService;
import com.lovo.util.Factory;
public class StudentServiceImpl implements IStudentService{
private IStudentDao dao = (IStudentDao)Factory.getBean("IStudentDao");
@Override
public void update(int id, int money) {
dao.update(id, money);
}
//测试
public static void main(String[] args) {
IStudentService s = new StudentServiceImpl();
s.update(1, 8000);
}
}
控制层
package com.lovo.servlet;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.Date;
import java.util.Enumeration;
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.lovo.bean.StudentBean;
/**
* Servlet implementation class AddServlet
*/
@WebServlet("/add")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddServlet() {
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
StudentBean bean = new StudentBean();
this.fullForm(bean, request);
response.getWriter().print(bean);
}
/**
* 将请求对象中的数据,封装实体对象
* @param objBean 实体对象
* @param request 请求对象
*/
private void fullForm(Object objBean,HttpServletRequest request){
//得到所有表单名的枚举对象
Enumeration<String> em = request.getParameterNames();
//得到实体类的类模版
Class beanClass = objBean.getClass();
try{
while(em.hasMoreElements()){//判断是否有下一个元素
String formName = em.nextElement();//取出下一个元素
String value = request.getParameter(formName);
//得到指定表单名对应的属性对象(表单名和属性名必须一致)
Field f = beanClass.getDeclaredField(formName);
//去掉访问修饰符检查
f.setAccessible(true);
if(f.getType() == String.class){
f.set(objBean, value);
}
else if(f.getType() == int.class || f.getType() == Integer.class){
f.set(objBean, Integer.parseInt(value));
}
else if(f.getType() == Date.class){
f.set(objBean, Date.valueOf(value));
}
else if(f.getType() == double.class || f.getType() == Double.class){
f.set(objBean, Double.parseDouble(value));
}
else if(f.getType() == String[].class){
f.set(objBean, request.getParameterValues(formName));
}
}
}catch(Exception e){
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doGet(request, response);
}
}
工具类
package com.lovo.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
@WebFilter("/*")
public class CharFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
arg0.setCharacterEncoding("utf-8");
arg1.setContentType("text/html;charset=utf-8");
HttpServletRequest request = (HttpServletRequest)arg0;
arg2.doFilter(new MyRequest(request), arg1);
}
private class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
//重写方法过滤不雅字句
@Override
public String getParameter(String name) {
// TODO Auto-generated method stub
String value = request.getParameter(name);
//判断是否含有不雅字句"他妈的"
if(value.indexOf("他妈的") != -1){
//将“他妈的”替换成“***”
value = value.replaceAll("他妈的", “***”);
}
return value;
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
工厂模式
package com.lovo.util;
import java.io.FileReader;
import java.io.InputStream;
import java.util.Properties;
public class Factory {
private static Properties pro = new Properties();
static{
try {
//相对class文件,查找资源文件
InputStream in = Factory.class.getResourceAsStream("/dao.txt");
//加载资源文件
pro.load(in);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据接口名,得到该接口实现类对象
* @param interfaceName 接口名
* @return 实现类对象
*/
public static Object getBean(String interfaceName){
String classPath = pro.getProperty(interfaceName);
try {
//加载类,得到类模版
Class c = Class.forName(classPath);
return c.newInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
创建txt文件放置于src目录
IStudentDao=com.lovo.dao.impl.StudentDaoImpl
页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/student/add" method="post">
姓名:<input type="text" name="studentName"><br>
生日:<input type="text" name="birthday"><br>
学历:<select name="edu">
<option value="高中">高中</option>
<option value="大专">大专</option>
<option value="本科">本科</option>
</select><br>
身价:<input type="text" name="money"><br>
描述:<input type="text" name="info"><br>
<input type="submit" value="提交">
</form>
</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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>student</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>
- 框架原理反射的应用
- 简单的反射框架应用
- 反射:Class类、反射概念、类中各成员的反射、反射的应用、数组的反射、框架
- 反射的应用 原理 详细解析
- 反射的应用---实习框架功能
- struts2框架是如何应用反射的
- 框架的概念及用反射技术开发框架的原理
- 框架的概念及用反射技术开发框架的原理
- (Java基础--反射)框架的概念及用反射技术开发框架的原理
- Spring框架反射构建对象的代码原理(一)
- 8.9反射的应用 实现框架的功能
- 反射原理机制和应用
- 黑马程序员----反射机制的原理和应用
- Java反射机制在Android自动化测试框架的应用
- Java基础加强之框架的概念及反射技术的开发框架的原理
- 09.框架的概念及用反射技术开发框架的原理.
- Java高新技术之框架的概念及用反射技术开发框架的原理和配置文件
- Java基础知识_框架的概念以及用反射开发框架的原理
- javascript中call方法说明
- NOIP集训总结
- SVN命令行
- HTML5实现消灭星星
- caffe多任务学习之多标签分类
- 框架原理反射的应用
- 负载均衡——Nginx理论
- openCV(1)-Mat初始化
- HashMap源码分析
- LeetCode 101. Symmetric Tree
- 洛谷 P1462 通往奥格瑞玛的道路
- Hdu 5023 A Corrupt Mayor's Performance Art(线段树+状压)
- 让mybatis在控制台里打印sql语句
- C++总结