• SSH框架快速搭建(Maven)


    1.新建Maven项目ssh

    2.pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
            http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.java</groupId>
        <artifactId>ssh</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <packaging>war</packaging>
        <name>${project.artifactId}</name>
        <url>http://maven.apache.org</url>
    
        <!-- 配置版本常量 -->
        <properties>
            <jdk.version>1.7</jdk.version>
            <spring.version>3.2.18.RELEASE</spring.version>
            <struts2.version>2.3.35</struts2.version>
            <hibernate.version>3.6.10.Final</hibernate.version>
        </properties>
    
        <dependencies>
    
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <!-- Struts2 -->
            <dependency>
                <groupId>org.apache.struts</groupId>
                <artifactId>struts2-spring-plugin</artifactId>
                <version>${struts2.version}</version>
            </dependency>
    
            <!-- Hibernate的核心包 -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>${hibernate.version}</version>
            </dependency>
    
            <!-- 连接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.11</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
    
    
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.13</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>4.0.1</version>
                <scope>provided</scope>
            </dependency>
    
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.49</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <finalName>${project.artifactId}</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                    <configuration>
                        <source>${jdk.version}</source>
                        <target>${jdk.version}</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

     

    3.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"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
        version="2.5">
    
        <display-name>ssh</display-name>
        <welcome-file-list>
            <welcome-file>index.jsp</welcome-file>
        </welcome-file-list>
    
        <context-param>
            <param-name>webAppRootKey</param-name>
            <param-value>ssh</param-value>
        </context-param>
    
        <filter>
            <filter-name>struts2</filter-name>
            <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>struts2</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:applicationContext*.xml</param-value>
        </context-param>
    
        <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
        </listener>
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
        </context-param>
    
        <session-config>
            <session-timeout>30</session-timeout>
        </session-config>
    
    </web-app>

    4./ssh/src/main/resources 目录下文件

    5.   struts.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
    
    <struts>
        <constant name="struts.i18n.encoding" value="utf-8" />
        <constant name="struts.ui.theme" value="simple" />
    
        <package name="user" extends="struts-default" namespace="/user">
            <action name="login" class="userAction" method="login">
                <result name="success">/WEB-INF/views/user/Main.jsp</result>
                <result name="login">/WEB-INF/views/user/Login.jsp</result>
            </action>
            <action name="queryUserList" class="userAction" method="queryUserList" />
            <action name="toAddOrUpdateUser" class="userAction" method="toAddOrUpdateUser">
                <result>/WEB-INF/views/user/AddOrUpdateUser.jsp</result>
            </action>
            <action name="addOrUpdateUser" class="userAction" method="addOrUpdateUser">
                <result name="success">/WEB-INF/views/user/Main.jsp</result>
            </action>
            <action name="deleteUser" class="userAction" method="deleteUser" />
        </package>
    
    
    </struts>

    6.   applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                        http://www.springframework.org/schema/beans/spring-beans.xsd 
                        http://www.springframework.org/schema/context     
                        http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/tx 
                        http://www.springframework.org/schema/tx/spring-tx.xsd 
                        http://www.springframework.org/schema/aop 
                        http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <context:property-placeholder location="classpath:param.properties" />
    
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <property name="url" value="${jdbc.url}" />
            <property name="username" value="${jdbc.username}" />
            <property name="password" value="${jdbc.password}" />
            <property name="driverClassName" value="${jdbc.driver}" />
            <property name="initialSize" value="5" />
            <property name="maxActive" value="20" />
        </bean>
    
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <!-- 注入dataSource连接资源 -->
            <property name="dataSource" ref="dataSource" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hibernate.connection.autocommit">true</prop>
                    <prop key="hibernate.cache.use_query_cache">false</prop>
                </props>
            </property>
            <property name="mappingLocations">
                <list>
                    <value>classpath*:com/java/entity/*.hbm.xml</value>
                </list>
            </property>
        </bean>
    
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
    
        <!-- 配置通知 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="get*" read-only="true" />
                <tx:method name="find*" read-only="true" />
                <tx:method name="query*" read-only="true" />
                <tx:method name="add*" propagation="REQUIRED" read-only="false" rollback-for="Exception" />
                <tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="Exception" />
                <tx:method name="insert*" propagation="REQUIRED" read-only="false" rollback-for="Exception" />
                <tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="Exception" />
                <tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="Exception" />
                <tx:method name="*" propagation="REQUIRES_NEW" read-only="false" rollback-for="Exception" />
            </tx:attributes>
        </tx:advice>
    
        <!-- 将事务作用到service包下所有类的所有方法 -->
        <aop:config>
            <aop:pointcut id="pointcut" expression="execution(* com.java.service..*.*(..))" />
            <aop:advisor pointcut-ref="pointcut" advice-ref="txAdvice" />
        </aop:config>
    
        <!-- 注解方式管理事务,需要在类上使用注解@Transactional -->
        <tx:annotation-driven transaction-manager="transactionManager" />
    
        <context:component-scan base-package="com.java.dao.impl" />
        <context:component-scan base-package="com.java.service.impl" />
        <context:component-scan base-package="com.java.action" />
        <context:annotation-config />
    
    </beans>

    7.   param.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://192.168.32.20:3306/ssh?useUnicode=true&characterEncoding=UTF-8
    jdbc.username=root
    jdbc.password=123456

    8.   log4j.properties

    log4j.rootLogger= INFO, stdout
    log4j.logger.INFO=INFO,logfile
    
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender   
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout   
    log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} [%5p] [%c] - %m%n
    
    log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
    log4j.appender.logfile.File=G:/Java/logs/ssh/LogFile.log
    log4j.appender.logfile.DatePattern='_'yyyy-MM-dd'.log'
    log4j.appender.logfile.Threshold=INFO
    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
    log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%5p] - %m%n
    log4j.appender.logfile.Append=true

     

    9.  User.java

    package com.java.entity;
    
    public class User {
        private Integer id;
    
        private String username;
    
        private String password;
    
        private Integer age;
    
        public String getUsername() {
            return username;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User [id=" + id + ", username=" + username + ", password=" + password + ", age=" + age + "]";
        }
    
    }

    10.   User.hbm.xml

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping>
        <class name="com.java.entity.User" table="user">
            <id name="id" type="java.lang.Integer">
                <column name="id" />
                <generator class="increment"></generator>
            </id>
            <property name="username" type="java.lang.String">
                <column name="username" length="32" />
            </property>
            <property name="password" type="java.lang.String">
                <column name="password" length="32" />
            </property>
            <property name="age" type="java.lang.Integer">
                <column name="age" length="3" />
            </property>
        </class>
    </hibernate-mapping>

    11.   BaseDao.java

    package com.java.dao;
    
    import java.io.Serializable;
    import java.util.Collection;
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.hibernate.HibernateException;
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
    
    public class BaseDao extends HibernateDaoSupport {
    
        @Resource
        public void setHibernateSessionFactory(SessionFactory sessionFactory) {
            setSessionFactory(sessionFactory);
        }
    
        public void save(Object entity) {
            getHibernateTemplate().save(entity);
        }
    
        public void update(Object entity) {
            getHibernateTemplate().update(entity);
        }
    
        public void saveOrUpdate(Object entity) {
            getHibernateTemplate().saveOrUpdate(entity);
        }
    
        public void delete(Object entity) {
            getHibernateTemplate().delete(entity);
        }
    
        public <T> void deleteAll(Collection<T> entities) {
            getHibernateTemplate().deleteAll(entities);
        }
    
        public <T> Object get(Class<T> entityClass, Serializable id) {
            return getHibernateTemplate().get(entityClass, id);
        }
    
        public <T> List<T> loadAll(Class<T> entityClass) {
            return getHibernateTemplate().loadAll(entityClass);
        }
    
        public List<?> find(String hql, Object... values) {
            return getHibernateTemplate().find(hql, values);
        }
    
        public List<?> query(String sql, Object... values) {
            Session session = openSession();
            SQLQuery query = session.createSQLQuery(sql);
            if (null != values) {
                int len = values.length;
                for (int i = 0; i < len; i++) {
                    query.setParameter(i, values[i]);
                }
            }
            List<?> list = query.list();
            session.close();
            return list;
    
        }
    
        public Object sqlQueryUnique(String sql, Object... values) {
            Session session = openSession();
            SQLQuery query = session.createSQLQuery(sql);
            if (null != values) {
                int len = values.length;
                for (int i = 0; i < len; i++) {
                    query.setParameter(i, values[i]);
                }
            }
            Object result = query.uniqueResult();
            session.close();
            return result;
        }
    
        public int executeSQL(String sql, Object... values) {
            Session session = openSession();
            SQLQuery query = session.createSQLQuery(sql);
            if (null != values) {
                int len = values.length;
                for (int i = 0; i < len; i++) {
                    query.setParameter(i, values[i]);
                }
            }
            int count = query.executeUpdate();
    
            session.close();
            return count;
        }
    
        /**
         * 批量执行SQL
         * 
         * @param sqlList 将要执行的SQL集合
         * @return 执行SQL数量
         */
        public int exeBatchSQL(List<String> sqlList) {
            Session session = openSession();
    
            int count = sqlList.size();
            for (int i = 0; i < count; i++) {
                String sql = sqlList.get(i);
                session.createSQLQuery(sql).executeUpdate();
                if (i % 10000 == 0) {
                    session.flush();
                    session.clear();
                }
            }
            session.flush();
            session.clear();
    
            session.close();
            return count;
        }
    
        /**
         * 开启Session
         * 
         * @return Session
         * @throws HibernateException Hibernate异常
         */
        public Session openSession() throws HibernateException {
            return getHibernateTemplate().getSessionFactory().openSession();
        }
    
    }

     

    12.   UserDao.java

    package com.java.dao;
    
    import java.util.List;
    
    import com.java.entity.User;
    
    public interface UserDao {
    
        Object checkLogin(User user);
    
        List<User> queryUserList(User user);
    
        void saveOrUpdateUser(User user);
    
        void deleteUser(User user);
    
    }

    13.   UserDaoImpl.java

    package com.java.dao.impl;
    
    import java.util.List;
    
    import org.springframework.stereotype.Repository;
    
    import com.java.dao.BaseDao;
    import com.java.dao.UserDao;
    import com.java.entity.User;
    
    @Repository("userDao")
    public class UserDaoImpl extends BaseDao implements UserDao {
    
        @Override
        public Object checkLogin(User user) {
            String sql = "select 1 from user where username=? and password=?";
            return sqlQueryUnique(sql, user.getUsername(), user.getPassword());
        }
    
        @Override
        @SuppressWarnings("unchecked")
        public List<User> queryUserList(User user) {
            String hql = "from User";
            return (List<User>) find(hql);
        }
    
        @Override
        public void saveOrUpdateUser(User user) {
            saveOrUpdate(user);
        }
    
        @Override
        public void deleteUser(User user) {
            delete(user);
        }
    
    }

     

    14.   UserService.java

    package com.java.service;
    
    import java.util.List;
    
    import com.java.entity.User;
    
    public interface UserService {
    
        Object checkLogin(User user);
    
        List<User> queryUserList(User user);
    
        void saveOrUpdateUser(User user);
    
        void deleteUser(User user);
    
    }

    15.   UserServiceImpl.java

    package com.java.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.java.dao.UserDao;
    import com.java.entity.User;
    import com.java.service.UserService;
    
    @Service("userService")
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserDao userDao;
    
        @Override
        public Object checkLogin(User user) {
            return userDao.checkLogin(user);
        }
    
        @Override
        public List<User> queryUserList(User user) {
            return userDao.queryUserList(user);
        }
    
        @Override
        public void saveOrUpdateUser(User user) {
            userDao.saveOrUpdateUser(user);
    
            // 切入异常的方法,抛出异常时事务自动回滚
            // throw new RuntimeException("事务异常演习!");
        }
    
        @Override
        public void deleteUser(User user) {
            userDao.deleteUser(user);
        }
    
    }

    16.   BaseAction.java

    package com.java.action;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.apache.struts2.interceptor.ServletRequestAware;
    import org.apache.struts2.interceptor.ServletResponseAware;
    import org.apache.struts2.interceptor.SessionAware;
    
    import com.alibaba.fastjson.JSON;
    import com.opensymphony.xwork2.ActionSupport;
    
    public class BaseAction extends ActionSupport implements ServletRequestAware, ServletResponseAware, SessionAware {
    
        /**
         * 序列号
         */
        private static final long serialVersionUID = -2096531748559702251L;
    
        /**
         * 日志
         */
        private static final Log LOG = LogFactory.getLog(BaseAction.class);
    
        protected HttpServletRequest request;
        protected HttpServletResponse response;
        protected Map<String, Object> session;
    
        protected void write(String message) {
            response.setContentType("text/html; charset=utf-8");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.write(message);
                writer.flush();
            } catch (IOException e) {
                LOG.error("IO异常");
                e.printStackTrace();
            } finally {
                writer.close();
            }
        }
    
        protected void write(Object object) {
            String json = JSON.toJSONString(object);
            write(json);
        }
    
        protected OutputStream getDownloadOutputStream(String fileName) {
            try {
                fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
                OutputStream os = response.getOutputStream();
                response.reset();
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
                return os;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public Object getCurrentUser() {
            return session.get("user");
        }
    
        @Override
        public void setSession(Map<String, Object> session) {
            this.session = session;
        }
    
        @Override
        public void setServletResponse(HttpServletResponse response) {
            this.response = response;
        }
    
        @Override
        public void setServletRequest(HttpServletRequest request) {
            this.request = request;
        }
    
    }

    17.   UserAction.java

    package com.java.action;
    
    import java.util.List;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;
    
    import com.java.entity.User;
    import com.java.service.UserService;
    
    @Controller
    @Scope("prototype")
    public class UserAction extends BaseAction {
    
        /**
         * 序列号
         */
        private static final long serialVersionUID = -1969618485215878991L;
    
        private static final Log LOG = LogFactory.getLog("INFO");
    
        @Autowired
        private UserService userService;
    
        private User user;
    
        public String login() {
            LOG.info("Into login");
            System.out.println(user);
    
            // 检查用户名密码是否存在
            Object result = userService.checkLogin(user);
            System.out.println("result: " + result);
            LOG.info("result: " + result);
            LOG.info("Exit login");
    
            // 绑定用户名密码输出返回
            if (null == result) {
                return LOGIN;
            }
    
            return SUCCESS;
        }
    
        public void queryUserList() {
            LOG.info("Into queryUserList");
            System.out.println(user);
    
            // user对象可做查询条件封装传入
            List<User> list = userService.queryUserList(user);
    
            write(list);
            LOG.info("Exit queryUserList");
        }
    
        public String toAddOrUpdateUser() {
            LOG.info("Into toAddOrUpdateUser");
            System.out.println("user: " + user);
    
            LOG.info("Exit toAddOrUpdateUser");
            return SUCCESS;
        }
    
        public String addOrUpdateUser() {
            LOG.info("Into addOrUpdate");
            System.out.println("user: " + user);
    
            userService.saveOrUpdateUser(user);
            LOG.info("Exit addOrUpdate");
            return SUCCESS;
        }
    
        public void deleteUser() {
            System.out.println(user);
            LOG.info("Into deleteUser");
    
            userService.deleteUser(user);
    
            LOG.info("Exit deleteUser");
            write("删除成功!");
        }
    
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    
    }

    18.  ssh.sql

    DROP DATABASE IF EXISTS ssh;
    CREATE DATABASE ssh;
    USE ssh;
    DROP TABLE IF EXISTS `user`;
    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `username` varchar(32) NOT NULL,
      `password` varchar(32) NOT NULL,
      `age` int(3) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    
    ;

     

    19.页面结构

     

    index.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>登录</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script type="text/javascript">
        function addUser() {
            location.href = "user/toAddOrUpdateUser";
        }
    </script>
    </head>
    
    <body>
        <form action="user/login" method="post">
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input name="user.username" /><br /></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" name="user.password" /><br /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="登录" /></td>
                    <td><input type="button" value="注册" onclick="addUser();" /></td>
                </tr>
            </table>
    
        </form>
    
    </body>
    
    </html>

    /webapp/WEB-INF/views/user/Login.jsp 

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>登录</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script type="text/javascript">
        function addUser() {
            location.href = "user/toAddOrUpdateUser";
        }
    </script>
    </head>
    
    <body>
        <form action="user/login" method="post">
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input name="user.username" value="${user.username}" /><br /></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" name="user.password" value="${user.password}" /><br /></td>
                </tr>
                <tr>
                    <td><input type="submit" value="登录" /></td>
                    <td><input type="button" value="注册" onclick="addUser();" /></td>
                </tr>
            </table>
    
        </form>
    
    </body>
    
    </html>

    Main.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
        String path = request.getContextPath();
                String basePath = request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + path + "/";
    %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>主页</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="js/jquery-1.11.3.js"></script>
    <style type="text/css">
    td,th {
        border: 1px solid #AAA;
    }
    </style>
    <script type="text/jscript">
        
                $(function() {
                    queryUserList();
                });
                
                function queryUserList() {
                    $.post("user/queryUserList", {id: 1}, function(data) {
                        var userList = eval("(" + data + ")");
                        var line = null;
                        $("#list").empty();
                        for(var i in userList) {
                            line = tr(td(userList[i].id) + td(userList[i].username) + td(userList[i].password) + td(userList[i].age) + td(addBtn() + delBtn()));
                            $("#list").append(line);
                        }
                    });
                }
    
                function tr(text) {
                    return "<tr>" + text + "</tr>";
                }
    
                function td(text) {
                    if(!text) {
                        text = "";
                    }
                    return "<td>" + text + "</td>";
                }
                
                function addBtn() {
                    return "<button onClick='update(this);'>修改</button>";
                }
                
                function delBtn() {
                    return "<button onClick='deleteUser(this);'>删除</button>";
                }
                
                function update(obj) {
                    var row = getRow(obj);
                    
                    var id = row.eq(0).text();
                    var username = row.eq(1).text();
                    var password = row.eq(2).text();
                    var age = row.eq(3).text();
    
                    // Get方式发送请求,会出现乱码,需要修改Tomcat URIEncoding="UTF-8"
                    // var params = "id=" + id + "&username=" + username + "&password=" + password + "&age=" + age;                
                    // location.href = "user/toAddOrUpdateUser?" + params;
                    
                    var user = {
                            "user.id": id,
                            "user.username": username,
                            "user.password": password,
                            "user.age": age
                    }
                    
                    var form = document.createElement("form");
                    form.action = "user/toAddOrUpdateUser";
                    form.method = "post";
                    
                    var input = null;
                    for(var key in user) {
                        input = document.createElement("input");
                        
                        input.type = "hidden";
                        input.name = key;
                        input.value = user[key];
                        form.appendChild(input)
                    }
                    document.body.appendChild(form);
                    form.submit();
    
                }
                
                function deleteUser(obj) {
                    var row = getRow(obj);
                    
                    var id = row.eq(0).text();
                    $.post("user/deleteUser", {"user.id": id}, function(data) {
                        alert(data);
                        queryUserList();
                    });
                }
                
                function getRow(obj) {
                    return $(obj).parent().parent().children();
                }
            
    </script>
    </head>
    
    <body>
        <button onClick="location.href='user/toAddOrUpdateUser'">新增</button>
        <div>
            <table style="border-collapse: collapse;  800px;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>年龄</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="list">
                </tbody>
            </table>
        </div>
    
    </body>
    
    </html>

    AddOrUpdateUser.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    %>
    
    <!DOCTYPE html>
    <html>
    <head>
    <base href="<%=basePath%>">
    
    <title>新增用户</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    </head>
    
    <body>
        <form action="user/addOrUpdateUser" method="post">
            <input name="user.id" value="${user.id}" type="hidden"/>
            <table>
                <tr>
                    <td>用户名:</td>
                    <td><input type="text" name="user.username" value="${user.username}"  /><br /></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input type="password" name="user.password" value="${user.password}"  /><br /></td>
                </tr>
                <tr>
                    <td>年龄:</td>
                    <td><input type="text" name="user.age" value="${user.age}"  /><br /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" value="提交" /></td>
                </tr>
            </table>
    
        </form>
    
    </body>
    
    </html>

    注意:

     jquery-1.11.3.js 请自行下载,配置到Main.jsp文件中

       https://code.jquery.com/jquery-1.11.3.js
       https://code.jquery.com/jquery-1.11.3.min.js

    配置完成!

    .

  • 相关阅读:
    LoadScript
    Mac终端Terminal调用Sublime Text
    jquery ajax 提交 FormData
    ps切图设置
    bootstrap-select搜索框输入中文
    Homebrew安装
    清空file input框
    javascript 随机数区间
    Canvas与Image互转
    html空格小结
  • 原文地址:https://www.cnblogs.com/jonban/p/ssh.html
Copyright © 2020-2023  润新知