源码下载:https://pan.baidu.com/s/1kUK7qYj   提取码:3mgb

 

 

最近在学习SSM框架,先讲一下这三大框架都有什么作用。

SpringMVC: 

它用于web层,相当于controller(等价于传统的servlet和struts的action),用来处理用户请求。举个例子,用户在地址栏输入http://网站域名/login,那么springmvc就会拦截到这个请求,并且调用controller                            层中相应的方法,(中间可能包含验证用户名和密码的业务逻辑,以及查询数据库操作,但这些都不是springmvc的职责),最终把结果返回给用户,并且返回相应的页面(当然也可以只反馈josn/xml等格式                          数据)。 springmvc就是做前面和后面过程的活,与用户打交道!!

Spring:       

太强大了,以至于我无法用一个词或一句话来概括它。但与我们平时开发接触最多的估计就是IOC容器,它可以装载bean(也就是我们java中的类,当然也包括service dao里面的),有了这个机制,我们就                           不用在每次使用这个类的时候为它初始化,很少看到关键字new。另外spring的aop,事务管理等等都是我们经常用到的。

MyBatis:   

  如果你问我它跟鼎鼎大名的Hibernate有什么区别?我只想说,他更符合我的需求。第一,它能自由控制sql,这会让有数据库经验的人(当然不是说我啦~捂脸~)编写的代码能搞提升数据库访问的效率。第                           二,它可以使用xml的方式来组织管理我们的sql,因为一般程序出错很多情况下是sql出错,别人接手代码后能快速找到出错地方,甚至可以优化原来写的sql。

 

一、创建一个Maven工程

    1.1、Maven是什么?

     Maven是一个项目管理和综合工具。Maven提供了开发人员构建一个完整的生命周期框架。开发团队可以自动完成项目的基础工具建设,Maven使用标准的目录结构和默认构建生命周期。

     在多个开发团队环境时,Maven可以设置按标准在非常短的时间里完成配置工作。由于大部分项目的设置都很简单,并且可重复使用,Maven让开发人员的工作更轻松,同时创建报表,检查,构建和测试自动化设置。

     如果没有搭建可以参考我的另一篇博客

     1.2、使用Elipse创建Maven工程,如果不会可以点这http://www.yiibai.com/maven/create-a-maven-web-project-with-eclipse.html

      创建完成后的工程项目结构如下:

spring mvc按钮点击事件 spring mvc 例子_java

spring mvc按钮点击事件 spring mvc 例子_spring_02

二、下面进行框架整合

2.1、导入需要的jar包,Maven工程只需要在pom.xml中配置即可

pom.xml


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.smart</groupId>
  <artifactId>FirstSSM</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>FirstSSM Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <properties>  
        <spring.version>4.3.3.RELEASE</spring.version>  
    </properties>  
    
 <dependencies>  
        <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>4.11</version>  
            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->  
            <scope>test</scope>  
        </dependency>  
        
          <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>servlet-api</artifactId>  
            <version>2.3</version>  
            <scope>provided</scope>  
        </dependency>  
        
         <!-- MySQL依赖 start -->  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.38</version>  
        </dependency>  
  
        <!-- MySQL依赖 end -->  
          
           <!-- 导入dbcp的jar包,用来在xml中配置数据库 -->  
        <dependency>  
            <groupId>commons-dbcp</groupId>  
            <artifactId>commons-dbcp</artifactId>  
            <version>1.2.2</version>  
        </dependency> 
          
        <!-- 加入MyBatis 依赖 start -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.2.5</version>  
        </dependency>  
        <!-- 加入MyBatis 依赖 end -->  
  
        <!-- Log4j start -->  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
        </dependency>  
        <!-- Log4j end -->  
        
        
         <!-- 引入Spring(包含SpringMVC) 依赖 start -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-oxm</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>${spring.version}</version>  
        </dependency>  
  
        <!-- 引入Spring 依赖 end -->  
        
         <!-- 引用插件依赖:MyBatis整合Spring -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.3.0</version>  
        </dependency>  
      
        <!-- JSTL -->  
        <dependency>  
            <groupId>jstl</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
      
  </dependencies>
  <build>
    <finalName>FirstSSM</finalName>
     <plugins>               
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <!-- Config: contextPath and Port (Default - /HelloSpringMVC : 8080) -->
                <!--
                <configuration>
                    <path>/</path>
                    <port>8899</port>
                </configuration>
                -->   
            </plugin>
        </plugins>
  </build>
</project>

pom.xml

2.2、配置mybatis.xml文件

mybatis.xml


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
   <typeAliases>
       <typeAlias alias="User" type="com.smart.bean.User"/>
   </typeAliases>
</configuration>

mybatis.xml

2.3、配置spring-mybatis.xml, 这个文件就是用来完成spring和mybatis的整合的。这里面也没多少行配置,主要的就是自动扫描,自动注入,配置数据库。注释也很详细,大家看看就明白了。

 spring-mybatis.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
    default-autowire="byName" default-lazy-init="false">
    
    
    <!--本示例采用DBCP连接池,应预先把DBCP的jar包复制到工程的lib目录下。classpath路径是resources文件下 -->
    <context:property-placeholder location="classpath:database.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver"
        p:url="jdbc:mysql://localhost:3306/表名?characterEncoding=utf8"
        p:username="root" p:password="数据库密码" p:maxActive="10" p:maxIdle="10">
    </bean>
    
    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--dataSource属性指定要用到的连接池-->
        <property name="dataSource" ref="dataSource" />
        <!--configLocation属性指定mybatis的核心配置文件-->
        <property name="configLocation" value="classpath:mybatis.xml" />
        <!-- 所有配置的mapper文件 -->
        <property name="mapperLocations" value="classpath*:mapper/*.xml" />
    </bean>
    
     <!-- DAO接口所在包名,Spring会自动查找其下的类 --> 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.smart.dao"/>
    </bean>
    </beans>


2.4、下面是配置database.properties和log4j.properties

   为了方便调试,一般都会使用日志来输出信息,Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、     UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。

  Log4j的配置很简单,而且也是通用的

log4j.properties


log4j.rootLogger = debug , stdout , D , E


log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{ABSOLUTE}  %m%n


log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${catalina.base}/logs/system.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n


log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File =  ${catalina.base}/logs/systemerror.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = ERROR
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n


 

database.properties

 


jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=""


  

2.5、以上整合了Spring和Mybatis,下面加入SpringMVC

web.xml


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>MyBatis_Spring_MVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
               <!--字符过滤器-->
    <filter>
        <filter-name>encodingFilter</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>

               <!--静态资源-->
     <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:spring-mybatis.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextCleanupListener</listener-class>
    </listener>
     
<!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

View Code

spring-mvc-servlet.xml


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
        
        <!--自动扫描controller-->
    <context:component-scan base-package="com.smart.controller" />
    
    <!--视图解析-->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

View Code

以下框架就算搭建完成了,数据表源码中有。

三、实现

User.class


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

package com.smart.bean;

public class User {
    private int id;    
    private String name;
    private String phone;
    private String email;
    private String password;
    private String repassword;
    private String sex;
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getRepassword() {
        return repassword;
    }
    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
}

View Code

UserDao


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

package com.smart.dao;

import java.util.List;

import com.smart.bean.User;

public interface UserDao {

    public void addUser(User user);
    public User getUserByName(String name);
    public List<User> listUser();
    public void delUser(String name);
}

View Code

UserMapper.xml


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace指定接口-->
<mapper namespace="com.smart.dao.UserDao">

    <!-- 为了返回list 类型而定义的returnMap -->
    <resultMap type="User" id="resultUser">
        <id column="id" property="id" />
        <result column="phone" property="phone" />
        <result column="email" property="email" />
        <result column="password" property="password" />
        <result column="repassword" property="repassword" />
        <result column="name" property="name" />
        <result column="sex" property="sex" />
    </resultMap>
    
    <insert id="addUser" parameterType="User">
         INSERT INTO stu(phone,email,password,repassword,name,sex)
         VALUES(#{phone},#{email},#{password},#{repassword},#{name},#{sex})
    </insert>
    
    <select id="getUserByName" parameterType="User" resultMap="resultUser">
         select *
         from stu
         where name=#{name}
    </select>    

    <select id="listUser"  resultMap="resultUser">
       SELECT *
       FROM stu      
    </select>
    
    <delete id="delUser" parameterType="String">
        delete from stu
        where name=#{name}
    </delete>
    
</mapper>

View Code

UserController


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

package com.smart.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.Out;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.smart.bean.User;
import com.smart.dao.UserDao;



@Controller
@RequestMapping("/")
public class UserController {
    @Autowired
    UserDao userdao;
    
    //主页
      @RequestMapping(value = "/user", method = RequestMethod.GET)
       public ModelAndView student() {
          return new ModelAndView("user", "command", new User());
       }
    
      //注册
      @RequestMapping(value="/register")
      public ModelAndView add(User user) {
          List<User> list = userdao.listUser();
          ModelAndView mav = null;
          int flag= 0;
          for (User user1 : list) {
            if(user1.getName().equals(user.getName())) {
                  flag = 1;
                  mav = new ModelAndView("user");
                  mav.addObject("tip1", "用户已存在!");
                  break;
            }
        }
          if(flag==0) {
              userdao.addUser(user);
              mav = new ModelAndView("user");
              mav.addObject("tip1", "注册成功!!!");
          }
          
          return mav;
      }
      
      
      //登录
      @RequestMapping(value="/login")
        public ModelAndView Login() {
            return new ModelAndView("Login");
        }
      
      
      //用户列表
      @RequestMapping(value="/list")
        public ModelAndView List(String name,String password,String n) {
            System.out.println(n);
            List<User> list = userdao.listUser();
            int f = 0;
            ModelAndView mav = null;
            for (User user : list) {
                if(user.getName().equals(name)) {
                    f = 1;
                    if(user.getPassword().equals(password)) {
                        mav = new ModelAndView("UserList");                    
                        mav.addObject("list",list);
                    } else {                    
                        mav = new ModelAndView("Login");
                        mav.addObject("tip", "密码错误,请重新登录!");
                    }
                    break;
                }                                                                 
            }
            if(f==0) {
                mav = new ModelAndView("Login");
                mav.addObject("tip", "用户名不存在,请重新输入");
            }    
                    
            return mav;
        }
      
      @RequestMapping(value="/del")
      public ModelAndView del(String name) throws UnsupportedEncodingException {
          String n =  new String(name.getBytes("iso-8859-1"),"utf-8");
          System.out.println(n);
          userdao.delUser(n);
          ModelAndView mav = new ModelAndView("UserList");
          List<User> list = userdao.listUser();
          mav.addObject("list", list);
          return mav;
      }
      
      @RequestMapping("/lll")
      public String testlll(String name,HttpServletResponse response) {
         System.out.println(name);
         String msg = "N";
         String ss=name;
          List<User> list = userdao.listUser();
          for (User user2 : list) {              
            if(user2.getName().equals(ss)) {
                msg = "Y";                
                break;
            }            
        }          
          try {
            PrintWriter out=response.getWriter();
            out.write(msg);        
            out.flush();
        } catch (IOException e) {            
            e.printStackTrace();
        }                   
          return msg;
      }
      
     
}

View Code

 

JSP视图

user.jsp注册页面


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>register</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">

<script type="text/javascript">
$().ready(function() {
    // 在键盘按下并释放及提交后验证提交表单
      $("#vForm").validate({
          
            rules: {
              phone:{required:true,isMobile:true},    
              email:{required:true,email:true},
              
              password: {
                required: true,
                minlength: 5,
                maxlength: 12
              },
              repassword: {
                required: true,
                minlength: 5,
                maxlength: 12,
                equalTo: "#password"
              }, 
              name: {required: true,maxlength:32},
            },

            messages: {              
              phone: {
                required: "请输入手机号<br/>",
                minlength: "请输入11位的有效手机号码<br/>"
              },
              email: {
                    required: "请输入邮箱<br/>",
                    minlength: "请输入正确的邮箱<br/>"
                  },
              password: {
                required: "请输入密码<br/>",
                minlength: "密码长度不能小于 5 个字母<br/>",
                maxlength: "密码长度不能大于 12 个字母<br/>"
              },
              repassword: {
                required: "请再次输入密码<br/>",
                minlength: "密码长度不能小于 5 个字母<br/>",
                maxlength: "密码长度不能大于 12 个字母<br/>",
                equalTo: "两次密码输入不一致<br/>"
              },
              name: {
                    required: "请输入用户名<br/>",
                    minlength: "用户名长度不得大于32个字符<br/>"
                  },          
            }
        });
    });
</script>

<style>
.error{
    color:red;
}
</style>

</head>
<body>

<script type="text/javascript">
$(document).ready(function () {
    
    if(!"${tip1}"){
        $(".alert").hide();
    }        
    
})
</script>

<div class="container" style="margin-top: 30px">
<div class="well" style="margin-left: 10%;margin-right: 10%">

<div class="alert alert-warning" id="alert">
    <a href="#" class="close" data-dismiss="alert">
        ×
    </a>
    <strong>${tip1}</strong>
</div>


<div class="row" style="margin-top: 35px">
 <form class="form-horizontal"  role="form" id="vForm" method="POST" action="register">
  
  <div class="form-group">
    <label for="phone" class="col-sm-4 control-label">手       机</label>
    <div class="col-sm-4">
      <input type="text" class="form-control" id="phone" name="phone" placeholder="请输入手机号">
    </div>
  </div>
  
  <div class="form-group">
    <label for="email" class="col-sm-4 control-label">邮       箱</label>
    <div class="col-sm-4">
      <input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
    </div>
  </div>
  
  <div class="form-group">
    <label for="passowrd" class="col-sm-4 control-label">密       码</label>
    <div class="col-sm-4">
      <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
    </div>
  </div>
  
  <div class="form-group">
    <label for="repassowrd" class="col-sm-4 control-label">重复密码</label>
    <div class="col-sm-4">
      <input type="password" class="form-control" id="repassword" name="repassword" placeholder="请再次输入密码">
    </div>
  </div>
  
  <div class="form-group ">
    <label for="name" class="col-sm-4 control-label">姓       名</label>
    <div class="col-sm-4">
      <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
    </div>
  </div>
  
  
 <div class="form-group">
  <label for="sex" class="col-sm-4 control-label">性       别</label>
    <div>   
      <label class="radio-inline">
           <input type="radio" name="sex" id="boy" value="男" checked> 男
      </label>
      <label class="radio-inline">
        <input type="radio" name="sex" id="girl"  value="女"> 女
      </label>
    </div>
 </div>
 
 <div class="form-group">
   <div class="col-sm-4 col-sm-offset-3 control-label ">
    <button type="submit" class="btn btn-info">提交</button>       
    <a href="login" class="btn btn-info">登录</a>
   </div>
 </div>
 
</form>
</div>
</div>
</div>



</body>
</html>

View Code

Login.jsp登录页面


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
    
    if(!"${tip}"){
        $(".alert").hide();
    }    
    
    $("#bu").click(function () {        
        $("#vForm").submit();            
    })
    
    $("#name").blur(function () {
        $.ajax({
            type:"post",
            url:"lll",
            data:{"name":$("#name").val()},
            async:false,
            success:function(msg){
                if(msg=="N"){alert("用户不存在!")}
            },
            error:function(){
                alert(error);
            }
        })
        
    
    })
    
})
</script>
<div class="container" style="margin-top: 30px">
<div class="well" style="margin-left: 10%;margin-right: 10%">

<div class="alert alert-warning" id="alert">
    <a href="#" class="close" data-dismiss="alert">
        ×
    </a>
    <strong>${tip}</strong>
</div>

<div class="row" style="margin-top: 35px">
 <form class="form-horizontal"  role="form" id="vForm" method="POST" action="list">
  <div class="form-group ">
    <label for="name" class="col-sm-4 control-label">姓       名</label>
    <div class="col-sm-4">
      <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
    </div>
  </div>
 <div class="form-group">
    <label for="passowrd" class="col-sm-4 control-label">密       码</label>
    <div class="col-sm-4">
      <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
    </div>
  </div>
   <div class="form-group">
   <div class="col-sm-4 col-sm-offset-3 control-label ">
    <button type="button" class="btn btn-info" id="bu">登录</button>    
    <a href="register" class="btn btn-info">注册</a>
   </div>
 </div>
  </form>
  </div>
</div>
</div>
</body>
</html>

View Code

UserList.jsp用户列表


spring mvc按钮点击事件 spring mvc 例子_数据库_03

spring mvc按钮点击事件 spring mvc 例子_spring mvc按钮点击事件_04

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
  <%@ taglib prefix="c" 
           uri="http://java.sun.com/jsp/jstl/core" %>
           <%@ page isELIgnored="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jqPaginator.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="margin-top: 30px">
<div class="well" style="margin-left: 10%;margin-right: 10%">
<div class="row" style="margin-top: 35px">
<table class="table table-striped" >
  <caption>用户列表</caption>
  <thead>  
    <tr>
      <th>电话</th>
      <th>邮箱</th>
      <th>密码</th>
      <th>重复密码</th>
      <th>名字</th>
      <th>性别</th>
      <th>操作</th>
    </tr>    
  </thead>
  <tbody>
  <c:forEach items="${list}" var="user">
    <tr>
      <td>${user.phone}</td>
      <td>${user.email}</td>
      <td>${user.password}</td>
      <td>${user.repassword}</td>
      <td id="name">${user.name}</td>
      <td>${user.sex}</td> 
      <td><a href="del?name=${user.name}">删除</a></td>     
    </tr>     
  </c:forEach>
  </tbody>
</table>
  </div>
  </div>
  </div>

</body>
</html>

View Code