您的位置:首页 > 编程语言 > Java开发

ssm框架搭建详细(spring4+struts2+mybatis3)

2015-02-12 13:45 776 查看
    以前工作中,项目用的是ssm(spring,struts,mbatis)框架,但是自己没有搭建过,最近花了一段时间来整理学习了一下,把最近的收获分给大家,主要是ssm的搭建。

1.首先我们要准备好自己框架所需要的jar包

    1.1 struts2所需jar包:包括整合spring的jar包



   1.2 spring所需的jar包:我这里是把spring的所有核心jar包都考了进来

 


  1.3  mybatis所需要的jar包和其他,链接数据库,log4j,的jar包

 


上面是所需要的jar包,由于是后来才写的博文,有可能还有不全,忘大家多提意见!

2.配置xml配置文件

2.1 mybatis的配置文件内容:mybatis-config.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>
<typeAliases>
<typeAlias alias="userinfo" type="com.gly.model.Userinfo" />
</typeAliases>

<mappers>
<mapper resource="com/gly/dao/userinfoMapping.xml" />
</mappers>

</configuration>


增删改查的操作,userinfoMapping.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"mybatis-3-mapper.dtd">
<mapper namespace="com.gly.dao.IUserinfoDao">

<!-- Result Map -->
<resultMap type="com.gly.model.Userinfo" id="BaseResultMap">
<result property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="sex" column="sex" />
<result property="birthday" column="birthday" jdbcType="TIMESTAMP" />
<result property="insertDate" column="insertDate" jdbcType="TIMESTAMP" />
<result property="message" column="message" jdbcType="CLOB"
javaType="java.lang.String" />
</resultMap>

<!-- 表中所有列 -->
<sql id="Base_Column_List">
id,username,password,sex,birthday,insertDate,message
</sql>

<!-- 1.新增记录,message,,birthday,insertDate,#{message,type=CLOB},#{birthday,jdbcType=DATE},#{insertDate,jdbcType=TIMESTAMP} -->
<insert id="insertUserinfo" parameterType="com.gly.model.Userinfo">
insert into
userinfo(id,username,password,sex,birthday,message,insertDate)
values(#{id},#{username},#{password},#{sex},#{birthday,jdbcType=DATE},#{message,jdbcType=CLOB},sysdate)
</insert>
<!-- 2.查询记录条数count -->
<select id="userCount" parameterType="java.util.Map" resultType="long">
select count(*) from userinfo where 1=1
<if test="sex != null and sex != '' "> and sex = #{sex} </if>
</select>
<!-- 3.分页的查询记录 -->
<select id="selectPage" parameterType="com.gly.model.page.PageModel" resultMap="BaseResultMap">
select <include refid="Base_Column_List" /> from (select t.*,rownum ro from userinfo t where 1=1
<if test="conditions.sex != null and conditions.sex != '' "> and sex = #{conditions.sex} </if>
) where ro between #{begin} and #{end}

</select>
<!-- 4.根据id进行删除 -->
<delete id="deleteById" parameterType="java.lang.String">
delete from userinfo where id = #{id}
</delete>
<!-- 5.根据id查询 -->
<select id="queryById" resultMap="BaseResultMap" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from userinfo where id = #{id}
</select>

<!-- 5.根据id修改记录 -->
<update id="updateById" parameterType="com.gly.model.Userinfo">
update userinfo set
name=#{name},sex=#{sex},birthday=#{birthday},message=#{message}
where
id=#{id}
</update>

<!-- 6.只修改不为空的字段 -->
<update id="updateBySelective" parameterType="com.gly.model.Userinfo">
update userinfo set
<trim suffixOverrides=",">
<if test="username != null  and username != '' ">
username=#{username},
</if>
<if test="sex != null  and sex != '' ">
sex=#{sex},
</if>
<if test="birthday != null">
birthday=#{birthday},
</if>
<if test="message != null  and message != '' ">
message=#{message},
</if>
</trim>
where id=#{id}
</update>

</mapper>


2.2 struts配置文件的内容:struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>

<package name="default" extends="struts-default">
<action name="baseController" class="baseController">
</action>
<action name="insert_*" class="insert" method="{1}">
</action>
</package>

<!-- Struts的html模板:模板内容对你的开发有影响可以改为simple。 -->
<constant name="struts.ui.theme" value="simple"></constant>
</struts>


2.3 spring的配置文件的内容,有详细的注解:applicationContext.xml

!-- <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.gly.service" />
<context:component-scan base-package="com.gly.dao" />

<!-- 配置数据源 1.导入资源文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />

<!-- 数据源1配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />

<!-- 初始化连接大小 <property name="initialSize" value="${initialSize}"></property>
连接池最大数量 <property name="maxActive" value="${maxActive}"></property> 连接池最大空闲
<property name="maxIdle" value="${maxIdle}"></property> 连接池最小空闲 <property
name="minIdle" value="${minIdle}"></property> 获取连接最大等待时间 <property name="maxWait"
value="${maxWait}"></property> -->
</bean>

<!-- 配置事务管理器,注意这里的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事务就没有作用了 -->

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 创建SqlSessionFactory,同时指定数据源 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--configLocation属性指定mybatis的核心配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 自动扫描mapping.xml文件 <property name="mapperLocations" value="classpath:com/dky/distance/staticTable/*.xml"></property> -->
</bean>

<!-- 配置事务的传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="modify*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- 那些类的哪些方法参与事务
我解释一下(* com.z2sci.soa.manager.*.*(..))中几个通配符的含义:
|第一个 * —— 通配 任意返回值类型| |第二个 * —— 通配 包com.z2sci.soa.manager下的任意class| |第三个 * ——
通配 包com.z2sci.soa.manager下的任意class的任意方法| |第四个 .. —— 通配 方法可以有0个或多个参数|
<aop:config>
<aop:pointcut id="allManagerMethod"
expression="execution(* com.dky.distance.staticTable.*.*(..))" />
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice" />
</aop:config>-->

<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--自动检索注入的包-->
<property name="basePackage" value="com.gly.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<import resource="com/gly/spring.xml" />
</beans>


pringle.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"
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
">

<bean id="baseController" class="com.gly.controller.BaseController">
<property name="allservice">
<ref bean="allService"></ref>
</property>
</bean>

<bean id="insert" class="com.gly.controller.Insert" parent="baseController"
scope="prototype">
</bean>
<bean id="pic" class="com.gly.controller.Pic" parent="baseController">
</bean>
</beans>


2.4数据库连接的文件:jdbc.properties,这里要根据我们需要的数据库进行不同的修改,我是使用 的Oracle

db.driver=oracle.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@localhost:1521:orcl
db.username=user1
db.password=user1
</pre><p>2.5 log4j的文件:自己根据情况自己配置</p><pre class="html" name="code">llog4j.rootLogger = debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern = %p  %d{yyyy-MM-dd HH:mm:ss} -- %m -- %l%n

###file logger###
log4j.appender.R = org.apache.log4j.RollingFileAppender
log4j.appender.R.File = d:/logs/lylg.log
log4j.appender.R.MaxFileSize = 1Mb
log4j.appender.R.MaxBackupIndex = 100
log4j.appender.R.layout = org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern =%p  %d{yyyy-MM-dd HH\:mm\:ss} -- %m -- %l%n

log4j.logger.org.springframework=debug,console
log4j.logger.org.apache.ibatis = ERROR
log4j.logger.com.ibatis=ERROR
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=ERROR
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=ERROR
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=ERROR
log4j.logger.java.sql.Connection = ERROR
log4j.logger.java.sql.Statement = ERROR
log4j.logger.java.sql.PreparedStatement = ERROR
log4j.logger.java.sql.ResultSet = ERROR


3. 在数据库中创建我们相应的表:Userinfo

create table USERINFO
(
ID         VARCHAR2(32) not null,
USERNAME   VARCHAR2(20),
PASSWORD   VARCHAR2(20),
SEX        VARCHAR2(2),
INSERTDATE DATE,
MESSAGE    CLOB,
PIC        BLOB,
BIRTHDAY   DATE
)

-- Add comments to the columns
comment on column USERINFO.ID
is 'id';
comment on column USERINFO.USERNAME
is '用户名';
comment on column USERINFO.PASSWORD
is '密码';
comment on column USERINFO.SEX
is '性别';
comment on column USERINFO.INSERTDATE
is '入库时间';
comment on column USERINFO.MESSAGE
is '长数据';
comment on column USERINFO.PIC
is '头像';
comment on column USERINFO.BIRTHDAY
is '生日';



4.编写我们的类

4.1先创建我们的dao接口,这里是利用alldao的思路实现的,所以又一个all到类

public interface IUserinfoDao {

public int insertUserinfo(Userinfo userinfo);
public List<Userinfo> selectPage(PageModel<Userinfo> page);
public long userCount(Map<String,String> pageMap);
public void deleteById(String id);
public Userinfo queryById(String id);
public int updateById(Userinfo userinfo);
public int updateBySelective(Userinfo userinfo);

}
</pre><pre class="java" name="code">@Repository
public class AllDao {

@Autowired
private IUserinfoDao userinfodao;

public IUserinfoDao getUserinfodao() {
return userinfodao;
}

public void setUserinfodao(IUserinfoDao userinfodao) {
this.userinfodao = userinfodao;
}

}


4.2 service类,这里也是利用了all的思想,所以也有allservice的类

@Service
public class UserinfoService {

@Autowired
private AllDao alldao;

public int insertUserinfo(Userinfo user) {
return this.alldao.getUserinfodao().insertUserinfo(user);

}

public long userCount(Map<String, String> pageMap) {
return this.alldao.getUserinfodao().userCount(pageMap);
};

public List<Userinfo> selectPage(PageModel<Userinfo> page) {

return this.alldao.getUserinfodao().selectPage(page);
}

public void deleteById(String id) {

this.alldao.getUserinfodao().deleteById(id);
}
public Userinfo queryById(String id){
return this.alldao.getUserinfodao().queryById(id);
};
public int updateById(Userinfo userinfo){
return this.alldao.getUserinfodao().updateById(userinfo);
};
public int updateBySelective(Userinfo userinfo){
return this.alldao.getUserinfodao().updateBySelective(userinfo);
};
}


@Service
public class AllService {

@Autowired
private UserinfoService userinfoservice;

public UserinfoService getUserinfoservice() {
return userinfoservice;
}

public void setUserinfoservice(UserinfoService userinfoservice) {
this.userinfoservice = userinfoservice;
}

}


4.3 下面就是我们的实现功能,对应的controller,这里有一个base,是用来声明service的,公共使用,所有的类都要继承它。

public class BaseController extends ActionSupport {

private AllService allservice;

public AllService getAllservice() {
return allservice;
}

public void setAllservice(AllService allservice) {
this.allservice = allservice;
}

}

功能的实现类:我这里的代码包括了分页的功能,也是自己写的,有需要的可以看看,要原码的在联系我。

@Transactional
/**
* 操作增删改查
* @author Administrator
*
*/
public class Insert extends BaseController {

cJson cjson = new cJson();
private String jsonString;

public String getJsonString() {
return jsonString;
}

public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}

// 分页model
public PageModel<Userinfo> page;

public String insert() {
try {
JSONObject object = JSONObject.fromObject(jsonString);
String name = object.getString("name");
String password = object.getString("password");
String sex = object.getString("sex");
String id = UUID.randomUUID().toString().replaceAll("-", "");
Date birthday = new SimpleDateFormat("yyyy-MM-dd").parse(object
.getString("birthday"));

String message = object.getString("message");

Userinfo user = new Userinfo(id, name, password, sex, birthday,
new Date(), message);
int ses = this.getAllservice().getUserinfoservice()
.insertUserinfo(user);
if (ses == 1) {
cjson.write("true");
}

} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

public String selectById() {

return null;
}

public String selectPage() {
try {
JSONObject object = JSONObject.fromObject(jsonString);
int gotoPage = object.getInt("gotoPage");
int pageNum = object.getInt("pageNum");
Map<String, String> pageMap = new HashMap<String, String>();
pageMap.put("sex", "男");
int userCount = (int) this.getAllservice().getUserinfoservice()
.userCount(pageMap);

page = new PageModel<Userinfo>(userCount, pageNum, pageMap);
page.setGotoPage(gotoPage);

List<Userinfo> userinfoList = this.getAllservice()
.getUserinfoservice().selectPage(page);
page.setList(userinfoList);
cjson.write(page);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

/**
* 根据id删除
*
* @return
*/
public String deleteById() {

try {
this.getAllservice().getUserinfoservice().deleteById(jsonString);
cjson.write("true");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 根据id查询
*
* @return
*/
public String queryById() {
try {
Userinfo userinfo = this.getAllservice().getUserinfoservice()
.queryById(jsonString);
cjson.write(userinfo);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

public String update() {
try {
JSONObject object = JSONObject.fromObject(jsonString);
String id = object.getString("userId");
String name = object.getString("name");
String password = object.getString("password");
String sex = object.getString("sex");
String bir = object.getString("birthday");
Date birthday = null;
if (bir != null && !bir.equals("")) {
birthday = new SimpleDateFormat("yyyy-MM-dd").parse(bir);

}

String message = object.getString("message");

Userinfo userinfo = new Userinfo(id, name, password, sex, birthday,
new Date(), message);
this.getAllservice().getUserinfoservice()
.updateBySelective(userinfo);
cjson.write("true");
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}


对其中不懂的地方解释:cjson.write()是自己写的,其实是用的json传参,具体类:

public class cJson {
static HttpServletResponse response;
static PrintWriter out;

public void write(String jsonString) throws IOException {

String returnJSONObject = jsonString;
//System.out.println(returnJSONObject);
response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("text/htm;");
out = response.getWriter();

out.print(returnJSONObject);
out.flush();
out.close();

}

public void write(Object jsonObj) throws IOException {

String returnJSONObject = JSONArray.fromObject(jsonObj).toString();
//System.out.println(returnJSONObject);
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("text/htm;");

PrintWriter out = response.getWriter();

out.print(returnJSONObject);
out.flush();
out.close();
}
}


5.下面是页面的功能

<%@ 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 'index.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">
-->
<style type="text/css">
table {
border-collapse: collapse;
}

table td {
border: solid 1px;
border-color: blue;
padding: 0px 0px 0px 10px;
text-align: center;
}

a {
text-decoration: none;
}

.all {
width: 1024px;
}

.show_tab tr td {
width: 340px;
height: 30px;
}
</style>
</head>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
function user(userId, name, password, sex, birthday, message) {
this.userId = userId;
this.name = name;
this.password = password;
this.sex = sex;
this.birthday = birthday;
this.message = message;
}
function insert() {
var action = $("#insertfrom").attr('action');
var userId = $("#userId").val();
var name = $("#name").val();
var sex = $("input:radio[name=sex]:checked").val();
var password = $("#password").val();
var birthday = $("#birthday").val();
var message = $("#message").val();
var userinsert = new user(userId, name, password, sex, birthday,
message);
var jsonString = JSON.stringify(userinsert);
$.ajax({
url : action,
data : {
"jsonString" : jsonString
},
type : 'post',
async : false,
/*complete : function(request, dArra) {
if (request.responseText == 'true') {
alert("成功!");
} else if(request.responseText == 'flase'){
error(request);//失败时的处理方法
}

}*/
success : function(data) {
alert("成功!");

},
error : function(data) {
error(data);//失败时的处理方法
}
});

}

function error(data) {
var result = data.responseText;
if (result != null && result != '') {//后台异常时,并在后台捕获
var url = getRootPath() + "/error.jsp";//获取工程路径
location.href = url;
//$(document.body).html(result);
} else {//后台异常,且没有被捕获
var url = getRootPath() + "/error.jsp";//获取工程路径
location.href = url;
}
}

//js获取项目根路径,如:http://localhost:8099/UniqueduHome
function getRootPath() {
//获取当前网址,如: http://localhost:8099/UniqueduHome/view/error/notAuthorize.jsp var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: UniqueduHome/view/error/notAuthorize.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8099 var localhostPaht = curWwwPath.substring(0, pos);
//获取带"/"的项目名,如:/UniqueduHome
var projectName = pathName.substring(0,
pathName.substr(1).indexOf('/') + 1);
return (localhostPaht + projectName);
}

$(document).ready(function() {
//回车事件,添加
$(document).keydown(function(event) {
if (event.keyCode == 13) {
insert();
}
});
pageNum();
select(1);
});

function pageParameter(gotoPage, pageNum) {
this.gotoPage = gotoPage;
this.pageNum = pageNum;
}
function select(gotoPage) {
//分页的方法:调用的时候传一个参数,要去的页数沟通gotoPage
//对gotopage的最大和最小控制
if (gotoPage < 1) {
gotoPage = 1;
}
//每页的条数
var pageNum = $("#pagenum  option:selected").text();
var userPage = new pageParameter(gotoPage, pageNum);
var jsonString = JSON.stringify(userPage);
$.ajax({
url : "insert_selectPage.action",
data : {
"jsonString" : jsonString
},
type : 'post',
async : false,
success : function(data) {
//var pageModel = JSON.parse(request.responseText);
var pageModel = JSON.parse(data);
zhuiJia(pageModel[0]);

},
error : function(data) {
error(data);//失败时的处理方法
}
});
}
function zhuiJia(pageModel) {
var showTab = $("#show_tab");
var showTr = showTab.find(" tr");
for ( var i = 1; i < showTr.length; i++) {
showTr.eq(i).remove();
}

for ( var i = 0; i < pageModel.list.length; i++) {
var unitOne = $("<tr height='30px'><td class='bacx'>"
+ (Number(i) + Number(1))
+ "</td><td class='bacx'>"
+ pageModel.list[i].username
+ "</td><td class='bacx'>"
+ pageModel.list[i].sex
+ "</td><td class='bacx'><a href='javascript:' id='updateA'>修改</a> |  "
+ "<a href='javascript:' id='deleteA'>删除</a></td></tr>");
//这里直接在unitOne赋值会出现由于符号导致添加的连接有问题
//所以要动态添加
var updateA = unitOne.children().last().find("#updateA");

var deleteA = unitOne.children().last().find("#deleteA");
updateA.attr("href", "javascript:queryById('"
+ pageModel.list[i].id + "')");

//这里用onclick不起作用,不知道原因,所以改为href
deleteA.attr("href", "javascript:deleteSql('"
+ pageModel.list[i].id + "');");

showTab.append(unitOne);

}
$("#gotoPage").val(pageModel.gotoPage);
$("#pageIndex").val(pageModel.gotoPage);
$("#pageCount").text(pageModel.pageCount);
}
//查询条件使用
function gotoPage(condition) {
var gotopage = $("#pageIndex").val();
if (condition == "begin") {
gotopage = 1;
} else if (condition == "last") {
gotopage = Number(gotopage) - Number(1);
} else if (condition == "next") {
gotopage = Number(gotopage) + Number(1);
} else if (condition == "end") {
gotopage = $("#pageCount").text();
} else if (condition == "input") {
gotopage = $("#gotoPage").val();
}
select(gotopage);
}
//下拉框改变的方法
function pageNum() {
var pageSelect = $("#pagenum");
pageSelect.change(function() {
select(1);
});
}
function deleteSql(id) {
if (confirm('确定删除?')) {
$.ajax({
url : "insert_deleteById.action",
data : {
"jsonString" : id
},
type : 'post',
async : false,
complete : function(request, dArra) {
if (request.responseText == 'true') {
select(1);
//$(obj).parent().parent().remove();
} else {
error(data);//失败时的处理方法
}
}
});
} else {
alert('取消');
}

}
function queryById(id) {
$.ajax({
url : "insert_queryById.action",
data : {
"jsonString" : id
},
type : 'post',
async : false,
success : function(data) {
var userinfo = JSON.parse(data)[0];
$("#userId").val(userinfo.id);
$("#name").val(userinfo.username);
$("input:radio[name=sex][value=" + userinfo.sex + "]").attr(
"checked", true);
$("#message").val(userinfo.message);

},
error : function(data) {
error(data);//失败时的处理方法
}

});
}
function update() {
var name = $("#name").val();
var sex = $("input:radio[name=sex]:checked").val();
var userId = $("#userId").val();
var password = $("#password").val();
var birthday = $("#birthday").val();
var message = $("#message").val();
var userinsert = new user(userId, name, password, sex, birthday,
message);
var jsonString = JSON.stringify(userinsert);
$.ajax({
url : "insert_update.action",
data : {
"jsonString" : jsonString
},
type : 'post',
async : false,
/*complete : function(request, dArra) {
if (request.responseText == 'true') {
alert("成功!");
} else if(request.responseText == 'flase'){
error(request);//失败时的处理方法
}

}*/
success : function(data) {
alert("成功!");

},
error : function(data) {
error(data);//失败时的处理方法
}
});

}
</script>
<body>
<div class="all">
<div>
<form action="insert_insert.action" method="post" id="insertfrom"
enctype="multipart/form-data">
<table style="width:100%;">
<tr>
<td style="width:10%; height:40px;">username:</td>
<td style="width:20%; height:40px;"><input type="hidden"
value="" id="userId" /> <input type="text" name="name" id="name" />
</td>
<td style="width:10%; height:40px;">password:</td>
<td style="width:20%; height:40px;"><input type="password"
name="password" id="password" /></td>
<td style="width:10%; height:40px;">sex:</td>
<td style="width:29%; height:40px;"><input type="radio"
name="sex" value="男" />男  <input type="radio" name="sex"
value="女" />女</td>

</tr>
<tr>
<td style="width:10%; height:40px;">birthday:</td>
<td style="width:20%; height:40px;"><input type="text"
name="birthday" id="birthday" /></td>
<td style="width:10%; height:40px;">CLOB:</td>
<td style="width:29%; height:50px;"><textarea rows="3"
cols="30" name="message" id="message"></textarea>
</td>
<td colspan="2" style="width:29%; height:40px;"><input
type="button" onclick="insert()" value="保存"> <input
type="button" onclick="update()" value="修改">
</td>
</tr>
</table>
</form>
<form action="pic_insertPic.action" method="post" id="insertfrom"
enctype="multipart/form-data">
<input type="hidden" value="" id="userId" name="userId"/>
<table style="width:100%;">
<tr>
<td style="width:20%; height:40px;">文件:</td>
<td style="width:50%; height:40px;"><input type="file"
name="photo" id="photo" /></td>

<td style="width:20%; height:40px;"><input type="submit"
value="保存">
</td>
</tr>
</table>
</form>
</div>
<div>
<table class="show_tab" id="show_tab">
<tr>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>操作</td>
</tr>
<tr>
<td>name</td>
<td>男</td>
<td><a href="#">修改</a><a href="#">删除</a>
</td>
</tr>
</table>
</div>
<div
style="width:100%; height:35px; background: silver; line-height: 35px; color:blue;">
<a href="javascript:gotoPage('begin');">首页<a /> 
<a href="javascript:gotoPage('last');">上一页<a/> 
<a href="javascript:gotoPage('next');" >下一页<a/> 
<a href="javascript:gotoPage('end');">末尾</a> | 
<input type="hidden" value="" id="pageIndex">
<input type="text" style="width:40px;" id="gotoPage" value="" /> / <span id="pageCount">1</span>页
<a href="javascript:gotoPage('input');" >跳转</a> | 每页
<select id="pagenum">
<option>10</option>
<option>20</option>
<option>50</option>
<option>100</option>
</select>条
</div>
</div>
</body>
</html>


如有需要下载代码的,可加群:399846037 里面有上传,希望互相学习。




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ssm spring struts2 mybatis