SpringMVC+Hibernate框架快速搭建

 

1.  新建Maven项目springmvc

 

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>springmvc</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>
        <hibernate.version>3.6.10.Final</hibernate.version>
    </properties>

    <dependencies>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.7</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>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.23.1-GA</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>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</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>springmvc</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>springmvc</param-value>
    </context-param>

    <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>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <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.   /springmvc/src/main/resources  目录下文件

 

 

5.   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:annotation-config />

</beans>

 

 

6.   springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc" 
    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/mvc     
                    http://www.springframework.org/schema/mvc/spring-mvc.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">



    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/views/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="4294967296"></property>
    </bean>

    <!-- 配置资源 -->
    <mvc:resources location="/WEB-INF/assets/" mapping="/assets/**"></mvc:resources>

    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <context:component-scan base-package="com.java.controller" />
    <context:annotation-config />

</beans>

 

 

7.   param.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.32.20:3306/springmvc?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/springmvc/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.   创建数据库

DROP DATABASE IF EXISTS springmvc;
CREATE DATABASE springmvc;
USE springmvc;
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;

;

 

10.   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 + "]";
    }

}

 

 

11.   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>

 

 

12.   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();
    }

}

 

13.   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);

}

 

 

14.   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);
    }

}

 

 

15.   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);

}

 

16.   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);
    }

    @Override
    public void deleteUser(User user) {
        userDao.deleteUser(user);
    }

}

 

17.   UserController.java

package com.java.controller;

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 org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.java.entity.User;
import com.java.service.UserService;

@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController {

    private static final Log LOG = LogFactory.getLog("INFO");

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(@ModelAttribute User user, Model model) {
        LOG.info("Into login");
        System.out.println(user);

        // 检查用户名密码是否存在
        Object result = userService.checkLogin(user);
        System.out.println("result: " + result);
        LOG.info("result: " + result);

        // 绑定用户名密码输出返回
        if (null == result) {
            model.addAttribute("username", user.getUsername());
            model.addAttribute("password", user.getPassword());
            return "user/Login";
        }

        LOG.info("Exit login");
        return "user/Main";
    }

    @ResponseBody
    @RequestMapping("/queryUserList")
    public List<User> queryUserList(@ModelAttribute User user) {
        System.out.println(user);
        LOG.info("Into queryUserList");

        List<User> list = userService.queryUserList(user);

        LOG.info("Exit queryUserList");
        return list;
    }

    @RequestMapping("/toAddOrUpdateUser")
    public String toAddOrUpdateUser(@ModelAttribute User user, Model model) {
        LOG.info("Into toAddOrUpdateUser");
        System.out.println("user: " + user);

        // 输出id,根据id是否为空,判断是新增还是修改
        model.addAttribute("user", user);
        LOG.info("Exit toAddOrUpdateUser");
        return "user/AddOrUpdateUser";
    }

    @RequestMapping("/addOrUpdateUser")
    public String addOrUpdateUser(@ModelAttribute User user) {
        LOG.info("Into addOrUpdate");
        System.out.println("user: " + user);

        userService.saveOrUpdateUser(user);
        LOG.info("Exit addOrUpdate");
        return "user/Main";
    }

    @ResponseBody
    @RequestMapping("/deleteUser")
    public String deleteUser(@ModelAttribute User user) {
        System.out.println(user);
        LOG.info("Into deleteUser");

        userService.deleteUser(user);

        LOG.info("Exit deleteUser");
        return "删除成功!";
    }

}

 

 

18.   页面文件结构

 

 index.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="username" /><br /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" /><br /></td>
            </tr>
            <tr>
                <td><input type="submit" value="登录" /></td>
                <td><input type="button" value="注册" onclick="addUser();" /></td>
            </tr>
        </table>

    </form>

</body>

</html>

 

 

 

 

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="username" value="${username}" /><br /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" value="${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="assets/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(userList) {
                    /* var userList = eval("(" + userList + ")"); */
                    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 = {
                        id: id,
                        username: username,
                        password: password,
                        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", {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;width: 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="id" value="${user.id}" type="hidden"/>
        <table>
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="username" value="${user.username}"  /><br /></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" name="password" value="${user.password}"  /><br /></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="text" name="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

 

 配置完成!

 

.

posted @ 2018-09-23 14:54  诚信天下  阅读(497)  评论(0编辑  收藏  举报