1. mybatis核心类
package com.lc.lcMybatis;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class LcResources {
public static InputStream getResourceAsStream(String resource) {
String file = new Object() {
public String getPath() {
return this.getClass().getResource("/").getPath();
}
}.getPath().substring(1);
String WEBINFPath=file.substring(0, file.indexOf("classes"));
String path=WEBINFPath+resource;
File f =new File(path);
//鍒涘缓鍩轰簬鏂囦欢鐨勮緭鍏ユ祦
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return fis;
}
}
package com.lc.lcMybatis;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class LcSqlSession {
private String modelPackage;
private Map<String, Map> mapInfo;
private Connection connection;
public String getModelPackage() {
return modelPackage;
}
public void setModelPackage(String modelPackage) {
this.modelPackage = modelPackage;
}
public Map<String,Map> getMapInfo() {
return mapInfo;
}
public void setMapInfo(Map<String, Map> mapInfo) {
this.mapInfo = mapInfo;
}
public Connection getConnection() {
return connection;
}
public void setConnection(Connection connection) {
this.connection = connection;
}
private final List<String> columnNames = new ArrayList<String>();
private final List<String> classNames = new ArrayList<String>();
public <E> E selectOne(String string, int id) {
E object = null;
try {
Statement statement = connection.createStatement();
Map map =mapInfo.get(string);
String sql=(String) map.get("sql");
sql=sql.replace("#{id}", id+"");
ResultSet rs = statement.executeQuery(sql);
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add( metaData.getColumnName(i));
classNames.add(metaData.getColumnClassName(i));
}
String resultType=(String) map.get("resultType");
String modelClassName=modelPackage+"."+resultType;
//构造器
Constructor constructor= Class.forName(modelClassName).getConstructor();
while (rs.next()) {
object=(E) constructor.newInstance();
Map propertyMap=new HashMap();
for (int i = 0; i < columnCount; i++) {
Object paramValue=new Object();
if(classNames.get(i).equals("java.lang.Integer")){
paramValue=rs.getInt(i+1);
}else if(classNames.get(i).equals("java.lang.String")){
paramValue=rs.getString(i+1);
}
String paramName=rs.getMetaData().getColumnName(i+1);
propertyMap.put(paramName, paramValue);
}
setValue(object,propertyMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
public <E> List<E> selectList(String sqlstring, Map<String, Object> params) {
List<E> list=new ArrayList<E>();
try {
Statement statement = connection.createStatement();
// 准备sql语句,注意: 字符串要用单引号'
Map map =mapInfo.get(sqlstring);
String sql=(String) map.get("sql");
for (Map.Entry<String, Object> entry : params.entrySet()) {
//Map.entry<Integer,String> 映射项(键-值对) 有几个方法:用上面的名字entry
//entry.getKey() ;entry.getValue(); entry.setValue();
//map.entrySet() 返回此映射中包含的映射关系的 Set视图。
//System.out.println("key= " + entry.getKey() + " and value= "+ entry.getValue());
sql=sql.replace("#{"+entry.getKey()+"}", "'"+entry.getValue()+"'");
}
//sql=sql.replace("#{0}", "'"+param+"'");
//System.out.println(sql);
ResultSet rs = statement.executeQuery(sql);
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add( metaData.getColumnName(i));
classNames.add(metaData.getColumnClassName(i));
}
String resultType=(String) map.get("resultType");
String modelClassName=modelPackage+"."+resultType;
//构造器
Constructor constructor= Class.forName(modelClassName).getConstructor();
while (rs.next()) {
Object object=constructor.newInstance();
Map propertyMap=new HashMap();
for (int i = 0; i < columnCount; i++) {
Object paramValue=new Object();
if(classNames.get(i).equals("java.lang.Integer")){
paramValue=rs.getInt(i+1);
}else if(classNames.get(i).equals("java.lang.String")){
paramValue=rs.getString(i+1);
}
String paramName=rs.getMetaData().getColumnName(i+1);
propertyMap.put(paramName, paramValue);
}
setValue(object,propertyMap);
list.add((E) object);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public <E> List<E> selectList(String sqlstring, String param) {
List<E> list=new ArrayList<E>();
try {
Statement statement = connection.createStatement();
// 准备sql语句,注意: 字符串要用单引号'
Map map =mapInfo.get(sqlstring);
String sql=(String) map.get("sql");
sql=sql.replace("#{0}", "'"+param+"'");
//System.out.println(sql);
ResultSet rs = statement.executeQuery(sql);
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add( metaData.getColumnName(i));
classNames.add(metaData.getColumnClassName(i));
}
String resultType=(String) map.get("resultType");
String modelClassName=modelPackage+"."+resultType;
//构造器
Constructor constructor= Class.forName(modelClassName).getConstructor();
while (rs.next()) {
Object object=constructor.newInstance();
Map propertyMap=new HashMap();
for (int i = 0; i < columnCount; i++) {
Object paramValue=new Object();
if(classNames.get(i).equals("java.lang.Integer")){
paramValue=rs.getInt(i+1);
}else if(classNames.get(i).equals("java.lang.String")){
paramValue=rs.getString(i+1);
}
String paramName=rs.getMetaData().getColumnName(i+1);
propertyMap.put(paramName, paramValue);
}
setValue(object,propertyMap);
list.add((E) object);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public <E> List<E> selectList(String sqlstring) {
List<E> list=new ArrayList<E>();
try {
Statement statement = connection.createStatement();
// 准备sql语句,注意: 字符串要用单引号'
Map map =mapInfo.get(sqlstring);
String sql=(String) map.get("sql");
ResultSet rs = statement.executeQuery(sql);
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add( metaData.getColumnName(i));
classNames.add(metaData.getColumnClassName(i));
}
String resultType=(String) map.get("resultType");
if(resultType==null){
resultType=(String) mapInfo.get(map.get("resultMap")).get("type");
//resultType="Student";
String modelClassName=modelPackage+"."+resultType;
//构造器
Constructor constructor= Class.forName(modelClassName).getConstructor();
Map idColumnMap=(Map) mapInfo.get(map.get("resultMap")).get("idColumn");
Map collectionIdColumnMap=(Map) ((Map) mapInfo.get(map.get("resultMap")).get("collection")).get("idColumn");
List collectionResultColumns=(List) ((Map) mapInfo.get(map.get("resultMap")).get("collection")).get("resultColumns");
Map collectionMap= (Map) mapInfo.get(map.get("resultMap")).get("collection");
while (rs.next()) {
Object object=constructor.newInstance();
Map propertyMap=new HashMap();
for (int i = 0; i < columnCount; i++) {
Object paramValue=new Object();
if(classNames.get(i).equals("java.lang.Integer")){
paramValue=rs.getInt(i+1);
}else if(classNames.get(i).equals("java.lang.String")){
paramValue=rs.getString(i+1);
}else if(classNames.get(i).equals("java.lang.Float")){
paramValue=rs.getFloat(i+1);
}
String paramName=rs.getMetaData().getColumnName(i+1);
propertyMap.put(paramName, paramValue);
}
propertyMap.remove(idColumnMap.get("property"));
List resultColumnsMaps=(List) mapInfo.get(map.get("resultMap")).get("resultColumns");
for(Object resultColumnsMap:resultColumnsMaps){
String property=(String) ((Map)resultColumnsMap).get("property");
propertyMap.remove(property);
}
System.out.println(propertyMap);
String ofType=(String) ((Map)mapInfo.get(map.get("resultMap")).get("collection")).get("ofType");
Constructor constructorCollection= Class.forName(modelPackage+"."+ofType).getConstructor();
Object objectCollection=constructorCollection.newInstance();
for (Object key : propertyMap.keySet()) {
//主对象
Object value = propertyMap.get(key);
if(key.equals(idColumnMap.get("column"))){
key=idColumnMap.get("property");
}
for(Object resultColumnsMap:resultColumnsMaps){
if(key.equals( ((Map)resultColumnsMap).get("column"))){
key= ((Map)resultColumnsMap).get("property");
}
}
//判断是否存在该属性
Field[] fields= object.getClass().getDeclaredFields();
boolean bool=false;
for (int i = 0; i < fields.length; i++) {
if(fields[i].getName().equals(key)){
bool=true;
break;
}
}
if(bool){
Field f1 = object.getClass().getDeclaredField((String) key);
f1.setAccessible(true);
f1.set(object, value);
continue;
}
//副对象
if(key.equals(collectionIdColumnMap.get("column"))){
key=collectionIdColumnMap.get("property");
}
for(Object resultColumnsMap:collectionResultColumns){
if(key.equals(((Map)resultColumnsMap).get("column"))){
key=((Map)resultColumnsMap).get("property");
}
}
//判断是否存在该属性
Field[] collectionFields= objectCollection.getClass().getDeclaredFields();
boolean collectionbool=false;
for (int i = 0; i < collectionFields.length; i++) {
if(collectionFields[i].getName().equals(key)){
collectionbool=true;
break;
}
}
if(!collectionbool){
continue;
}
Field collectionf1 = objectCollection.getClass().getDeclaredField((String) key);
collectionf1.setAccessible(true);
collectionf1.set(objectCollection, value);
}
Field coursesf1 = object.getClass().getDeclaredField((String) collectionMap.get("property"));
coursesf1.setAccessible(true);
List listCollection=new ArrayList<E>();
listCollection.add(objectCollection);
coursesf1.set(object, listCollection);
if(list.size()>0){
boolean isExsit=false;
for (Iterator<E> it = list.iterator(); it.hasNext();) {
E obj = it.next();
Field f1 = object.getClass().getDeclaredField((String)idColumnMap.get("property"));
f1.setAccessible(true);
Object primKey=f1.get(object);
Field f2 = obj.getClass().getDeclaredField((String) idColumnMap.get("property"));
f2.setAccessible(true);
Object primKey2=f2.get(obj);
if(primKey.equals(primKey2)){
isExsit=true;
Field objcoursesf1 = obj.getClass().getDeclaredField((String) collectionMap.get("property"));
objcoursesf1.setAccessible(true);
List objcoursesf1List=(List) objcoursesf1.get(obj);
objcoursesf1List.add(objectCollection);
objcoursesf1.set(obj, objcoursesf1List);
}
}
if(!isExsit){
list.add((E) object);
}
}else{
list.add((E) object);
}
}
}else{
String modelClassName=modelPackage+"."+resultType;
//构造器
Constructor constructor= Class.forName(modelClassName).getConstructor();
while (rs.next()) {
Object object=constructor.newInstance();
Map propertyMap=new HashMap();
for (int i = 0; i < columnCount; i++) {
Object paramValue=new Object();
if(classNames.get(i).equals("java.lang.Integer")){
paramValue=rs.getInt(i+1);
}else if(classNames.get(i).equals("java.lang.String")){
paramValue=rs.getString(i+1);
}else if(classNames.get(i).equals("java.lang.Float")){
paramValue=rs.getFloat(i+1);
}
String paramName=rs.getMetaData().getColumnName(i+1);
propertyMap.put(paramName, paramValue);
}
setValue(object,propertyMap);
list.add((E) object);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static Object setValue(Object object, Map map) {
try {
for (Object key : map.keySet()) {
Object value = map.get(key);
if(!isExistFieldName((String)key,object)){
continue;
}
Field f1 = object.getClass().getDeclaredField((String) key);
f1.setAccessible(true);
String type = f1.getType().toString();// 得到此属性的类型
if (type.endsWith("int") || type.endsWith("Integer")) {
f1.set(object, value);
} else {
f1.set(object, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
//判断是否包含某属性
public static Boolean isExistFieldName(String fieldName, Object obj) throws NoSuchFieldException {
//获取这个类的所有属性
Field[] fields = obj.getClass().getDeclaredFields();
boolean flag = false;
//循环遍历所有的fields
for (int i = 0; i < fields.length; i++) {
if (fields[i].getName().equals(fieldName)) {
flag = true;
break;
}
}
return flag;
}
public void insert(String string, Object object) {
try {
Statement statement = connection.createStatement();
// 准备sql语句,注意: 字符串要用单引号'
Map map =mapInfo.get(string);
String sql=(String) map.get("sql");
Field[] field = object.getClass().getDeclaredFields();
for(int j=0 ; j<field.length ; j++){ //遍历所有属性
String name = field[j].getName(); //获取属性的名字
//System.out.println("attribute name:"+name);
//打开私有访问
field[j].setAccessible(true);
Object paramValue=field[j].get(object);
if(paramValue==null){
paramValue="null";
}else{
paramValue="'"+paramValue+"'";
}
if(sql.indexOf("#{"+name+"}")==-1){
continue;
}
sql=sql.replace("#{"+name+"}", paramValue.toString());
}
statement.execute(sql);
} catch (Exception e) {
e.printStackTrace();
}
}
public void delete(String string, Object object) {
insert(string,object);
}
public void update(String string, Object object) {
insert(string,object);
}
@SuppressWarnings("unchecked")
public <T> T getMapper(LcSqlSession session,Class<T> clazz) {
ProxyHandler proxyHandler=new ProxyHandler(session);
return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, proxyHandler );
}
}
package com.lc.lcMybatis;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
public class LcSqlSessionFactory {
private String driver;
private String url;
private String username;
private String password;
private String modelPackage;
private Map<String, Map> mapInfo;
public String getModelPackage() {
return modelPackage;
}
public void setModelPackage(String modelPackage) {
this.modelPackage = modelPackage;
}
public Map<String, Map> getMapInfo() {
return mapInfo;
}
public void setMapInfo(Map<String, Map> mapInfo) {
this.mapInfo = mapInfo;
}
public String getDriver() {
return driver;
}
public void setDriver(String driver) {
this.driver = driver;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public LcSqlSession openSession() {
LcSqlSession lcSqlSession=new LcSqlSession();
try {
Class.forName(this.driver);
Connection connection = DriverManager.getConnection(this.url,this.username, this.password);
lcSqlSession.setConnection(connection);
lcSqlSession.setModelPackage(modelPackage);
lcSqlSession.setMapInfo(mapInfo);
} catch (Exception e) {
e.printStackTrace();
}
return lcSqlSession;
}
}
package com.lc.lcMybatis;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class LcSqlSessionFactoryBuilder {
public LcSqlSessionFactory build(InputStream inputStream) {
LcSqlSessionFactory lcSqlSessionFactory=new LcSqlSessionFactory();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
DocumentBuilder bulider;
try {
bulider = dbf.newDocumentBuilder();
Document doc = bulider.parse(inputStream);
XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
XPath xpath = factory.newXPath();
String modelPackage =getModelInfo(xpath,doc);
lcSqlSessionFactory.setModelPackage(modelPackage);
String resource =getMapperPath(xpath,doc);
Map<String, Map> mapInfo=getMapperInfo(resource);
lcSqlSessionFactory.setMapInfo(mapInfo);
//获取数据源的地址,用户名,密码
XPathExpression compile = xpath.compile("//dataSource");
NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
for(int i=0;i<nodes.getLength();i++) {
NodeList childNodes = nodes.item(i).getChildNodes(); //获取一个student节点所有的子节点,返回集合
//System.out.println(childNodes.getLength());
//遍历所有子节点,获取节点的名称与数据,将其存与Students对象的属性进行匹配并存入到该对象
for(int j=0;j<childNodes.getLength();j++) {
if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
continue;
}
NamedNodeMap arr = childNodes.item(j).getAttributes();
//System.out.println(arr.getLength());
for(int k=0;k<arr.getLength();k++) {
Node ar = arr.item(k);
//System.out.println(ar.getNodeName()+"="+ar.getTextContent());
if(ar.getNodeName().equals("driver")){
lcSqlSessionFactory.setDriver(ar.getTextContent());
}else if(ar.getNodeName().equals("url")){
lcSqlSessionFactory.setUrl(ar.getTextContent());
}else if(ar.getNodeName().equals("username")){
lcSqlSessionFactory.setUsername(ar.getTextContent());
}else if(ar.getNodeName().equals("password")){
lcSqlSessionFactory.setPassword(ar.getTextContent());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return lcSqlSessionFactory;
}
/**
* 获取model的包名
* @param xpath
* @param doc
* @return
*/
public static String getModelInfo(XPath xpath,Document doc){
String modelPackage = null;
//获取实体类
try {
XPathExpression compile = xpath.compile("//typeAliases");
NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
NodeList childNodes = nodes.item(0).getChildNodes();
for(int j=0;j<childNodes.getLength();j++) {
if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
continue;
}
NamedNodeMap arr = childNodes.item(j).getAttributes();
Node ar = arr.item(0);
//System.out.println(ar.getTextContent());
modelPackage=ar.getTextContent();
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return modelPackage;
}
/**
* 根据mappers获取mapper。xml路径
* @param xpath
* @param doc
* @return
*/
public static String getMapperPath(XPath xpath,Document doc){
String resource = null;
//获取实体类
try {
XPathExpression compile = xpath.compile("//mappers");
NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
NodeList childNodes = nodes.item(0).getChildNodes();
for(int j=0;j<childNodes.getLength();j++) {
if(childNodes.item(j).getNodeType() == Node.TEXT_NODE) {
continue;
}
NamedNodeMap arr = childNodes.item(j).getAttributes();
Node ar = arr.item(0);
//System.out.println(ar.getTextContent());
resource=ar.getTextContent();
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return resource;
}
/**
* 获取mapper。xml中的信息
* @param resource
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map getMapperInfo(String resource){
Map<String,Map> selectMapperInfo=new HashMap();
try {
String file = new Object() {
public String getPath() {
return this.getClass().getResource("/").getPath();
}
}.getPath().substring(1);
File f =new File(file+"/"+resource);
//创建基于文件的输入流
FileInputStream inputStream = new FileInputStream(f);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
DocumentBuilder bulider = dbf.newDocumentBuilder();
Document doc = bulider.parse(inputStream);
XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
XPath xpath = factory.newXPath();
String[] sqltypes={"//select","//insert","//delete","//update","//resultMap"};
for(String sqltype:sqltypes){
XPathExpression compile = xpath.compile(sqltype);
NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);
if(sqltype.equals("//resultMap")){
for (int index=0;index<nodes.getLength();index++) {
NamedNodeMap namedNodeMap = nodes.item(index).getAttributes();
Map map=new HashMap();
for(int i=0;i<namedNodeMap.getLength();i++){
map.put(namedNodeMap.item(i).getNodeName(),namedNodeMap.item(i).getNodeValue());
}
//map.put("sql",nodes.item(index).getTextContent().replace("\n", "").replace("\t", ""));
NodeList childNodes = nodes.item(index).getChildNodes();
for(int i=0;i<childNodes.getLength();i++){
if(childNodes.item(i).getNodeName().equals("id")){
Map idColumnMap=new HashMap();
NamedNodeMap idColumnMapnamedNodeMap = childNodes.item(i).getAttributes();
for(int idCmnindex=0;idCmnindex<idColumnMapnamedNodeMap.getLength();idCmnindex++){
if(idColumnMapnamedNodeMap.item(idCmnindex).getNodeName().equals("column")){
idColumnMap.put("column", idColumnMapnamedNodeMap.item(idCmnindex).getNodeValue());
}
if(idColumnMapnamedNodeMap.item(idCmnindex).getNodeName().equals("property")){
idColumnMap.put("property",idColumnMapnamedNodeMap.item(idCmnindex).getNodeValue());
}
}
map.put("idColumn",idColumnMap);
}
if(childNodes.item(i).getNodeName().equals("result")){ //33333333333
List resultColumns=new ArrayList();
Map resultColumnsMap1=new HashMap();
NamedNodeMap rcnnm = childNodes.item(i).getAttributes();
for(int rcnnmindex=0;rcnnmindex<rcnnm.getLength();rcnnmindex++){
if(rcnnm.item(rcnnmindex).getNodeName().equals("column")){
resultColumnsMap1.put("column", rcnnm.item(rcnnmindex).getNodeValue());
}
if(rcnnm.item(rcnnmindex).getNodeName().equals("property")){
resultColumnsMap1.put("property", rcnnm.item(rcnnmindex).getNodeValue());
}
resultColumns.add(resultColumnsMap1);
}
map.put("resultColumns",resultColumns);
}
if(childNodes.item(i).getNodeName().equals("collection")){
Map collectionMap=new HashMap();
NamedNodeMap ccmnm = childNodes.item(i).getAttributes();
for(int ccmnmindex=0;ccmnmindex<ccmnm.getLength();ccmnmindex++){
if(ccmnm.item(ccmnmindex).getNodeName().equals("property")){
collectionMap.put("property", ccmnm.item(ccmnmindex).getNodeValue());
}
if(ccmnm.item(ccmnmindex).getNodeName().equals("ofType")){
collectionMap.put("ofType", ccmnm.item(ccmnmindex).getNodeValue());
}
}
NodeList ccChildNodes =childNodes.item(i).getChildNodes();
for(int ccCnIndex=0;ccCnIndex<ccChildNodes.getLength();ccCnIndex++){
if(ccChildNodes.item(ccCnIndex).getNodeName().equals("id")){
Map collectionIdColumnMap=new HashMap();
NamedNodeMap idColumnMapnamedNodeMap = childNodes.item(i).getAttributes();
for(int idCmnindex=0;idCmnindex<idColumnMapnamedNodeMap.getLength();idCmnindex++){
if(idColumnMapnamedNodeMap.item(idCmnindex).getNodeName().equals("column")){
collectionIdColumnMap.put("column", idColumnMapnamedNodeMap.item(idCmnindex).getNodeValue());
}
if(idColumnMapnamedNodeMap.item(idCmnindex).getNodeName().equals("property")){
collectionIdColumnMap.put("property", idColumnMapnamedNodeMap.item(idCmnindex).getNodeValue());
}
collectionMap.put("idColumn",collectionIdColumnMap);
}
}
if(ccChildNodes.item(ccCnIndex).getNodeName().equals("result")){
List collectionResultColumns=new ArrayList();
Map collectionResultColumnsMap1=new HashMap();
/*collectionResultColumnsMap1.put("column", "cname");
collectionResultColumnsMap1.put("property", "name");
collectionResultColumns.add(collectionResultColumnsMap1);
collectionMap.put("resultColumns", collectionResultColumns);*/
NamedNodeMap rcnnm = ccChildNodes.item(ccCnIndex).getAttributes();
for(int rcnnmindex=0;rcnnmindex<rcnnm.getLength();rcnnmindex++){
if(rcnnm.item(rcnnmindex).getNodeName().equals("column")){
collectionResultColumnsMap1.put("column", rcnnm.item(rcnnmindex).getNodeValue());
}
if(rcnnm.item(rcnnmindex).getNodeName().equals("property")){
collectionResultColumnsMap1.put("property", rcnnm.item(rcnnmindex).getNodeValue());
}
collectionResultColumns.add(collectionResultColumnsMap1);
}
collectionMap.put("resultColumns", collectionResultColumns);
}
}
map.put("collection", collectionMap);
}
}
selectMapperInfo.put( namedNodeMap.item(0).getTextContent(),map);
}
continue;
}
for (int index=0;index<nodes.getLength();index++) {
NamedNodeMap namedNodeMap = nodes.item(index).getAttributes();
Map<String,String> map=new HashMap();
for(int i=0;i<namedNodeMap.getLength();i++){
map.put(namedNodeMap.item(i).getNodeName(),namedNodeMap.item(i).getNodeValue());
}
map.put("sql",nodes.item(index).getTextContent().replace("\n", "").replace("\t", ""));
selectMapperInfo.put( namedNodeMap.item(0).getTextContent(),map);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return selectMapperInfo;
}
}
package com.lc.lcMybatis;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class ProxyHandler implements InvocationHandler{
public LcSqlSession sqlSession;
public ProxyHandler(LcSqlSession sqlSession) {
this.sqlSession = sqlSession;
}
@SuppressWarnings({ "rawtypes" })
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName=method.getName();
if(methodName.indexOf("add")!=-1){
sqlSession.insert(methodName, args[0]);
}else if(methodName.indexOf("list")!=-1){
List list=sqlSession.selectList(methodName);
return list;
}else if(methodName.indexOf("get")!=-1){
Object object=sqlSession.selectOne(methodName,(int) args[0]);
return object;
}else if(methodName.indexOf("update")!=-1){
sqlSession.update(methodName,args[0]);
}else if(methodName.indexOf("delete")!=-1){
sqlSession.update(methodName,args[0]);
}
return null;
}
}
2. lcspring核心类
package org.lcframework;
import java.util.HashMap;
import java.util.Map;
public class LcModelAndView {
private String responsePage;
private Map map=new HashMap();
public String getResponsePage() {
return responsePage;
}
public void setResponsePage(String responsePage) {
this.responsePage = responsePage;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public LcModelAndView(String responsePage) {
this.responsePage=responsePage;
}
public void addObject(String key, Object value) {
map.put(key, value);
}
}
package org.lcframework;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.lcframework.annotation.LcAutowired;
import org.lcframework.annotation.LcComponent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.lcframework.annotation.LcController;
import org.lcframework.annotation.LcRequestMapping;
public class LcSpring {
public static void main(String[] args) {
LcSpring lcSpring=new LcSpring();
System.out.println(lcSpring.getBean("urlmaping"));
}
/**
* 根据id获取bean
* @param id
* @return
*/
public Object getBean(String id) {
String classname = "";
Object object = null;
Map map = new HashMap();
try {
String file = new File(this.getClass().getResource("/").getPath()).toString();
System.out.println(file.toString());
String WEBINFPath=file.substring(0, file.indexOf("classes"));
System.out.println(WEBINFPath);
File inputFile = new File(WEBINFPath+"springmvc-servlet.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
String nameString = doc.getFirstChild().getNodeName();
if (!nameString.equals("LcSpring")) {
throw new Exception("未发现LcSpring");
}
//读取xml,看是否扫描包来通过注解加载bean
NodeList lcAnnotationScan = doc.getElementsByTagName("lcAnnotationScan");
if(lcAnnotationScan.getLength()!=0){
Element element = (Element)lcAnnotationScan.item(0);
String packageName = element.getAttribute("package");
//System.out.println("扫描"+packageName);
List classList=this.getClasses(packageName);
Map<String, Map<String,Object>> urlmaping=new HashMap();
for (Object clazz : classList) {
LcController lcController=(LcController) ((Class)clazz).getAnnotation(LcController.class);
if(lcController!=null){
try {
object = ((Class)clazz).getConstructor().newInstance();
List list=getMethodByAnnotation((Class)clazz,LcRequestMapping.class);
for (Object methodObject : list) {
LcRequestMapping lcRequestMapping=((Method)methodObject).getAnnotation(LcRequestMapping.class);
String requestUrl=lcRequestMapping.value();
Map urlHandleMap=new HashMap();
urlHandleMap.put("requestClass", clazz);
urlHandleMap.put("requestMethod", methodObject);
urlmaping.put(requestUrl, urlHandleMap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
LcComponent lcComponent=(LcComponent) ((Class)clazz).getAnnotation(LcComponent.class);
if(lcComponent!=null && "student".equals(lcComponent.value())){
System.out.println(clazz+"是");
List list=getFieldByAnnotation((Class)clazz,LcAutowired.class);
for (Object fieldobject : list) {
Object annoObject=getBeanByClassName(((Field)fieldobject).getType().getName());
if(annoObject==null){
annoObject=Class.forName(((Field)fieldobject).getType().getName()).getConstructor().newInstance();
}
map.put(((Field)fieldobject).getName(),annoObject);
}
try {
object = ((Class)clazz).getConstructor().newInstance();
object = setValue(object, map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if(id.equals("urlmaping")){
return urlmaping;
}
return object;
}
//不通过注解,使用xml配置加载bean
NodeList nodeList = doc.getElementsByTagName("bean");
for (int i = 0; i < nodeList.getLength(); i++) {
//获得一级子元素
Element element = (Element)nodeList.item(i);
//获得属性
String beanid = element.getAttribute("id");
//获得元素的值
//String name = element.getFirstChild().getNodeValue();
if(id.equals(beanid)){
classname = element.getAttribute("classname");
NodeList propertyNodeList = element.getElementsByTagName("property");
for (int j = 0;j < propertyNodeList.getLength(); j++) {
String ref = ((Element) propertyNodeList.item(j)).getAttribute("ref");
String mapstr = ((Element) propertyNodeList.item(j)).getAttribute("map");
Object value = "";
if (ref.equals("true")) {
value = getBean(propertyNodeList.item(j).getTextContent());
}else if(mapstr.equals("true")){
NodeList mapnodeList =((Element) propertyNodeList.item(j)).getElementsByTagName("prop");
Map urlmaping=new HashMap();
for (int k = 0; k < mapnodeList.getLength(); k++) {
//获得一级子元素
System.out.println(((Element) mapnodeList.item(i)).getAttribute("key"));
System.out.println(((Element) mapnodeList.item(i)).getTextContent());
urlmaping.put(((Element) mapnodeList.item(i)).getAttribute("key"), ((Element) mapnodeList.item(i)).getTextContent());
}
return urlmaping;
}else {
value = propertyNodeList.item(j).getTextContent();
}
String property = ((Element) propertyNodeList.item(j)).getAttribute("name");
map.put(property, value);
}
List list=getFieldByAnnotation(Class.forName(classname),LcAutowired.class);
for (Object fieldobject : list) {
Object annoObject=getBeanByClassName(((Field)fieldobject).getType().getName());
map.put(((Field)fieldobject).getName(),annoObject);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
object = Class.forName(classname).getConstructor().newInstance();
object = setValue(object, map);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
public Object setValue(Object object, Map map) {
try {
for (Object key : map.keySet()) {
Object value = map.get(key);
Field f1 = object.getClass().getDeclaredField((String) key);
f1.setAccessible(true);
String type = f1.getType().toString();// 得到此属性的类型
if (type.endsWith("int") || type.endsWith("Integer")) {
f1.set(object, Integer.parseInt((String) value));
} else {
f1.set(object, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
/**
* 查找类的所有属性是否含有某注解
* @param objClazz 类对象
* @param annoClazz 注解类对象
* @return 含有该注解的属性列表
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public List getFieldByAnnotation(Class objClazz,Class annoClazz){
Field[] fields =objClazz.getDeclaredFields();
List list=new ArrayList();
for (Field field : fields) {
if(field.getAnnotation(annoClazz)!=null){
list.add(field);
}
}
return list;
}
public List getMethodByAnnotation(Class objClazz,Class annoClazz){
Method[] methods=objClazz.getMethods();
List list=new ArrayList();
for (Method method : methods) {
if(method.getAnnotation(annoClazz)!=null){
list.add(method);
}
}
return list;
}
/**
* 通过类全名查找生成类对象
* @param className
* @return
*/
public Object getBeanByClassName(String className){
File inputFile = new File("LcSpring4.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
Document doc =null;
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
String nameString = doc.getFirstChild().getNodeName();
if (!nameString.equals("LcSpring")) {
throw new Exception("未发现LcSpring");
}
} catch (Exception e) {
e.printStackTrace();
}
//加载xml配置的bean
NodeList nodeList = doc.getElementsByTagName("bean");
for (int i = 0; i < nodeList.getLength(); i++) {
//获得一级子元素
Element element = (Element)nodeList.item(i);
//获得属性
String classname = element.getAttribute("classname");
if(classname.equals(className)){
String id=element.getAttribute("id");
Object object=getBean(id);
return object;
}
}
return null;
}
/**
* 从包package中获取所有的Class
*
* @param pack
* @return
*/
private List<Class<?>> getClasses(String packageName) {
// 第一个class类的集合
List<Class<?>> classes = new ArrayList<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection()).getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx).replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class") && !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(packageName.length() + 1, name.length() - 6);
try {
// 添加到classes
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
private void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, List<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0, file.getName().length() - 6);
try {
// 添加到集合中去
classes.add(Class.forName(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
package org.lcframework;
import java.beans.Introspector;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LcSpringmvc extends HttpServlet{
public static void main(String[] args) {
String webname="/pp";
String weburi="/pp/index";
System.out.println(weburi.replace(webname, ""));
/* LcSpring lcSpring=new LcSpring();
Map map=(Map) lcSpring.getBean("urlmaping");
System.out.println(map);
lcSpring.getBean("indexController");
IndexControllerOld controllerObject=(IndexControllerOld) lcSpring.getBean((String) map.get("/index"));
System.out.println(controllerObject.handleRequest());*/
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void service(HttpServletRequest request, HttpServletResponse response){
/* Map<String, String[]> parameters = request.getParameterMap();
Set<String> paramNames = parameters.keySet();
for (String param : paramNames) {
String[] value = parameters.get(param);
System.out.println(param + ":" + Arrays.asList(value));
}*/
try {
System.out.println("进入LcSpringmvc");
String requestURI=request.getRequestURI();
String contextPath= request.getContextPath();
requestURI=requestURI.replace(contextPath, "");
System.out.println(requestURI);
LcSpring lcSpring=new LcSpring();
Map<String, Map<String,Object>> map=(Map<String, Map<String,Object>>) lcSpring.getBean("urlmaping");
//LcController controllerObject=(LcController) lcSpring.getBean((String) map.get(requestURI));
Map urlHandleMap=map.get(requestURI);
Class requestClass=(Class) urlHandleMap.get("requestClass");
Method requestMethod=(Method) urlHandleMap.get("requestMethod");
Object controllerObject= ((Class)requestClass).getConstructor().newInstance();
response.setContentType("text/html; charset=UTF-8");
/*Class<?>[] getTypeParameters = requestMethod.getParameterTypes();
if(getTypeParameters.length==0){
System.out.println("此方法无参数");
}
for (Class<?> class1 : getTypeParameters) {
String parameterName = class1.getName();
System.out.println("参数类型:"+parameterName);
}*/
Map<String, String[]> parameters = request.getParameterMap();
List invokeargs=new ArrayList();
Class<?>[] getTypeParameters = requestMethod.getParameterTypes();
for (Class<?> class1 : getTypeParameters) {
Object object = class1.getConstructor().newInstance();
object = setValue(object, parameters);
invokeargs.add(object);
}
LcModelAndView lcModelAndView=(LcModelAndView) requestMethod.invoke(controllerObject,invokeargs.toArray() );
// LcModelAndView lcModelAndView=(LcModelAndView)runMethod(requestMethod,controllerObject,argsArr);
// for (Class<?> class1 : getTypeParameters) {
// //Object object = class1.getConstructor().newInstance();
// //object = setValue(object, parameters);
// Object object =invokeargs.get(0);
// lcModelAndView.addObject("product", object);
// }
for (int i=0;i<getTypeParameters.length;i++) {
Object object =invokeargs.get(i);
String paramname=Introspector.decapitalize(getTypeParameters[i].getSimpleName());
lcModelAndView.addObject(paramname, object);
}
Map responseMap=lcModelAndView.getMap();
for (Object key : responseMap.keySet()) {
System.out.println("key = " + key);
request.setAttribute((String) key, responseMap.get(key));
}
request.getRequestDispatcher(lcModelAndView.getResponsePage()).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object setValue(Object object, Map map) {
try {
for (Object key : map.keySet()) {
Object[] value = (Object[]) map.get(key);
Field f1 = object.getClass().getDeclaredField((String) key);
f1.setAccessible(true);
String type = f1.getType().toString();// 得到此属性的类型
if (type.endsWith("int") || type.endsWith("Integer")) {
f1.set(object, Integer.parseInt((String) value[0]));
} else if (type.endsWith("float") || type.endsWith("Float")) {
f1.set(object, Float.parseFloat((String) value[0]));
}else if(type.endsWith("List")){
f1.set(object, Arrays.asList(value));
}else{
f1.set(object, value[0]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
}
3.注解
package org.lcframework.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LcAutowired {
}
package org.lcframework.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LcComponent {
String value();
}
package org.lcframework.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LcController {
}
package org.lcframework.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface LcRequestMapping {
String value();
}
测试
controller
package controller;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import org.lcframework.LcModelAndView;
import org.lcframework.annotation.LcController;
import org.lcframework.annotation.LcRequestMapping;
import com.lc.lcMybatis.LcResources;
import com.lc.lcMybatis.LcSqlSession;
import com.lc.lcMybatis.LcSqlSessionFactory;
import com.lc.lcMybatis.LcSqlSessionFactoryBuilder;
import dao.ProductDao;
import pojo.Product;
@LcController
public class TestSubmitController{
@LcRequestMapping("/addProduct")
public LcModelAndView add(Product product) throws Exception {
String resource = "Lcmybatis-config.xml";
InputStream inputStream = LcResources.getResourceAsStream(resource);
LcSqlSessionFactory sqlSessionFactory = new LcSqlSessionFactoryBuilder().build(inputStream);
LcSqlSession session=sqlSessionFactory.openSession();
ProductDao productDao=session.getMapper(session,ProductDao.class);
productDao.addProduct(product);
List<Product> listProduct = productDao.listProduct();
System.out.println(listProduct);
LcModelAndView mav = new LcModelAndView("listProduct.jsp");
mav.addObject("cs", listProduct);
return mav;
}
}
dao
package dao;
import java.util.List;
import pojo.Product;
public interface ProductDao {
public List<Product> listProduct();
public void addProduct(Product Product);
public Product getProduct(Integer id);
public void updateProduct(Product Product);
public void deleteProduct(Product Product);
}
xml
<mapper>
<select id="listProduct" resultType="Product">
select * from product_
</select>
<insert id="addProduct">
insert into product_ ( id,name,price ) values (#{id},#{name},#{price})
</insert>
<delete id="deleteProduct">
delete from product_ where id= #{id}
</delete>
<select id="getProduct" resultType="Product">
select * from product_ where id= #{id}
</select>
<update id="updateProduct">
update product_ set name=#{name} where id=#{id}
</update>
</mapper>
pojo
package pojo;
public class Product {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
lcmybatis配置文件
<configuration>
<typeAliases>
<package name="pojo"/>
</typeAliases>
<dataSource type="POOLED">
<property driver="com.mysql.jdbc.Driver"/>
<property url="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/>
<property username="root"/>
<property password="root"/>
</dataSource>
<mappers>
<mapper resource="dao/ProductDaoMapper.xml"/>
</mappers>
</configuration>
lcspring配置文件
<LcSpring>
<!-- <bean id="urlmaping">
<property name="mappings" map="true">
<prop key="/index">indexController</prop>
</property>
</bean>
<bean id="indexController" classname="controller.IndexController"></bean> -->
<lcAnnotationScan package="controller"/>
</LcSpring>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>LcSpringmvc</servlet-name>
<servlet-class>org.lcframework.LcSpringmvc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LcSpringmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
addProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*" isELIgnored="false"%>
<form action="addProduct">
产品名称 :<input type="text" name="name" value=""><br />
产品价格: <input type="text" name="price" value=""><br />
<input type="submit" value="增加商品">
</form>
listProduct.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table align='center' border='1' cellspacing='0'>
<tr>
<td>id</td>
<td>name</td>
<td>price</td>
</tr>
<c:forEach items="${cs}" var="c" varStatus="st">
<tr>
<td>${c.id}</td>
<td>${c.name}</td>
<td>${c.price}</td>
</tr>
</c:forEach>
</table>
http://127.0.0.1/Lcssm/addProduct.jsp进入增加页面,提交后跳转到展示页