java框架--spring+mybatis+springmvc+ajax

Posted 周无极

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java框架--spring+mybatis+springmvc+ajax相关的知识,希望对你有一定的参考价值。

 

 

 

 

 

 

package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.ResponseBody;

import com.page.PageUtil;
import com.pojo.BlogUsers;
import com.service.impl.BlogUsersServiceImpl;
@Controller
public class BlogUsersController {
    @Autowired
    private BlogUsersServiceImpl service;
    
    @RequestMapping("login.do")
    public String login(HttpServletRequest request,BlogUsers blogUsers){
        if(blogUsers!=null){
            System.out.println("登录param success");
            BlogUsers login=service.login(blogUsers);
            request.getSession().setAttribute("login", login);
        }else{
            System.out.println("登录param fail");
            
        }
        
        return "index.jsp";
    }
    
    @RequestMapping("findPage.do")
    @ResponseBody
    public Map<String, Object> findPage(PageUtil pageutil){
        
        Map<String, Object> map=new HashMap<String, Object>();
        int pageno=1;
        int pagesize=3;
        int totalcount=service.getTotalCount();
        
        Integer no=pageutil.getPageno();
        //第二次
        if(no!=null){
            pageno=no;
        }
        pageutil=new PageUtil(pageno, pagesize, totalcount);
        List<BlogUsers> bloglist=service.findPage(pageutil);
        map.put("bloglist", bloglist);
        map.put("pageutil", pageutil);
        
        return map;
    }
    
    @RequestMapping("save.do")
    public String save(HttpServletRequest request,BlogUsers blogUsers){
        System.out.println("save blogUsers:"+blogUsers);
        BlogUsers login=(BlogUsers) request.getSession().getAttribute("login");
        System.out.println("login:"+login);
        blogUsers.setUserid(login.getUserid());
        service.saveBlog(blogUsers);
        return "index.jsp";
    }
    @RequestMapping("delete.do")
    public String delete(Integer id){
        service.deleteById(id);
        return "index.jsp";
    }
    
    @RequestMapping("findbyid.do")
    public String findbyid(Integer id,HttpServletRequest request){
        BlogUsers blog=service.findById(id);
        request.setAttribute("blog", blog);
        return "update.jsp";
    }
    
    @RequestMapping("update.do")
    public String update(HttpServletRequest request,BlogUsers blogUsers){
        System.out.println("update blogUsers:"+blogUsers);
        BlogUsers login=(BlogUsers) request.getSession().getAttribute("login");
        System.out.println("login:"+login);
        blogUsers.setUserid(login.getUserid());
        service.updateBlog(blogUsers);
        return "index.jsp";
    }

}
BlogUsersController
package com.mapper;

import java.util.List;

import com.page.PageUtil;
import com.pojo.BlogUsers;

public interface BlogUsersMapper {
    /**
     * 分页查询
     * @param pageutil
     * @return
     */
    List<BlogUsers> findPage(PageUtil pageutil);
    /**
     * 根据id查询
     * @param id
     * @return
     */
    BlogUsers findById(Integer id);
    /**
     * 登录
     * @param id
     * @return
     */
    BlogUsers login(BlogUsers blogUsers);
    /**
     * 查询总条数
     * @return
     */
    Integer getTotalCount();
    /**
     * 保存
     * @param blogUsers
     * @return
     */
    Integer saveBlog(BlogUsers blogUsers);
    /**
     * 添加
     * @param blogUsers
     * @return
     */
    Integer updateBlog(BlogUsers blogUsers);
    /**
     * 删除
     * @param blogUsers
     * @return
     */
    Integer deleteById(Integer id);
    
    

}
BlogUsersMapper
<?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="com.mapper.BlogUsersMapper">
   <select id="findPage" parameterType="com.page.PageUtil" resultType="com.pojo.BlogUsers">
       <![CDATA[
      select * from
        (
        select rownum r,b.*,username,nickname,mobile,address 
        from users u,blog b
        where u.id=b.userid and rownum<=#{endrow}
        ) t
        where t.r>#{startrow}
       ]]>
   </select>
   <select id="login"  resultType="com.pojo.BlogUsers" parameterType="com.pojo.BlogUsers">
      select u.id userid,username,password
        from users u
        where username=#{username} and password=#{password}
   </select>
   
   <select id="findById" resultType="com.pojo.BlogUsers" parameterType="Integer">
      select b.*,username,nickname,mobile,address 
        from users u,blog b
        where u.id=b.userid and b.id=#{id}
   </select>
   
   <select id="getTotalCount" resultType="Integer">
       select count(*) from blog 
   </select>
   
   <insert id="saveBlog" parameterType="com.pojo.BlogUsers">
    insert into blog(id,content,publishtime,userid) values(3,#{content},#{publishtime},#{userid})
   </insert>
   
   <update id="updateBlog" parameterType="com.pojo.BlogUsers">
      update blog set content=#{content},publishtime=#{publishtime},userid=#{userid} where id=#{id}
   </update>
   
   <delete id="deleteById" parameterType="Integer">
     delete from  blog where id=#{id}
   </delete>
</mapper>
BlogUsersMapper.xml
package com.page;


/**
 * 分页工具类
 */
public class PageUtil {
    private Integer pageno;
    private Integer pagesize;
    private Integer totalcount;
    private Integer totalpage;
    private Integer startrow;
    private Integer endrow;
    
    
    public PageUtil() {
    }
    
    public PageUtil(Integer pageno, Integer pagesize, Integer totalcount) {
        this.pageno = pageno;
        this.pagesize = pagesize;
        this.startrow=(pageno-1)*pagesize;
        this.endrow=pageno*pagesize;
        this.totalcount = totalcount;
        this.totalpage=totalcount%pagesize==0?totalcount/pagesize:totalcount/pagesize+1;
    }

    public Integer getPageno() {
        return pageno;
    }
    public void setPageno(Integer pageno) {
        this.pageno = pageno;
    }
    public Integer getPagesize() {
        return pagesize;
    }
    public void setPagesize(Integer pagesize) {
        this.pagesize = pagesize;
    }
    public Integer getTotalcount() {
        return totalcount;
    }
    public void setTotalcount(Integer totalcount) {
        this.totalcount = totalcount;
    }
    public Integer getTotalpage() {
        return totalpage;
    }
    public void setTotalpage(Integer totalpage) {
        this.totalpage = totalpage;
    }
    public Integer getStartrow() {
        return startrow;
    }
    public void setStartrow(Integer startrow) {
        this.startrow = startrow;
    }
    public Integer getEndrow() {
        return endrow;
    }
    public void setEndrow(Integer endrow) {
        this.endrow = endrow;
    }

    

    
}
PageUtil
package com.pojo;

import java.io.Serializable;
import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

/**
 * 多方:多对一
 * 多方:配置对象
 * @author pc
 *
 */
public class BlogUsers implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String content;
    
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date publishtime;
    
    private Integer userid; //用户编号
    private String username; //用户名
    private String password; //用户密码
    private Integer age; //年龄
    private Integer sex; //性别
    private String nickname; //昵称
    private String mobile; //手机
    private String address; //地址
    private Integer supper; //是否是管理员
    private String picpath;  //头像名称
    

    
    public BlogUsers(String content, Date publishtime, Integer userid) {
        this.content = content;
        this.publishtime = publishtime;
        this.userid = userid;
    }

    public BlogUsers(String content, Date publishtime, Integer userid,
            String username, String password, Integer age, Integer sex,
            String nickname, String mobile, String address, Integer supper,
            String picpath) {
        this.content = content;
        this.publishtime = publishtime;
        this.userid = userid;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.nickname = nickname;
        this.mobile = mobile;
        this.address = address;
        this.supper = supper;
        this.picpath = picpath;
    }

    public BlogUsers(Integer id, String content, Date publishtime,
            Integer userid, String username, String password, Integer age,
            Integer sex, String nickname, String mobile, String address,
            Integer supper, String picpath) {
        this.id = id;
        this.content = content;
        this.publishtime = publishtime;
        this.userid = userid;
        this.username = username;
        this.password = password;
        this.age = age;
        this.sex = sex;
        this.nickname = nickname;
        this.mobile = mobile;
        this.address = address;
        this.supper = supper;
        this.picpath = picpath;
    }

    public BlogUsers() {
    }
    
    

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getPublishtime() {
        return publishtime;
    }

    public void setPublishtime(Date publishtime) {
        this.publishtime = publishtime;
    }

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getSupper() {
        return supper;
    }

    public void setSupper(Integer supper) {
        this.supper = supper;
    }

    public String getPicpath() {
        return picpath;
    }

    public void setPicpath(String picpath) {
        this.picpath = picpath;
    }

    @Override
    public String toString() {
        return "BlogUsers [address=" + address + ", age=" + age + ", content="
                + content + ", id=" + id + ", mobile=" + mobile + ", nickname="
                + nickname + ", password=" + password + ", picpath=" + picpath
                + ", publishtime=" + publishtime + ", sex=" + sex + ", supper="
                + supper + ", userid=" + userid + ", username=" + username
                + "]";
    }
    

}
BlogUsers
package com.service;

import java.util.List;

import com.page.PageUtil;
import com.pojo.BlogUsers;

public interface BlogUsersService {
    /**
     * 分页查询
     * @param pageutil
     * @return
     */
    List<BlogUsers> findPage(PageUtil pageutil);
    /**
     * 根据id查询
     * @param id
     * @return
     */
    BlogUsers findById(Integer id);
    /**
     * 查询总条数
     * @return
     */
    Integer getTotalCount();
    /**
     * 保存
     * @param blogUsers
     * @return
     */
    Integer saveBlog(BlogUsers blogUsers);
    /**
     * 添加
     * @param blogUsers
     * @return
     */
    Integer updateBlog(BlogUsers blogUsers);
    /**
     * 删除
     * @param blogUsers
     * @return
     */
    Integer deleteById(Integer id);
    
    /**
     * 登录
     * @param id
     * @return
     */
    BlogUsers login(BlogUsers blogUsers);

}
BlogUsersService
package com.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mapper.BlogUsersMapper;
import com.page.PageUtil;
import com.pojo.BlogUsers;
import com.service.BlogUsersService;
@Service
@Transactional
public class BlogUsersServiceImpl implements BlogUsersService {
    @Autowired(required=true)
    private BlogUsersMapper mapper;
    
    public Integer deleteById(Integer id) {
        // TODO Auto-generated method stub
        return mapper.deleteById(id);
    }

    public BlogUsers findById(Integer id) {
        // TODO Auto-generated method stub
        return mapper.findById(id);
    }

    public List<BlogUsers> findPage(PageUtil pageutil) {
        // TODO Auto-generated method stub
        return mapper.findPage(pageutil);
    }

    public Integer getTotalCount() {
        // TODO Auto-generated method stub
        return mapper.getTotalCount();
    }

    public Integer saveBlog(BlogUsers blogUsers) {
        // TODO Auto-generated method stub
        return mapper.saveBlog(blogUsers);
    }

    public Integer updateBlog(BlogUsers blogUsers) {
        // TODO Auto-generated method stub
        return mapper.updateBlog(blogUsers);
    }

    public BlogUsers login(BlogUsers blogUsers) {
        // TODO Auto-generated method stub
        return mapper.login(blogUsers);
    }

}
BlogUsersServiceImpl
--创建用户信息表
--编号,用户名,密码,年龄,性别,昵称,手机,地址,管理员,图像地址
create table users
(
  id number(10) primary key,
  username varchar2(20) not null,
  password varchar2(40) not null,
  age number(10) not null,
  sex number(10) not null,
  nickname varchar2(20) not null,
  mobile varchar2(15) not null,
  address varchar2(50) not null,
  supper number(10) not null,
  picpath varchar2(100) not null
);


select * from blog

--创建微博表
--编号,内容,发布时间,用户编号
create table blog
(
  id number(10) primary key,
  content varchar2(1000) not null,
  publishtime date not null,
  userid number(10) references users(id)
);

--创建序列
create sequence seq_users;
create sequence seq_blog;

--插入数据
insert into users
(
id,username,password,age,sex,nickname,
mobile,address ,supper,picpath
) 
values
(seq_users.nextval,\'holly\',\'123\',18,0,\'holly上神\',
\'13451802404\',\'雨花台铁心桥新河苑\',0,\'holly.jpg\'); 

insert into users
(
id,username,password,age,sex,nickname,
mobile,address ,supper,picpath
) 
values
(seq_users.nextval,\'倩倩\',\'123\',18,0,\'倩倩上仙\',
\'13451805648\',\'大桥北路\',1,\'qianqian.jpg\'); 

insert into users
(
id,username,password,age,sex,nickname,
mobile,address ,supper,picpath
) 
values
(seq_users.nextval,\'死胖子\',\'123\',28,1,\'死盘子小仙\',
\'13451804869\',\'湖北非洲\',1,\'sipangzi.jpg\'); 

insert into users
(
id,username,password,age,sex,nickname,
mobile,address ,supper,picpath
) 
values
(seq_users.nextval,\'肉肉\',\'123\',38,1,\'肉肉小妖\',
\'13451885697\',\'新街口八条巷\',1,\'rourou.jpg\'); 

insert into users
(
id,username,password,age,sex,nickname,
mobile,address ,supper,picpath
) 
values
(seq_users.nextval,\'戴文\',\'123\',38,1,\'文文上仙\',
\'13451888569\',\'东海瀛洲\',1,\'daiwen.jpg\'); 

commit;

insert into blog
(id,content,publishtime,userid) 
values
(
seq_blog.nextval,\'倩倩上仙已经下凡渡劫失败...\',
to_date(\'2017-01-01\',\'yyyy-MM-dd\'),2
);

insert into blog
(id,content,publishtime,userid) 
values
(
seq_blog.nextval,\'倩倩上仙已经去东海瀛洲去营救...\',
to_date(\'2017-01-02\',\'yyyy-MM-dd\'),2
);

insert into blog
(id,content,publishtime,userid) 
values
(
seq_blog.nextval,\'倩倩上仙中午下凡去看团子...\',
to_date(\'2017-01-03\',\'yyyy-MM-dd\'),2
);

insert into blog
(id,content,publishtime,userid) 
values
(
seq_blog.nextval,\'倩倩上仙中午已去十里桃源...\',
to_date(\'2017-01-04\',\'yyyy-MM-dd\'),2
);

insert into blog
(id,content,publishtime,userid) 
values
(
seq_blog.nextval,\'死胖子小仙已经去了诛仙台...\',
to_date(\'2017-01-05\',\'yyyy-MM-dd\'),3
);
commit;
select * from
(
select rownum r,b.*,username,nickname,mobile,address 
from users u,blog b
where u.id=b.userid and rownum<=#{endrow}
) t
where t.r>#{startrow}

select rownum r,b.*,username,nickname,mobile,address 
from users u,blog b
where u.id=b.userid and b.id=#{id}


select count(*) from users u,blog b where u.id=b.userid
blog.sql
$(function(){
    findpage(1);
    
    //动态绑定只有1.8.3 有效
    $(".page").live("click",function(){
        var pageno=parseInt($("#pageno").text());
        var totalpage=parseInt($("#totalpage").text());
        var apagetext=$(this).text();
        if(apagetext=="首页"){
            pageno=1;
        }else if(apagetext=="上一页"){
            if(pageno>1){
                pageno=pageno-1;
            }else{
                alert("已经是第一页!");
                return;
            }
        }else if(apagetext=="下一页"){
            if(pageno<totalpage){
                pageno=pageno+1;
            }else{
                alert("已经是最后一页!");
                return;
            }
        }else if(apagetext=="末页"){
                pageno=totalpage;
        }  
        
        //ajax回调
        findpage(pageno);
    });
    
});

function findpage(pageno){
    $.ajax({
        url:"findPage.do",
        type:"post",
        data:{"pageno":pageno},
        dataType:"json",
        async:true,
        success:function(obj){
            $("table").html("");
            var str="<tr><td>编号</td><td>昵称</td><td>手机</td><td>内容</td><td>发布时间</td><td>操作</td></tr>";
            $.each(obj.bloglist,function(i){
                str+="<tr>                                                        ";
                str+="  <td>"+obj.bloglist[i].id+"</td>                           ";
                str+="  <td>"+obj.bloglist[i].nickname+"</td>                     ";
                str+="  <td>"+obj.bloglist[i].mobile+"</td>                       ";
                str+="  <td>"+obj.bloglist[i].content+"</td>                      ";
                str+="  <td>"+obj.bloglist[i].publishtime+"</td>                  ";
                str+="  <td>                                                      ";
                str+="    <a href=\'findbyid.do?id="+obj.bloglist[i].id+"\'>修改</a>  ";
                str+="    &nbsp;|&nbsp;                                           ";
                str+="    <a href=\'delete.do?id="+obj.bloglist[i].id+"\'>删除</a>    ";
                str+="  </td>                                                     ";
                str+="</tr>                                                       ";
            });
            $("table").append(str);
            
            $("div").html("");
            var pagestr="第<span id=\'pageno\'>"+obj.pageutil.pageno+"</span>/<span id=\'totalpage\'>"+obj.pageutil.totalpage+"</span>页&nbsp";
               pagestr+="<a href=\'javascript:void(0);\' class=\'page\'>首页</a>&nbsp;                                                           ";
               pagestr+="<a href=\'javascript:void(0);\' class=\'page\'>上一页</a>&nbsp;                                                          ";
               pagestr+="<a href=\'javascript:void(0);\' class=\'page\'>下一页</a>&nbsp;                                                          ";
               pagestr+="<a href=\'javascript:void(0);\' class=\'page\'>末页</a>&nbsp;                                                           ";
               pagestr+="共<span id=\'totalcount\'>"+obj.pageutil.totalcount+"</span>条                                                    ";
               
                $("div").append(pagestr);
                 
                
                
            
        },
        error:function(){
            alert("error");
        }
    });
}
index.js
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:aop="http://www.springframework.org/schema/aop" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
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.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd 
">
<!-- 1.全局扫描包 -->
<context:component-scan base-package="com"/>

<!-- 2.mvc注解驱动 -->
<mvc:annotation-driven/>

<!-- 3.驱动管理数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
    <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"

以上是关于java框架--spring+mybatis+springmvc+ajax的主要内容,如果未能解决你的问题,请参考以下文章

java高并发框架 SSM框架 详细整合教程(Spring+SpringMVC+MyBatis)

java框架--spring+mybatis 注解整合

java高并发框架 SSM框架 详细整合教程(Spring+SpringMVC+MyBatis)

不学mybatis直接学spring boot

JAVA框架 Spring 和Mybatis整合

Mybatis源码 Mybatis是如何与spring框架整合的