7.27--SSH学习之SpringMVC,Ajax请求、拦截器、文件上传和MyBatis访问数据库基本操作

第一点:ajax请求

在一个表单中由jquery发起一个ajax请求,然后访问控制器,返回json结果,最后把结果显示在原表单中。

1. 下面是一个用户注册页面,当输入用户名时就立即发起ajax请求,来判断这个用户名是否可用

注册表单如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'adduser.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#loginId").bind("blur",function(){
                var loginId = $("#loginId").val();
                $.ajax({
                    url:"checkuserexist.action",
                    type:"post",
                    data:{"userName":loginId,"userPwd":"11111","userlevel":"VIP"},
                    datatype:"json",
                    success:function(data){
        //              alert("aaaa")
                        $("#userInfo").html(data.resultStr);
                    }
                });
            });
        });


    </script>
  </head>
  <body>
     <form action="listuser.jsp" method="post">
        账号:<input type="text" name="loginId" id="loginId" value="小篆风"><span style="color:red" id="userInfo"></span><br>
        密码:<input type="password" name="loginPwd" id="loginPwd" value="1111"><br>
        <input type="submit" value="注册">
     </form>
  </body>
</html>


在上面的ajax请求中访问名为checkuserexist.action的控制器方法,代码如下:

    @RequestMapping("checkuserexist.action")
    public @ResponseBody ResultData checkUserExist(User user)throws Exception{
        ResultData rd = new ResultData();
        System.out.println(user.getUserName());
        System.out.println(user.getUserPwd());
        System.out.println(user.getUserlevel());
        if(user.getUserName().equals("Tom")){
            rd.setResultStr("此用户已存在,请重新输入");
        }else{
            rd.setResultStr("用户名可以使用");
        }
        return rd;
    }


当然上面为了简单,就没有访问数据库,直接写了一个限制用户名,在项目开发中就需要访问数据库,然后把结果回显到原表单了。

另外一个就是显示数据库中某个表的数据,也是通过ajax请求完成,找到数据后还要重新绘制页面,以便数据显示呢。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'listuser.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(function(){
            $.ajax({
                url:"findalluser.action",
                type:"post",
                success:function(data){
                    for(var i = 0;i< data.length;i++){
                        var newRow = "<tr><td>"+data[i].userName+"</td><td>"+data[i].userPwd+"</td><td>"+data[i].userlevel+"</td><tr>";
                        $("#userTable").append(newRow);
                    //完成ajax请求需要对页面重新绘制
                    }
                }

            });
        });

    </script>
  </head>
  <body>
    <table border="1" id="userTable">
        <tr>
            <td>用户名</td>
            <td>密码</td>
            <td>等级</td>
        </tr>
    </table>
  </body>
</html>



第二点:拦截器


在SpringMVC中用户登录时先访问拦截器再执行验证登陆的方法

<body>
    <form action="login.action" method="post">
        用户名:<input type="text" name="userName" value="susu"><br>
        密码:<input type="password" name="userPwd" value="1111"><br>
        <input type="submit" value="Login">
    </form>
 </body>


在上面表单提交的action需要在springmvc.xml中配置拦截器

<!-- 配置SpringMVC的拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/login.action"/>
            <bean class="com.su.interceptor.FirstInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>


拦截器中有三个方法,依次按照其功能执行

    public class FirstInterceptor implements HandlerInterceptor {

    @Override //Handler方法执行完毕后执行的方法
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object obj, Exception ex)
            throws Exception {
        System.out.println("in FirstInterceptor method afterCompletion()");

    }

    @Override //进入Handler方法后,返回ModelAndView之前执行的方法
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object obj, ModelAndView model) throws Exception {
        System.out.println("in FirstInterceptor method postHandle()");

    }

    @Override  //进入Handler方法前执行的方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object obj) throws Exception {
        System.out.println("in FirstInterceptor method preHandle()");
        return true;
    }

}


执行拦截器中的方法后,再执行控制器中的方法

    @RequestMapping("login.action")
    public ModelAndView userLogin() throws Exception{
        System.out.println("in UserController method userLogin()");
        ModelAndView mav = new ModelAndView();
        mav.setViewName("success.jsp");
        System.out.println("userLogin()方法执行完毕!!");
        return mav;

    }


控制台输出的信息一目了然:

信息: FrameworkServlet 'DispatcherServlet': initialization completed in 2096 ms
in FirstInterceptor method preHandle()
in UserController method userLogin()
userLogin()方法执行完毕!!
in FirstInterceptor method postHandle()
in FirstInterceptor method afterCompletion()



第三点:文件上传


一般在项目开发中上传的都是图片,这里演示上传图片的内容

1. 在上传表单页面,输入用户名然后选择图片,选择的图片可以立即显示

这里是通过js代码实现的

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'upfie.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript">
        function showPicture(){
            var path=document.getElementById("upfile").value;
            var first = "C:\\Users\\su\\Pictures\\Saved Pictures\\";
            var second = path.substr(path.lastIndexOf("\\")+1);
            var third = first + second;
            alert(third)
            document.getElementById("showPic").src = third;         
        }
    </script>
  </head>
  <body>
     <form action="upload/upfile.action" method="post" enctype="multipart/form-data">
        用户名:<input type="text" name="userName"/><br>
        <img  src="" id="showPic" width="300" height="200"><br>
        上传文件:<input type="file" name="upfile" id="upfile" onChange="showPicture()"><br>
        <input type="submit" value="Upload">        
     </form>
  </body>
</html>


效果如下图:

这里写图片描述

文件上传的控制器代码如下:


@Controller
@RequestMapping("upload")
public class FileUploadController {
    @RequestMapping("upfile.action")
    public ModelAndView uploadFile(String userName,MultipartFile upfile,HttpServletRequest request)throws Exception{
        System.out.println("in FileUploadController method  uploadFile()");
        System.out.println(userName);
        ModelAndView mav = new ModelAndView();
        //从上传对象中获取文件名
        String fileName = upfile.getOriginalFilename();
        //获取工程路径+上传文件夹+上传文件名
        String filepath = request.getServletContext().getRealPath("/file/"+fileName);
        System.out.println(filepath);
        //创建上传文件对象
        File file = new File(filepath);
        //执行文件上传
        upfile.transferTo(file);

        mav.setViewName("success.jsp");

        return mav;

    }
}


在配置文件中也要配置

<!-- 设置文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件最大为3MB,单位为byte -->
        <property name="maxUploadSize">
            <value>3145728</value>
        </property>
    </bean>


对上面前三点完整的配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 指定自动扫描com.su.controller包下的控制器类 -->
    <context:component-scan base-package="com.su.controller"></context:component-scan>
    <!-- 自动加载注解适配器和映射器 -->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--  视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--  配置jsp路径的前缀
        <property name="prefix" value="/result/" />-->
        <!--  配置jsp路径的后缀
        <property name="suffix" value=".jsp" />-->
    </bean> 

    <!-- 配置SpringMVC的拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/login.action"/>
            <bean class="com.su.interceptor.FirstInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- 设置文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件最大为3MB,单位为byte -->
        <property name="maxUploadSize">
            <value>3145728</value>
        </property>
    </bean>
</beans>



第四点:Mybatis访问数据库


Mybatis不同于Hibernate可以自动建表,Mybatis需要手动在数据库中建好表,然后再访问。

下面介绍对Student表的数据库操作

Student.java

package com.su.domain;

public class Student {
    private Integer stuId;
    private String stuName;
    private String stuGender;
    private Integer stuAge;
    private Integer classesId;
    public Integer getClassesId() {
        return classesId;
    }
    public void setClassesId(Integer classesId) {
        this.classesId = classesId;
    }
    public Integer getStuId() {
        return stuId;
    }
    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public String getStuGender() {
        return stuGender;
    }
    public void setStuGender(String stuGender) {
        this.stuGender = stuGender;
    }
    public Integer getStuAge() {
        return stuAge;
    }
    public void setStuAge(Integer stuAge) {
        this.stuAge = stuAge;
    }
}


对应Student类的配置文件Student.xml如下:

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

<mapper namespace="student">

    <!-- 查询全部 -->
    <select id="findAllStudents" resultType="student">
        select * from student
    </select>

    <!-- 根据id查询 -->
    <select id="findStudentById" parameterType="java.lang.Integer" resultType="student">
        select * from student where stuid = #{value}
    </select>

    <!-- 根据姓名模糊查询 -->
    <select id="findStudentByName" parameterType="java.lang.String" resultType="student">
        select * from student where stuname like '%${value}%'
    </select>

    <!-- 根据姓名和性别查询 -->
    <select id="findStudentByBean" parameterType="student" resultType="student">
        select * from student where stuname like '%${stuName}%' and stugender = #{stuGender}
    </select>

    <!-- 根据条件查找全部数量 -->
    <select id="findStudentToCount" parameterType="student" resultType="java.lang.Integer">
        select count(*) from student where stuname like '%${stuName}%' and stugender = #{stuGender}
    </select>

    <!-- 新增学生信息 -->
    <insert id="addStudent" parameterType="student">
        <selectKey keyProperty="stuId" order="BEFORE" resultType="java.lang.Integer">
            SELECT stu_seq.nextval from dual
        </selectKey>
        insert into student values(#{stuId},#{stuName},#{stuGender},#{stuAge},#{classesId})
    </insert>

    <!-- 更新学生信息 -->
    <update id="updateStudent" parameterType="student">
        update student set stuname=#{stuName},stugender=#{stuGender},stuage=#{stuAge},classesid=#{classesId} where stuid=#{stuId}
    </update>

    <!-- 根据id删除信息 -->
    <delete id="deleteStudent" parameterType="java.lang.Integer">
        delete from student where stuid=#{stuId}
    </delete>

</mapper>


测试类:

package com.su.test;

import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.su.domain.Student;

public class MainTest {

    public static void main(String[] args) {
        try{
            //加载配置文件
            InputStream is = Resources.getResourceAsStream("mybatisconfig.xml");
            //创建SqlSessionFactory对象
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(is);
            //创建SqlSession
            SqlSession ss = ssf.openSession();

            //查询全部数据
//          List<Student> list = ss.selectList("student.findAllStudents");
//          for(Student stu : list){
//              System.out.println(stu.getStuId()+"\t"+stu.getStuName());
//          }

            //根据id查询
            Student stu = ss.selectOne("findStudentById", 2);
            System.out.println(stu.getStuName());

            //根据姓名模糊查询
//          List<Student> list = ss.selectList("findStudentByName", 'r');
//          for(Student stu : list)
//              System.out.println(stu.getStuName());

            //根据姓名和性别查询
//          Student stu = new Student();
//          stu.setStuName("o");
//          stu.setStuGender("男");
//          List<Student> list = ss.selectList("findStudentByBean", stu);
//          for(Student stu1 : list)
//              System.out.println(stu1.getStuName());

            //根据条件查找全部数量
//          Student stu = new Student();
//          stu.setStuName("o");
//          stu.setStuGender("男");
//          Integer count = ss.selectOne("findStudentToCount", stu);
//          System.out.println("共有:"+count+"条记录");

            //新增学员
//          Student stu = new Student();
//          stu.setStuName("小强");
//          stu.setStuGender("女");
//          stu.setStuAge(18);
//          stu.setClassesId(1);
//          int result = ss.insert("addStudent",stu);
//          if(result==1){
//              System.out.println("新增成功");
//              System.out.println(stu.getStuId());
//          }else{
//              System.out.println("新增失败");
//          }

            //更新学生信息
//          Student stu = new Student();
//          stu.setStuId(4);
//          stu.setStuName("susu");
//          stu.setStuGender("男");
//          stu.setStuAge(22);
//          stu.setClassesId(2);
//          int result = ss.update("updateStudent",stu);
//          if(result==1){
//              System.out.println("更新成功");
//              System.out.println(stu.getStuId());
//          }else{
//              System.out.println("更新失败");
//          }

            //根据id删除信息
//          Integer result = ss.delete("deleteStudent", 3);
//          if(result==1){
//              System.out.println("删除成功");
//      
//          }else{
//              System.out.println("删除失败");
//          }

            ss.commit();
            ss.close();     
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}


mybatisconfig.xml配置文件中需要进行一些配置:

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

    <!-- 加载配置文件 -->
    <properties resource="jdbc.properties"></properties>

     <!-- 配置全局参数 -->
     <settings>
        <!-- 打开延迟加载的开关 -->
        <setting name="lazyLoadingEnabled" value="true"/>
        <!-- 将积极加载改为消极加载即按需要加载 -->
        <setting name="aggressiveLazyLoading" value="false"/>
        <!-- 开启二级缓存 -->
        <setting name="cacheEnabled" value="true"/>
    </settings> 

    <typeAliases>
        <!-- 单个类定义别名 type:类型的路径 alias:别名-->
        <!-- <typeAlias type="com.mbd.domain.Student" alias="student"/> -->
        <!-- 指定包名,mybatis自动扫描包中所有实体类,自动定义别名,别名就是类名(首字母大写或小写都可以)-->
         <package name="com.su.domain"/> 
    </typeAliases>

    <!-- 声明数据连接环境 -->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池 
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
                <property name="username" value="school" />
                <property name="password" value="1573" />
            </dataSource>-->

            <dataSource type="POOLED">
                <property name="driver" value="${driverClass}" />
                <property name="url" value="${jdbcUrl}" />
                <property name="username" value="${user}" />
                <property name="password" value="${password}" />
            </dataSource>       
        </environment>
    </environments>

    <!-- 加载映射文件 -->
    <mappers>
        <mapper resource="com/su/domain/Student.xml"/>
    </mappers>
</configuration>


为了代码的可移植性,有数据库链接配置文件jdbc.properties

driverClass=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521:xe
user=school
password=1573


`以上就是今天复习内容,以便日后查看


Author:1573

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ssy03092919

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值