xuchen-mvc相關類

package org.mvc.framework.utils;javascript

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;css

public class ContextPathUtil {
    public static List<String> splitContextPath(String contextPath) {
        if (null == contextPath || "".equals(contextPath)) return null;
        List<String> pathlist = Arrays.asList(contextPath.trim().split(","));
        List<String> destlist =new ArrayList<String>();
        pathlist.stream().forEach(path -> {
            String destPath = path.replace(" ", "").trim();
            if (destPath.indexOf("classpath*:/") != -1) {
                destlist.add(destPath.substring(destPath.indexOf("/") + 1).trim());
            } else if (destPath.indexOf("classpath:/") != -1) {
                destlist.add(destPath.substring(destPath.indexOf("/") + 1).trim());
            } else if (destPath.indexOf("classpath*:") != -1) {
                destlist.add(destPath.substring(destPath.indexOf("*:") + 1).trim());
            } else if (destPath.indexOf("classpath:") != -1) {
                destlist.add(destPath.substring(destPath.indexOf(":") + 1).trim());
            }
        });
        return destlist;
    }
}
-------------------------------------------------------------------------------------html

package org.mvc.framework.utils;java

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;node

public class StringCaseUtil {
    @SuppressWarnings("deprecation")
    public static String urlChinseEncode(String enCodeValue) {
        return URLDecoder.decode(enCodeValue);
    }
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }
    
    /**
     * 首字母小寫
     * @return
     */
    public static String lowerFirstCase (String claxxName) {
        char[] chars = claxxName.toCharArray();
        chars[0] = (char) (chars[0] + 32);
        return String.valueOf(chars);
    }
    
    public static String upperFirstCase (String claxxName) {
        char[] chars = claxxName.toCharArray();
        chars[0] = (char) (chars[0] - 32);
        return String.valueOf(chars);
    }
    
    public static String getParameterValue(String bufferParam, String paramName) {
        if (StringUtils.isEmpty(bufferParam)) return null;
        String[] parameters = bufferParam.split("&");
        for(String parameter : parameters) {
            String valueParam[] = parameter.split("=");
            if (null != valueParam && valueParam.length>=2) {
                if(paramName.equals(valueParam[0])) {
                    return valueParam[1];
                }
            }
        }
        return null;
    }
    
    public static Map<String, Object> queryParam2Map(String bufferParam) {
        if (StringUtils.isEmpty(bufferParam)) return null;
        Map<String, Object> convertMap = new HashMap<>();
        List<String> params = Arrays.asList(bufferParam.split("&"));
        if (null == params || params.isEmpty()) return null;
        params.stream().forEach((value) -> {
            String[] keyValues = value.split("=");
            if (null != keyValues && keyValues.length >= 2) {
                convertMap.put(keyValues[0], keyValues[1]);
            }
        });
        return convertMap;
    }
    
    /** 
     * 判斷字符串是否爲亂碼並返回 
     * @param msg 傳入亂碼字符串 
     * @return 返回轉換後的漢字數據 
     */  
    public static String toChinese(String msg) {  
        if (isMessyCode(msg)) {  
            try {  
                return new String(msg.getBytes("ISO8859-1"), "UTF-8");  
            } catch (Exception e) {}  
        }  
        return msg;  
    }  
    
    public static boolean isMessyCode(String strName) {  
        Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");  
        Matcher m = p.matcher(strName);  
        String after = m.replaceAll("");  
        String temp = after.replaceAll("\\p{P}", "");  
        char[] ch = temp.trim().toCharArray();  
        float chLength = 0;  
        float count = 0;  
        for (int i = 0; i < ch.length; i++) {  
            char c = ch[i];  
            if (!Character.isLetterOrDigit(c)) {  
                if (!isChinese(c))  count = count + 1;  
                chLength++;  
            }  
        }  
        float result = count / chLength;  
        if (result > 0.4) return true;
        else return false;  
    }  
    
    private static boolean isChinese(char c) {  
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);  
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS  
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A  
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION  
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION  
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {  
            return true;  
        }  
        return false;  
    }
    
    public static byte[] HexStringToBytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }jquery

    private static int parse(char c) {
        if (c >= 'a') return (c - 'a' + 10) & 0x0f;
        if (c >= 'A') return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }
    
    public static void main(String[] args) {
        String hexStr = "B2A9C2EDC5ACCDDFB7FECACEC9CCC3B328C9CFBA";
         byte[] by = HexStringToBytes(hexStr );
         try {
            String store_name  = new String(by,"GB2312"); 
            System.out.println(store_name);
            System.out.println(urlChinseEncode("%E9%83%AD%E8%8D%A3%E9%9D%99"));
        } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }
}
-------------------------------------------------------------------------------------------git

package org.mvc.framework.utils;ajax

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;spring

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.mvc.framework.constant.CommonConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;apache

public class XmlUtils {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);
    
    @SuppressWarnings("unchecked")
    public static Map<String, Element> dealWithXml(ClassLoader loader,
            String xmlPath, String scanProperties) {
        Map<String, Element> xmlBeanMap = new HashMap<String, Element>();
        Document document = null;
        SAXReader render = new SAXReader();
        System.out.println("[INFO ] XmlUtils render xml " + xmlPath);
        InputStream in = loader.getResourceAsStream(xmlPath);
        if (null == in) {
            logger.info("XmlUtils render xml, but not find mvc-servlet.xml");
            throw new RuntimeException("XmlUtils render xml, but not find mvc-servlet.xml");
        }
        try {
            document = render.read(in);
            Element root = document.getRootElement();
            Iterator<Element> iterator = root.elementIterator();
            while (iterator.hasNext()) {
                Element el = iterator.next();
                String elName = el.getName();
                if (el.attributes().isEmpty() || null == el.attribute(CommonConstant.XML_BEAN_ID_ELEMENT_NAME)){
                    xmlBeanMap.put(elName, el);
                } else {
                    Attribute attribute = el.attribute("id");
                    if (null == attribute || "".equals(attribute.getText())) {
                        throw new RuntimeException("render xml exception bean attribute id canot be empty or null.");
                    }
                    xmlBeanMap.put(elName + "::" + attribute.getText(), el);
                }
            }
        } catch (DocumentException e) {
            logger.error("read xml file exception {}" , e);
            e.printStackTrace();
        }
        return xmlBeanMap;
    }
    
    @SuppressWarnings({ "unchecked", "unused" })
    private void selectNodeByName (String xmlPath, String scanProperties) {
        try {
            Document document = null;
            SAXReader render = new SAXReader();
            System.out.println(this.getClass().getName() + "{}" + xmlPath);
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(xmlPath);
            if (null == inputStream) {
                System.out.println(this.getClass().getName() + " not find springmvc-servlet.xml");
                return;
            }
            document = render.read(inputStream);
            String xmlPacakScanPath = "//context-package-scan";
            List<Element> nodelist = document.selectNodes(xmlPacakScanPath);
            for (Element element : nodelist) {
                Object packageName = element.getData();
            }
        } catch (Exception e) {
            logger.error("read xml file exception {}" , e);
            e.printStackTrace();
        }
    }
}
---------------------------------------------------------------------------------

package org.mvc.framework.handler;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;

import org.apache.commons.lang3.StringUtils;
import org.mvc.framework.annotation.XCautowired;
import org.mvc.framework.annotation.XCrequestMapping;
import org.mvc.framework.constant.CommonConstant;
import org.mvc.framework.entity.InnerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class ClassReflectHandler {
    private static final Logger logger = LoggerFactory.getLogger(ClassReflectHandler.class);
    public static ClassLoader getClassLoader() {
        try {
            return Thread.currentThread().getClass().getClassLoader();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void doBeanDiInstation(Entry<String, Object> entry, Class<?> claxx,
             Map<String, Object> iocBeanMap) throws IllegalAccessException {
        // 經過反射進行實例注入
        Field[] fields = claxx.getDeclaredFields();
        if (null == fields || fields.length <= 0) return;
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.isAnnotationPresent(XCautowired.class)) {
                System.out.println("[INFO ] " + claxx.getName() + " bean di -----------");
                String diBeanName = field.getAnnotation(XCautowired.class).value();
                if (StringUtils.isEmpty(diBeanName)) {
                    diBeanName = field.getName();
                }
                Object instance = iocBeanMap.get(diBeanName);
                field.set(entry.getValue(), instance);
            }
        }
    }
    
    public static void doBeanHandlerMapping(Class<?> clazz, Map<String, InnerHandler> handlerMapper) {
        Method[] methods = clazz.getDeclaredMethods();
        if (null == methods || methods.length <= 0) return;
        String basePath = clazz.getAnnotation(XCrequestMapping.class).value();
        for (Method method : methods) {
            String handlerUrl = "";
            method.setAccessible(true);
            if (method.isAnnotationPresent(XCrequestMapping.class)) {
                InnerHandler innerHandler = new InnerHandler();
                String methodPath = method.getAnnotation(XCrequestMapping.class).value();
                handlerUrl = (basePath + "/" + methodPath).replaceAll("\\*", "").replaceAll("/+", "/");
                String[] methodParamNames = methodParameterName(clazz, method.getName());
                Class<?>[] methodParameterTypes = method.getParameterTypes();
                
                innerHandler.setMethod(method);
                innerHandler.setMethodClass(clazz);
                innerHandler.setMethodParameterTypes(methodParameterTypes);
                innerHandler.setParameterAnnotations(method.getParameterAnnotations());
                innerHandler.setMethodParameterNames(Arrays.asList(methodParamNames));  
                handlerMapper.put(handlerUrl, innerHandler);
            }
        }
    }
    
    private static String[] methodParameterName(Class<?> clazz, String methodName) {
        String nameParams[] = null;
        try {
            ClassPool classPool = ClassPool.getDefault();
            classPool.insertClassPath(new ClassClassPath(clazz));
            CtClass ctClass = classPool.get(clazz.getName());
            CtMethod ctMethod = ctClass.getDeclaredMethod(methodName);
            MethodInfo methodInfo = ctMethod.getMethodInfo();
            CodeAttribute attribute = methodInfo.getCodeAttribute();
            LocalVariableAttribute lAttribute = (LocalVariableAttribute) attribute.getAttribute(LocalVariableAttribute.tag);
            if (null == lAttribute) {
                throw new RuntimeException("500 get parameter");
            }
            nameParams = new String[ctMethod.getParameterTypes().length];
            int pos = Modifier.isStatic(ctMethod.getModifiers())?0 : 1;
            for (int i=0; i< nameParams.length; i++) {
                nameParams[i] = lAttribute.variableName(i + pos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return nameParams;
    }
    
    public static Object invokeMethodParamValue(Class<?> paramType, String paramValue) {
        System.out.println("[INFO ] start convert request parameter." + JSON.toJSONString(paramType));
        try {
            if (paramType == String.class) {
                return paramValue;
            } else if (paramType == Integer.class || paramType == int.class) {
                return Integer.valueOf(paramValue);
            } else if (paramType == Long.class || paramType == long.class) {
                return Long.valueOf(paramValue);
            } else if (paramType == Boolean.class || paramType == boolean.class) {
                return Boolean.valueOf(paramValue);
            } else if (paramType == Short.class || paramType == short.class) {
                return Short.valueOf(paramValue);
            } else if (paramType == Float.class || paramType == float.class) {
                return Float.valueOf(paramValue);
            } else if (paramType == Double.class || paramType == double.class) {
                return Double.valueOf(paramValue);
            } else if (paramType == BigDecimal.class) {
                return new BigDecimal(paramValue);
            } else if (paramType == Character.class || paramType == char.class) {
                char[] cs = paramValue.toCharArray();
                if (cs.length > 1) {
                    throw new IllegalArgumentException("參數長度太大");
                }
                return paramValue;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
     /**
     * 加載類
     * @param name
     * @param initialize
     * @param loader
     * @return
     */
    public static Class<?> loadClass (String name, boolean initialize) {
        Class<?> cls = null;
        try {
            cls = Class.forName(name, initialize, getClassLoader());
        } catch (ClassNotFoundException e) {
            logger.error("load class failure" , e);
            throw new RuntimeException(e);
        }
        return cls;
    }
    
    public static Set<Class<?>> getClassSet (String packageName) {
        Set<Class<?>> classeSet = new HashSet<Class<?>>();
        try {
            Enumeration<URL> urls = getClassLoader().getResources(packageName.replace(".", "/"));
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();
                if (null != url) {
                    String protocol = url.getProtocol();
                    if (CommonConstant.PACKAGE_PROTOCOL_FILE.equals(protocol)) {
                        String packagePath = url.getPath().replaceAll("%20", "");
                        addClass(classeSet, packagePath, packageName);
                    } else if (CommonConstant.PACKAGE_PROTOCOL_JAR.equals(protocol)) {
                        JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                        if (null != jarURLConnection) {
                            JarFile jarFile = jarURLConnection.getJarFile();
                            if (null != jarFile) {
                                Enumeration<JarEntry> jarEntries = jarFile.entries();
                                while (jarEntries.hasMoreElements()) {
                                    JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
                                    String jarEntryName = jarEntry.getName();
                                    if (jarEntryName.endsWith(".class")) {
                                        String className = jarEntryName.substring(0, jarEntryName.lastIndexOf(".")).replaceAll("/", ".");
                                        doAddClass(classeSet, className);
                                    }
                                }
                            }
                        }
                        
                    }
                }
            }
            
            
        } catch (Exception e) {
            logger.error("[ERROR ] load class set exception", e);
            throw new RuntimeException(e);
        }
        return classeSet;
    }
    
    public static void setClass(Set<Class<?>> clazz_set, String path, String packagePath) {
        File[] files = new File(path).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
            }
        });
        
        for (File file : files) {
            String filename = file.getName();
            if (file.isFile()) {
                String className = packagePath + "." + filename.substring(0, filename.lastIndexOf("."));
                System.out.println(className);
                Class<?> clazz = loadClass(className, false);
                clazz_set.add(clazz);
            } else {
                setClass(clazz_set, path + "/" + filename, packagePath);
            }
        }
    }
    
    public static void addClass(Set<Class<?>> classSet, String packagePath, String packageName) {
        File[] files = new File(packagePath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
            }
        });
        
        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile()) {
                String className = fileName.substring(0, fileName.lastIndexOf("."));
                if (StringUtils.isNotEmpty(packageName)) {
                    className = packageName + "." + className;
                    System.out.println(className);
                    doAddClass(classSet, className);
                }
            } else {
                String subPacakgeName = packageName + "." + fileName;
                String subPacakge = packagePath + "/" + fileName;
                addClass(classSet, subPacakge , subPacakgeName);
            }
        }
    }
    
    public static void doAddClass (Set<Class<?>> classSet, String className) {
        Class<?> cls = loadClass(className, false);
        classSet.add(cls);
    }
}
-----------------------------------------------------------------------------------------

package org.mvc.framework.handler;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.dom4j.Element;
import org.mvc.framework.constant.CommonConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class XmlBeanHandler {
    private static final Logger logger = LoggerFactory.getLogger(XmlBeanHandler.class);
    
    public static void initXmlBean(Map<String, Element> xmlMap, Map<String, Object> iocBean,
            Properties properties) {
        System.out.println("[INFO ] XmlBeanHandler start init bean ...");
        if (null == xmlMap || xmlMap.isEmpty()) return;
        try {
            for (Entry<String, Element> entry : xmlMap.entrySet()) {
                String elName = entry.getKey();
                Element xmlElement = entry.getValue();
                String xmlAttrName = xmlElement.getName(); 
                // 把自定義的bean,直接放入 ioc 容器
                if (CommonConstant.XML_BEAN_ELEMENT_NAME.equals(xmlAttrName)) {
                    String className = xmlElement.attribute("class").getText().trim();
                    Class<?> beanClazz = Class.forName(className);
                    iocBean.put(elName.substring(elName.indexOf("::") + 2), beanClazz.newInstance());
                } else {
                    // 獲取掃描包的路徑
                    if (CommonConstant.XML_CONTEXT_SCAN_PACAKAGE.equals(elName)) {
                        properties.setProperty(elName, xmlElement.getTextTrim());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("[ERROR ] XmlBeanHandler initalize bean exception", e);
            e.printStackTrace();
        }
    }
    
}
--------------------------------------------------------------------------------------

package org.mvc.framework.entity;

import java.util.Collection;
import java.util.Map;

public interface Model {
    Model addAttribute(String attribureName, Object attibuteValue);
    Model addAttribute(Object attributeValue);
    Model addAllAttributes(Collection<?> attributeValues);
    Model addAllAttributes(Map<String, ?> attributes);
    boolean containsAttribute(String attributeName);
    Map<String, Object> asMap();
}
----------------------------------------------------------------------------

package org.mvc.framework.entity;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("serial")
public class ModelMap extends HashMap<String, Object> implements Model {

    @Override
    public Model addAttribute(String attribureName, Object attibuteValue) {
        put(attribureName, attibuteValue);
        return this;
    }

    @Override
    public Model addAttribute(Object attributeValue) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Model addAllAttributes(Collection<?> attributeValues) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Model addAllAttributes(Map<String, ?> attributes) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean containsAttribute(String attributeName) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Map<String, Object> asMap() {
        // TODO Auto-generated method stub
        return null;
    }

}
---------------------------------------------------------------------------------

package org.mvc.framework.entity;

public class User {
    private Long userId;
    private String mobile;
    private String userName;
    private String password;
    private String address;
    
    public Long getUserId() {
        return userId;
    }
    public void setUserId(Long userId) {
        this.userId = userId;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    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 String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("User [userId=");
        builder.append(userId);
        builder.append(", mobile=");
        builder.append(mobile);
        builder.append(", userName=");
        builder.append(userName);
        builder.append(", password=");
        builder.append(password);
        builder.append(", address=");
        builder.append(address);
        builder.append("]");
        return builder.toString();
    }
}
------------------------------------------------------------------------------------

package org.mvc.framework.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.mvc.framework.annotation.XCautowired;
import org.mvc.framework.annotation.XCcontroller;
import org.mvc.framework.annotation.XCrequestMapping;
import org.mvc.framework.annotation.XCrequestMethod;
import org.mvc.framework.annotation.XCrequestParam;
import org.mvc.framework.annotation.XCresponseBody;
import org.mvc.framework.entity.Model;
import org.mvc.framework.entity.User;
import org.mvc.framework.service.HelloService;
import org.mvc.framework.view.XCView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@XCcontroller
@XCrequestMapping(value = "/system/*")
public class PassportController {
    
    private static final Logger logger = LoggerFactory.getLogger(PassportController.class);
    
    @XCautowired
    private HelloService helloService;
    
    @XCresponseBody
    @XCrequestMapping(value = "validateUser.do", method = XCrequestMethod.POST)
    public JSONObject ValidateUser(HttpServletRequest request, User user, String email) {
        System.out.println("[INFO ] " + JSON.toJSONString(user) + " email:" + email);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", 1995804l);
        jsonObject.put("userName", "童蕾");
        jsonObject.put("user", user);
        jsonObject.put("email", email);
        return jsonObject;
    }
    
    @XCrequestMapping(value = "homde.do", method = XCrequestMethod.GET)
    public String homePage (HttpServletRequest request, Model model) {
        model.addAttribute("currentTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        return "system/login.jsp";
    }
    
    @XCrequestMapping(value = "loginIn.do", method = XCrequestMethod.GET)
    public XCView loginIn(@XCrequestParam("userName") String userName, String age, Model model) {
        logger.info("[INFO ] PassportController login page {},{}" , userName, age);
        
        XCView view = new XCView("index.jsp");
        view.setPath("index.jsp");
        
        model.addAttribute("userName", userName);
        model.addAttribute("age", age);
        
        
        Map<String, Object> modelO = new HashMap<>();
        modelO.put("name", userName);
        
        User user = new User();
        user.setUserId(109870l);
        user.setUserName("趙雄");
        user.setAddress("上海寶山區");
        user.setMobile("15897566210");
        user.setPassword("123456");
        
        User user1 = new User();
        user1.setUserId(201260l);
        user1.setUserName("周國民");
        user1.setAddress("上海浦東新區新蔭派");
        user1.setMobile("18957210566");
        user1.setPassword("123456");
        
        List<User> ulist = new ArrayList<>();
        ulist.add(user);
        ulist.add(user1);
//        modelO.put("ulist", ulist);
        model.addAttribute("ulist", ulist);
        view.addModel(modelO);
        return view;
    }
}
--------------------------------------------------------------

package org.mvc.framework.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface XCresponseBody {

}
----------------------------------------------------------

package org.mvc.framework.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface XCrequestMapping {

    String value() default "";
    XCrequestMethod[] method() default {};
    String[] params() default {};
}
--------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- 設定頁面使用的字符集。 -->
<meta http-equiv="content-Type" content="text/html;charset=UTF-8">
<!-- 若是網頁過時,那麼存盤的cookie將被刪除 -->
<meta http-equiv="Set-Cookie" content="cookievalue=xxx;expires=Friday, 12-Jan-2001 18:18:18 GMT;path=/">

    <style type="text/css">
        table {
            font-size: 14px;
            text-align: center;
            line-height: 20px;
        }
        
        table th {
            border: 1px solid grey;
            width: 150px;
            font-family: '楷體';
        }
        
        table td {
            border: 1px solid grey;
            width: 150px;
            font-family: '新宋體';
            border-top: 0px solid grey;
        }
    </style>

</head>
<body>
    <h2>Hello World!, welcome ${userName}</h2>
    <div align="center" style="width: 100%;">
        <table cellpadding="10" cellspacing="0">
            <thead>
                <tr>
                    <th>序號</th>
                    <th>用戶名</th>
                    <th>聯繫電話</th>
                    <th>聯繫地址</th>
                    <th>初始密碼</th>
                </tr>
            </thead>
            <tbody>
                <c:choose>
                    <c:when test="${not empty ulist}">
                        <c:forEach items="${ulist}" var="user" varStatus="status">
                            <tr style="border-top: 0px solid grey;">
                                <td>${status.index + 1}</td>
                                <td>${user.userId}</td>
                                <td>${user.userName}</td>
                                <td>${user.address}</td>
                                <td>${user.password}</td>
                            </tr>
                        </c:forEach>
                    </c:when>
                    <c:otherwise>
                        <tr style="border-top: 0px solid grey;">
                            <td colspan="5" style="font-family: '楷體';">沒有數據</td>
                        </tr>
                    </c:otherwise>
                </c:choose>
            </tbody>
        </table>
    </div>
</body>
</html>

-----------------------------------------------------------------

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  </head> <body> <div align="center" style="width: 100%; font-family: '';font-size: 18px;">     <form action="http://localhost:8080/xuchen-mvc/system/loginIn.do" method="post" style="line-height: 33px;">         <label>登錄名</label><input type="text" name="userName" > <br>         <label>手機號</label><input type="text" name="mobile" > <br>         <label>年     齡</label><input type="text" name="age" > <br>         <input type="submit" value="登錄™†">         <input type="button" value="驗證用戶" id="validateUser"/>     </form> </div> <script type="text/javascript" src="http://localhost:8080/xuchen-mvc/static/js/jquery-1.11.0.js"></script> <script type="text/javascript">     $(function(){         $("#validateUser").click(function(){             var queryData = {"userId":20021236,"userName":"王昭君","mobile":"18975621305","email":"wzj@163.com"};             $.ajax({                 url:'http://localhost:8080/xuchen-mvc/system/validateUser.do',                 type:'post',                 data:queryData,                 dataType:'json',                 success:function(data){                     alert(data);                 }             });                      });     }); </script> </body> </html>

相關文章
相關標籤/搜索