Ssh2工程:
1. 新建web project
2. 拷贝jar包到lib
3.创建hibernate连接
工程右击->MyEclipse->AddHibernate Capabilities
发现src下生成hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse HibernateTools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@202.204.105.151:1521:orcl</property>
<property name="connection.username">cugbdemo</property>
<property name="connection.password">cugbdemo</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="myeclipse.connection.profile">oracleDB151</property>
</session-factory>
</hibernate-configuration>
4. 创建po(也可反向工程生成)
修改jre system library:
在cn.cugb.po包中创建民族po:Mzs.java
package cn.cugb.po;
public classMzs implementsjava.io.Serializable {
private Long id;
private String name;
public Mzs() {
super();
}
public Mzs(Long id, Stringname) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在cn.cugb.po包中创建学生po:Students.java
package cn.cugb.po;
public classStudents implements java.io.Serializable {
private Long id;
private String xh;
private String xm;
private String zjh;
private String csrq;
private String xb;
private String nj;
private String xy;
private String zy;
private String pycc;
private Mzs mzs;
public Students() {
super();
}
public Students(Long id,String xh, String xm, String zjh, String csrq,
Stringxb, String nj, String xy, String zy, String pycc, Mzs mzs) {
super();
this.id = id;
this.xh = xh;
this.xm = xm;
this.zjh = zjh;
this.csrq = csrq;
this.xb = xb;
this.nj = nj;
this.xy = xy;
this.zy = zy;
this.pycc = pycc;
this.mzs = mzs;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getXm() {
return xm;
}
public void setXm(String xm) {
this.xm = xm;
}
public String getZjh() {
return zjh;
}
public void setZjh(String zjh) {
this.zjh = zjh;
}
public String getCsrq() {
return csrq;
}
public void setCsrq(String csrq) {
this.csrq = csrq;
}
public String getXb() {
return xb;
}
public void setXb(String xb) {
this.xb = xb;
}
public String getNj() {
return nj;
}
public void setNj(String nj) {
this.nj = nj;
}
public String getXy() {
return xy;
}
public void setXy(String xy) {
this.xy = xy;
}
public String getZy() {
return zy;
}
public void setZy(String zy) {
this.zy = zy;
}
public String getPycc() {
return pycc;
}
public void setPycc(String pycc) {
this.pycc = pycc;
}
public Mzs getMzs() {
return mzs;
}
public void setMzs(Mzs mzs) {
this.mzs = mzs;
}
}
创建相应的Mzs.hbm.xml
生成的Mzs.hbm.xml为:
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.cugb.po.Mzs" table="MZS" schema="CUGBDEMO">
<id name="id"type="java.lang.Long">
<column name="ID" precision="10"scale="0" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="10"/>
</property>
</class>
</hibernate-mapping>
同理创建Students.hbm.xml
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.cugb.po.Students" table="STUDENTZD" schema="CUGBDEMO">
<id name="id"type="java.lang.Long">
<column name="ID" precision="10"scale="0" />
<generator class="increment" />
</id>
<property name="xh" type="java.lang.String">
<column name="XH"length="20" />
</property>
<property name="xm"type="java.lang.String">
<column name="XM"length="20" />
</property>
<property name="zjh"type="java.lang.String">
<column name="ZJH"length="18" />
</property>
<property name="csrq"type="java.lang.String">
<column name="CSRQ"length="10" />
</property>
<property name="xb"type="java.lang.String">
<column name="XB"length="20" />
</property>
<property name="nj"type="java.lang.String">
<column name="NJ"length="4" />
</property>
<property name="xy"type="java.lang.String">
<column name="XY"length="60" />
</property>
<property name="zy"type="java.lang.String">
<column name="ZY"length="100" />
</property>
<property name="pycc"type="java.lang.String">
<column name="PYCC"length="2" />
</property>
<many-to-one name="mzs"class="cn.cugb.po.Mzs" update="false" insert="false"fetch="select">
<column name="ID"precision="10" scale="0"unique="true" />
</many-to-one>
</class>
</hibernate-mapping>
5. 创建dao
在cn.cugb.dao中创建StudentsDAO.java
package cn.cugb.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import cn.common.core.BaseHibernateDAO;
import cn.cugb.po.Students;
@Repository
public classStudentsDAO extends BaseHibernateDAO<Students, Long> {
private static final Log log = LogFactory.getLog(StudentsDAO.class);
public void save(StudentstransientInstance) {
log.debug("saving Students instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
}catch(RuntimeException re) {
log.error("save failed",re);
throw re;
}
}
public void delete(StudentspersistentInstance) {
log.debug("deleting Studentszd instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
}catch(RuntimeException re) {
log.error("delete failed",re);
throw re;
}
}
public StudentsfindById(java.lang.Long id) {
log.debug("getting Studentszd instance with id: " + id);
try {
Studentsinstance = (Students) getHibernateTemplate().get(
"cn.cugb.po.Students",id);
return instance;
}catch(RuntimeException re) {
log.error("get failed",re);
throw re;
}
}
}
在cn.cugb.dao中创建MzsDAO.java
package cn.cugb.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;
import cn.common.core.BaseHibernateDAO;
import cn.cugb.po.Mzs;
@Repository
public classMzsDAO extendsBaseHibernateDAO<Mzs, Long>{
private static final Log log = LogFactory.getLog(MzsDAO.class);
public void save(MzstransientInstance) {
log.debug("saving Mzs instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
}catch(RuntimeException re) {
log.error("save failed",re);
throw re;
}
}
public void delete(MzspersistentInstance) {
log.debug("deleting Mzs instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
}catch(RuntimeException re) {
log.error("delete failed",re);
throw re;
}
}
public MzsfindById(java.lang.Long id) {
log.debug("getting Mzs instance with id: " + id);
try {
Mzs instance =(Mzs)getHibernateTemplate().get("cn.cugb.po.Mzs", id);
return instance;
}catch(RuntimeException re) {
log.error("get failed",re);
throw re;
}
}
}
6. Add struts capabilities
工程右击->MyEclipse->AddStruts Capabilities
发现生成struts.xml,并添加相关内容
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//ApacheSoftware Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.custom.i18n.resources" value="applicationResource"></constant>
<constant name="struts.objectFactory.spring.autoWire"value="type"> </constant>
<constant name="struts.objectFactory" value="spring"> </constant>
<constant name="struts.devMode" value="true"> </constant>
</struts>
web.xml文件变为
<?xml version="1.0"encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></web-app>
修改后为:
<?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:jsp="http://java.sun.com/xml/ns/javaee/jsp"
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>studentDemo</display-name>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>studentDemo.root</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml,classpath:org/codehaus/xfire/spring/xfire.xml</param-value>
</context-param>
<context-param>
<param-name />
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>60000</param-value>
</context-param>
<context-param>
<param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>org.jasig.cas.client.session.SingleSignOutHttpSessionListener</listener-class>
</listener>
<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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter>
<filter-name>campusScopeFilter</filter-name>
<filter-class>cn.common.filter.CampusScopeFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>campusScopeFilter</filter-name>
<url-pattern>*.shtml</url-pattern>
</filter-mapping>
<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInView</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>cn.common.filter.MyStrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>XFireServlet</servlet-name>
<servlet-class>org.codehaus.xfire.spring.XFireSpringServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/myTag</taglib-uri>
<taglib-location>/WEB-INF/myTag-html.tld</taglib-location>
</taglib>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
</jsp-property-group>
</jsp-config>
</web-app>
7. Add Spring capabilities
工程右击->MyEclipse->AddSpring Capabilities
发现生成applicationContext.xml
<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
</bean>
</beans>
修改后为:
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="cn" />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" class="com.jolbox.bonecp.BoneCPDataSource"destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxConnectionsPerPartition"value="20"/>
<property name="minConnectionsPerPartition"value="5"/>
<property name="partitionCount"value="3"/>
<property name="acquireIncrement"value="10"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">none</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath*:cn/cugb/po/**/*.hbm.xml</value>
</list>
</property>
<property name="lobHandler">
<ref bean="lobHandler" />
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.DefaultLobHandler"lazy-init="true"/>
<bean id="txManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- methods starting with 'save', 'update' or'remove' use the default
transactionsettings -->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="remove*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="merge*" propagation="REQUIRED"/>
<!-- other methods are set to read only -->
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor pointcut="execution(* cn.cugb.service.*.*.*(..))"advice-ref="txAdvice" />
<aop:advisor pointcut="execution(* cn.common.core.BaseService.*(..))"advice-ref="txAdvice" />
</aop:config>
</beans>
8. 拷贝相关文件
拷贝jdbc.properties:
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@202.204.105.151:1521/orcl
jdbc.username=cugbdemo
jdbc.password=cugbdemo
cpool.checkoutTimeout=5000
cpool.minPoolSize=10
cpool.initialPoolSize=5
cpool.maxPoolSize=50
cpool.maxIdleTime=7200
cpool.maxIdleTimeExcessConnections=1800
cpool.acquireIncrement=3
拷贝log4j.properties(非必须)
log4j.rootLogger=warn,CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.Target=System.out
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=${student.root}/WEB-INF/student.log
log4j.appender.FA.Append=true
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss}[%-5p][%c{1}] - %m%n
log4j.logger.org.hibernate=error
9. 创建studentsService
在cn.cugb.service创建studentsService.java
package cn.cugb.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.common.core.BaseService;
import cn.cugb.dao.StudentsDAO;
import cn.cugb.po.Students;
@Service
public classstudentsService extends BaseService<Students, Long> {
private StudentsDAO studentsDAO;
public StudentsDAOgetStudentsDAO() {
return studentsDAO;
}
@Resource
public voidsetStudentsDAO(StudentsDAO studentsDAO) {
this.studentsDAO = studentsDAO;
setBaseHibernateDAO(studentsDAO);
}
public void delete(String id) {
Studentsrec = studentsDAO.get(Long.valueOf(id));
studentsDAO.delete(rec);
}
public void deletes(String[] ids) {
for (String id : ids) {
Studentsrec = studentsDAO.get(Long.valueOf(id));
studentsDAO.delete(rec);
}
}
public void save(Students rec) {
if (rec.getId() != null && rec.getId()> 0) {
studentsDAO.update(rec);
}else{
studentsDAO.save(rec);
}
}
public Students findById(Longid) {
Studentsrec = studentsDAO.findById(id);
return rec;
}
}
10.创建StudentAction
在cn.cugb.action中创建StudentsAction.java
package cn.cugb.action;
import javax.annotation.Resource;
importorg.springframework.context.annotation.Scope;
importorg.springframework.stereotype.Controller;
import cn.common.core.PageAction;
import cn.cugb.po.Students;
import cn.cugb.service.studentsService;
@Controller("StudentAction")
@Scope("prototype")
public class StudentAction extendsPageAction{
@Resource
privatestudentsService studentService; //依赖注入
privateStudents student;
publicString list()
{
if((orderItems == null || orderItems.equals(""))
&&((sortOp == null || sortOp.equals("")))) {
orderItems= "id";
sortOp= "desc";
}
Stringhql = " from Students as model ";
if(null != condition && condition.length() > 0) {
hql= hql + condition;
}
hql= hql + " order by model." + orderItems + " " + sortOp;
if(pageSize == null) {
pageSize= 20;
}
this.pageBean= studentService.queryforpage(pageSize, page, hql);
returnSUCCESS;
}
publicstudentsService getStudentService() {
returnstudentService;
}
publicvoid setStudentService(studentsService studentService) {
this.studentService= studentService;
}
publicStudents getStudent() {
returnstudent;
}
publicvoid setStudent(Students student) {
this.student= student;
}
}
11. 添加list.jsp
在WebRoot下创建info folder
在info文件夹下创建list.jsp
生成的list.jsp为
<%@ page language="java"import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.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">
<!--
<linkrel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
</body>
</html>
修改为:
<%@ page language="java"import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s"uri="/struts-tags"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.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">
<!--
<linkrel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:form name="form" action="list"namespace="/info">
<table width="100%"border="0" align="center"cellpadding="0" cellspacing="0"bgcolor="#ffffff">
<tr><td colspan=5 height=8></td></tr>
<tr>
<td width="5"> </td>
<td align="right">
<!--新增成员-->
<input type="button" name="xz" class="button"value="新 增" style="width:60px" style="cursor: hand;"onclick="add()">
<!--删除成员-->
<input type="button"name="sc" class="button" value="删 除" style="width:60px" style="cursor: hand;"onclick="del()">
<input type="button" name="cx" class="button"value="查 询" style="width:60px" style="cursor: hand;"onclick="search()">
<!--返回-->
<input type="button" name="fh" class="button"value="返 回" style="width:50px" style="cursor: hand;"onclick="history.go(-1)">
</td>
</tr>
</table>
<table width="100%" align="center"border="1" cellpadding="0"cellspacing="0" bordercolorlight="#C0C0C0" bordercolordark="#FFFFFF"class="dataTable">
<tr class="nr"height=28 ztype="head"class="dataTable">
<td noWrapalign="center" width="2%">序号</td>
<td noWrapalign="center" width="2%">编辑</td>
<td noWrapalign="center" width="3%"><a href="javascript:selectItem()">选择</a></td>
<td align="center"width="4%"><a title="排序此列" href="javascript:OItems('xh')">学号</a> </td>
<td align="center"width="5%"><a title="排序此列" href="javascript:OItems('xm')">姓名</a></td>
<td align="center"width="5%"><a title="排序此列" href="javascript:OItems('zjh')">证件号</a></td>
<td align="center"width="2%"><a title="排序此列" href="javascript:OItems('csrq')">性别</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('xb')">出生日期</a></td>
<td align="center"width="2%"><a title="排序此列" href="javascript:OItems('nj')">年级</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('mz')">民族</a></td>
<td align="center"width="4%"><a title="排序此列" href="javascript:OItems('xy')">学院</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('zy')">专业</a></td>
</tr>
<!-- 数据开始 -->
<s:iterator value="pageBean.list"status="s">
<tr height="24"onMouseOver="this.style.backgroundColor='#ffdf7e'" onMouseOut="this.style.backgroundColor='#ffffff'">
<td align=center class=nr><s:property value="#s.index+1"/></td>
<td align=center><a href="javascript:studentEdit('<s:property value="id"/>')"><img alt="编辑信息" src="<%=path%>/images/edit.gif"border="0"></a></td>
<!-- html标签,struts2标签怎么写 -->
<td align=center><input name="ids" type="checkbox"id="ids" value="<s:property value="id"/>"/></td>
<td align=center class=nr><s:property value="xh"/></td>
<td align=center class=nr><s:property value="xm"/></td>
<td align=center class=nr><s:property value="zjh"/></td>
<td align=center class=intro>
<s:if test="csrq==1">男 </s:if>
<s:elseif test="csrq==2">女 </s:elseif>
<s:else>未知</s:else>
</td>
<td align=center class=intro><s:property value="xb"/></td>
<td align=center class=intro><s:property value="nj"/></td>
<td align=center class=intro><s:property value="mz"/></td>
<td align=center class=intro><s:property value="xy"/></td>
<td align=center class=intro><s:property value="zy"/></td>
</tr>
</s:iterator>
<!-- 数据结束 -->
</table>
</s:form>
</body>
</html>
更新struts.xml为
<?xml version="1.0"encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//ApacheSoftware Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.custom.i18n.resources" value="applicationResource"></constant>
<constant name="struts.objectFactory.spring.autoWire"value="type"> </constant>
<constant name="struts.objectFactory" value="spring"> </constant>
<constant name="struts.devMode" value="true"> </constant>
<package name="info" extends="struts-default"namespace="/info">
<!-- 主页面 -->
<action name="list" method="list"class="StudentAction">
<result>/info/list.jsp</result>
</action>
</package>
</struts>
运行结果为
添加图片(WebRoot下添加images文件夹,存放图片)
添加分页(WebRoot下添加include文件夹,存放page.jsp)并在list.jsp中添加:
</s:iterator>
<jsp:include page="/Include/page.jsp"/>
添加样式文件(WebRoot下添加css文件夹,存放style.jsp)
运行结果为
12. 完善增删改查排序功能
12.1 新增
点击新增,跳转到studentAdd.jsp页面
1. List.jsp页面增加
<script type="text/javascript" language="javascript">
function add() {
document.form.action = "studentAdd.action";
document.form.submit();
}
</script>
2. 表示跳转到studentAdd.action,在struts.xml配置Action
<!-- 增 -->
<action name="studentAdd"method="add" class="StudentAction">
<result>/info/studentAdd.jsp</result>
</action>
3. 在StudentAction写函数add
public String add(){
student = new Students();
return SUCCESS;
}
4. studentAdd.jsp为:
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"prefix="s"%>
<%
Stringpath = request.getContextPath();
StringbasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
response.setHeader("Pragma","No-cache"); //HTTP 1.1
response.setHeader("Cache-Control","no-cache"); //HTTP 1.0
response.setHeader("Expires","0");//防止被proxy
%>
<html>
<head>
<TITLE>发送消息</TITLE>
<meta http-equiv="Expires"content="0">
<meta http-equiv="kiben"content="no-cache">
<link type="text/css"rel="stylesheet" href="<%=path%>/css/style.css" />
<script type="text/javascript"src="<%=path%>/ckeditor/ckeditor.js""></script>
<script type="text/javascript"src="<%=path%>/js/DatePicker/WdatePicker.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.EasyInsert-4.0.js"></script>
<script type="text/javascript"src="<%=path%>/js/statInput.js"></script>
<script type="text/javascript"src="<%=path%>/js/Birthday-Calendar.js"></script>
<script type="text/javascript"src="<%=path%>/js/birthday.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.js"></script>
<script type="text/javascript">
function submitForm() {
document.studentForm.action ="studentSave.action";
document.studentForm.submit();
}
</script>
</head>
<body leftmargin="0"topmargin="0" marginwidth="0"marginheight="0" bgcolor="#ffffff">
<div id="warp">
<div class="main">
<s:form name="studentForm" theme="simple" method="post"enctype="multipart/form-data">
<table border="0" width="100%"class="tableClass" id="table1"cellspacing="0" cellpadding="0">
<tr height=32>
<td width="1%"> </td>
<td>首页>>消息推送 >>发送消息</td>
</tr>
</table>
<table width="99%" border="0"align="center" cellpadding="0"cellspacing="1">
<tr>
<td valign=top>
<table width="100%" border="0"align="center" cellpadding="0"cellspacing="0">
<tr height=28>
<td width=10% align=right class=tdrowhead>学号:</td>
<td class="tdcontent"width=90% align="left"><font color="#ff0000"><s:textfield name="student.xh"id="xh" style="width:500px;"theme="simple" />
</td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>姓名:</td>
<td class='tdcontent'width=90%><s:textfield
name="student.xm" id="xm"style="width:500px;" theme="simple" />
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>证件号:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.zjh" id="zjh" theme="simple"/></td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>性别:</td>
<td class="tdcontent"width=90% align="left"><font
color="#ff0000">
<s:radio list="#{'1':'男','2':'女','3':'未知'}"
id="csrq" name="student.csrq"theme="simple" /> </font>
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>出生日期:</td>
<td class='tdcontent'width='90%'>
<input type="text" name="student.xb"value='<s:date name="student.xb"format="yyyy-mm-dd"/>'
id="updateTime" size="8" maxlength="10"style="WIDTH:80px">
<img src="<%=path%>/images/datetime.gif" onclick="WdatePicker({el:$dp.$('updateTime')});returnfalse">
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>民族:</td>
<td class='tdcontent'width='90%'>
<font color="#ff0000">
<s:select list="mzlist" listKey="code"listValue="name" id="mzcodeId"name="student.mzs.code" headerKey="0" headerValue="--请选择民族--" theme="simple"/>
</font>
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>年级:</td>
<td class='tdcontent'width='90%'>
<s:textfield name="student.nj" id="nj"theme="simple" /></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>学院:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.xy" id="xy"theme="simple" /></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>专业:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.zy" id="zy"theme="simple" /></td>
</tr>
</table>
<table width="100%" border="0"align="center" cellpadding="0"
cellspacing="0" bgcolor="#F6F6F6">
<tr>
<td height=36 align="center" bgcolor="#F7FFFF"><img
src="<%=path%>/images/submit.gif" style="cursor: hand;"
onclick="submitForm()">
</td>
</tr>
</table></td>
</tr>
</table>
<s:hidden name="page"/>
<s:hidden name="condition"/>
</s:form>
</div>
</div>
</body>
</html>
在studentAdd.jsp页面点击提交后,转到studentSave Action,配置struts.xml和StudentAction.java:
<action name="studentSave"method="save" class="StudentAction">
<!-- <result>/info/list.jsp</result>-->
<result type="redirect">list.action?page=${page}&condition=${condition}
</result>
</action>
public String save() {
studentsService.save(student);
mzlist = studentsService.getMzsList();
return SUCCESS;
}
12.2 删除
List.jsp点击删除按钮,执行函数为:
<script type="text/javascript"language="javascript">
function del(){
var element = document.getElementsByName("ids");
var checkId = "";
for ( var i = 0; i < element.length; i++) {
if (element[i].checked == true) {//checked属性
var tmp = element[i].value;
checkId = checkId +tmp + ",";
}
}
//sql = "delete student where idin("+checkId+")"
if (checkId == "") {
alert("没有选中记录,请选择!");
return false;
}
var len = 0;
for ( var i = 0; i <= element.length - 1;i++) {
if (element[i].checked)
len++;
}
if (confirm("是否确定删除?")) {
document.form.action = "studentDel.action";
document.form.submit();
}
}
</script>
多选删除跳转到studentDel.action
在struts.xml中和StudentAction.java中配置:
<!-- 删 -->
<action name="studentDel" method="del" class="StudentAction">
<result type="redirect">list.action</result>
</action>
public String del() {
studentsService.deletes(ids);
return SUCCESS;
}
12.3 修改
在list.jsp页面点击修改按钮,跳转到studentEdit.jsp页面
<script type="text/javascript" language="javascript">
function studentEdit(id){
document.form.action = "studentEdit.action?id=" + id;
document.form.submit();
}
</script>
studentEdit.jsp页面为:
<%@page import="cn.cugb.po.Students"%>
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"prefix="s" %>
<%
String path =request.getContextPath();
response.setHeader("Pragma","No-cache"); //HTTP 1.1
response.setHeader("Cache-Control","no-cache");//HTTP 1.0
response.setHeader("Expires","0"); //防止被proxy
%>
<html>
<head>
<TITLE>发送消息</TITLE>
<meta http-equiv="Expires"content="0">
<meta http-equiv="kiben"content="no-cache">
<link type="text/css"rel="stylesheet" href="<%=path%>/css/style.css" />
<script type="text/javascript"src="<%=path%>/ckeditor/ckeditor.js""></script>
<script type="text/javascript"src="<%=path%>/js/DatePicker/WdatePicker.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.EasyInsert-4.0.js"></script>
<script type="text/javascript"src="<%=path%>/js/statInput.js"></script>
<script type="text/javascript"src="<%=path%>/js/Birthday-Calendar.js"></script>
<script type="text/javascript"src="<%=path%>/js/birthday.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.js"></script>
<script type="text/javascript">
function submitForm() {
document.studentForm.action ="studentSave.action";
document.studentForm.submit();
}
</script>
</head>
<body leftmargin="0"topmargin="0" marginwidth="0"marginheight="0" bgcolor="#ffffff">
<div id="warp">
<div class="main">
<s:form name="studentForm" action="studentEdit" theme="simple" method="post"target="myself" enctype="multipart/form-data">
<table border="0"width="100%" class="tableClass"id="table1" cellspacing="0"cellpadding="0" >
<tr height=32>
<td width="1%"> </td>
<td>首页>>消息推送 >>发送消息</td>
</tr>
</table>
<table width="99%" border="0"align="center" cellpadding="0"
cellspacing="1">
<tr>
<td valign=top>
<table width="100%" border="0"align="center" cellpadding="0"
cellspacing="0">
<tr height=28>
<td>
<s:hidden name="student.id" value="%{id}"></s:hidden>
</td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>学号:</td>
<td class="tdcontent"width=90% align="left">
<s:textfield name="student.xh" id="xh"
style="width:500px;" theme="simple" />
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>姓名:</td>
<td class='tdcontent'width=90%><s:textfield
name="student.xm" id="xm"style="width:500px;" theme="simple" />
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>证件号:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.zjh" id="zjh" theme="simple"/></td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>性别:</td>
<td class="tdcontent"width=90% align="left"><font
color="#ff0000"> <s:radio
list="#{'1':'男','2':'女','3':'未知'}" id="csrq"
name="student.csrq" theme="simple" /> </font></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>出生日期:</td>
<td class='tdcontent'width='90%'>
<input type="text" name="xb"value='<s:date name="student.xb"format="yyyy-mm-dd"/>'
id="updateTime" size="8" maxlength="10"style="WIDTH:80px">
<img src="<%=path%>/images/datetime.gif" onclick="WdatePicker({el:$dp.$('updateTime')});returnfalse">
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>民族:</td>
<td class='tdcontent'width='90%'>
<s:select list="mzlist" listKey="code"listValue="name" name="student.mzs.code"id="mzs" headerKey="0"headerValue="--请选择民族--" theme="simple">
</s:select>
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>年级:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.nj" id="nj"theme="simple" /></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>学院:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.xy" id="xy"theme="simple" /></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>专业:</td>
<td class='tdcontent'width='90%'><s:textfield
name="student.zy" id="zy"theme="simple" /></td>
</tr>
</table>
<table width="100%" border="0"align="center" cellpadding="0"
cellspacing="0" bgcolor="#F6F6F6">
<tr>
<td height=36 align="center" bgcolor="#F7FFFF"><img
src="<%=path%>/images/submit.gif" style="cursor: hand;"
onclick="submitForm()"></td>
</tr>
</table></td>
</tr>
</table>
</s:form>
</div>
</div>
</body>
</html>
在studentEdit.jsp页面点击提交,跳转到studentSave.action,和添加student一样。配置struts.xml如下:
<!-- 改 -->
<action name="studentEdit" method="edit" class="StudentAction">
<result>/info/studentEdit.jsp</result>
</action>
12.4 查询
List.jsp页面点击查询按钮:
<script type="text/javascript" language="javascript">
function search() {
document.form.action = "studentSearch.action";
document.form.submit();
}
</script>
跳转到studentSearch.action,在struts.xml中和StudentAction.java配置:
<!-- 查 -->
<action name="studentSearch" method="search" class="StudentAction">
<result>/info/studentSearch.jsp</result>
</action>
<action name="studentSeByInfo" method="searchByInfo" class="StudentAction">
<result>/info/list.jsp</result>
</action>
public String search() {
student=new Students();
mzlist = studentsService.getMzsList();
return SUCCESS;
}
public String searchByInfo() {
Stringxh = student.getXh();
Stringxm = student.getXm();
Stringzjh = student.getZjh();
Stringmz = student.getMzs().getCode();
if(!("").equals(xh)){
condition += "and model.xh like '%"+xh+"%'";
}
if (!("").equals(xm)) {
condition += "and model.xm like '%"+xm+"%'";
}
if (!("").equals(zjh)) {
condition += "and model.zjh like '%"+zjh+"%'";
}
if (!("0").equals(mz)) {
condition += "and model.mzs.code like '%"+mz+"%'";
}
this.list();
return SUCCESS;
}
studentSearch.jsp页面为:
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"prefix="s" %>
<%
String path =request.getContextPath();
response.setHeader("Pragma","No-cache"); //HTTP 1.1
response.setHeader("Cache-Control","no-cache");//HTTP 1.0
response.setHeader("Expires","0"); //防止被proxy
%>
<html>
<head>
<TITLE>发送消息</TITLE>
<meta http-equiv="Expires"content="0">
<meta http-equiv="kiben"content="no-cache">
<link type="text/css"rel="stylesheet" href="<%=path%>/css/style.css" />
<script type="text/javascript"src="<%=path%>/ckeditor/ckeditor.js""></script>
<script type="text/javascript"src="<%=path%>/js/DatePicker/WdatePicker.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.EasyInsert-4.0.js"></script>
<script type="text/javascript"src="<%=path%>/js/statInput.js"></script>
<script type="text/javascript">
function searchByInfo() {
document.studentForm.action ="studentSeByInfo.action";
document.studentForm.submit();
}
</script>
</head>
<body leftmargin="0"topmargin="0" marginwidth="0"marginheight="0"
bgcolor="#ffffff">
<s:form name="studentForm" theme="simple" method="post"target="myself">
<div id="warp">
<div class="main">
<table width="99%" border="0"align="center" cellpadding="0"
cellspacing="1">
<tr>
<td valign=top>
<table width="100%" border="0"align="center" cellpadding="0"cellspacing="0">
<tr height=28>
<td width=10% align=right class=tdrowhead>学号:</td>
<td class="tdcontent"width=90% align="left">
<font color="#ff0000"><s:textfield name="student.xh" id="xh"style="width:500px;" theme="simple" />
</td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>姓名:</td>
<td class='tdcontent'width=90%>
<s:textfield name="student.xm" id="xm"style="width:500px;" theme="simple" />
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>证件号:</td>
<td class='tdcontent'width='90%'>
<s:textfield name="student.zjh" id="zjh" theme="simple"/></td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>性别:</td>
<td class="tdcontent"width=90% align="left">
<font color="#ff0000">
<s:radio list="#{'1':'男','2':'女','3':'未知'}" id="csrq" name="student.csrq"theme="simple" /> </font>
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>出生日期:</td>
<td class='tdcontent'width='90%'>
<input type="text" name="student.birthday"value='<s:date name="student.birthday"format="yyyy-mm-dd"/>' id="updateTime"size="8" maxlength="10"style="WIDTH:80px">
<img src="<%=path%>/images/datetime.gif" onclick="WdatePicker({el:$dp.$('updateTime')});returnfalse">
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>民族:</td>
<td class='tdcontent'width='90%'>
<font color="#ff0000">
<s:select list="mzlist" listKey="code"listValue="name" id="mzcodeId"name="student.mzs.code" headerKey="0" headerValue="--请选择民族--" theme="simple"/>
</font>
</td>
</tr>
</table>
<table width="100%" border="0"align="center" cellpadding="0"
cellspacing="0" bgcolor="#F6F6F6">
<tr>
<td height=36 align="center" bgcolor="#F7FFFF">
<input type="button" name="cx"class="button" value="查 询" style="width:60px" style="cursor: hand;" onclick="searchByInfo()">
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
</s:form>
</body>
</html>
12.5 排序
因为在list.jsp中,每一行都是:
<td align="center" width="4%"><a title="排序此列" href="javascript:OItems('xh')">学号</a></td>
<td align="center"width="5%"><a title="排序此列" href="javascript:OItems('xm')">姓名</a></td>
<td align="center"width="5%"><a title="排序此列" href="javascript:OItems('zjh')">证件号</a></td>
<td align="center"width="2%"><a title="排序此列" href="javascript:OItems('csrq')">性别</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('xb')">出生日期</a></td>
<td align="center"width="2%"><a title="排序此列" href="javascript:OItems('nj')">年级</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('mzs.code')">民族</a></td>
<td align="center"width="4%"><a title="排序此列" href="javascript:OItems('xy')">学院</a></td>
<td align="center"width="3%"><a title="排序此列" href="javascript:OItems('zy')">专业</a></td>
所以,相当于在执行:
<script type="text/javascript" language="javascript">
function OItems(I) {
if (I == document.form.OrderItems.value){
if (document.form.SortOp.value == "ASC") {
document.form.SortOp.value= "DESC";
} else {
document.form.SortOp.value= "ASC";
}
} else {
document.form.SortOp.value= "DESC";
document.form.OrderItems.value= I;
}
document.form.submit();
return;
}
</script>
身份证号验证
正则表达式:
http://www.runoob.com/regexp/regexp-syntax.html
)
/^表达开头
\d表示数字
+ 匹配前面的子表达式一次或多次(大于等于1次)
$ 匹配输入字符串的结束位置
?匹配前面的子表达式零次或一次。
[abc]字符集合。匹配所包含的任意一个字符。
[a-z] 字符范围。匹配指定范围内的任意字符。
function IdentityCodeValid(code) {
var city = {
11 : "北京",
12 : "天津",
13 : "河北",
14 : "山西",
15 : "内蒙古",
21 : "辽宁",
22 : "吉林",
23 : "黑龙江 ",
31 : "上海",
32 : "江苏",
33 : "浙江",
34 : "安徽",
35 : "福建",
36 : "江西",
37 : "山东",
41 : "河南",
42 : "湖北 ",
43 : "湖南",
44 : "广东",
45 : "广西",
46 : "海南",
50 : "重庆",
51 : "四川",
52 : "贵州",
53 : "云南",
54 : "西藏 ",
61 : "陕西",
62 : "甘肃",
63 : "青海",
64 : "宁夏",
65 : "新疆",
71 : "台湾",
81 : "香港",
82 : "澳门",
91 : "国外 "
};
var tip = "";
var pass = true;
if (!code
|| !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i
.test(code)) {
tip = "身份证号格式错误";
pass = false;
}
else if (!city[code.substr(0, 2)]) {
tip = "地址编码错误";
pass = false;
} else {
//18位身份证需要验证最后一位校验位
if (code.length == 18) {
code = code.split('');
//∑(ai×Wi)(mod 11)
//加权因子
var factor = [ 7, 9, 10, 5, 8, 4,2, 1, 6, 3, 7, 9, 10, 5, 8,
4, 2 ];
//校验位
var parity = [ 1, 0, 'X', 9, 8,7, 6, 5, 4, 3, 2 ];
var sum = 0;
var ai = 0;
var wi = 0;
for ( var i = 0; i < 17; i++) {
ai = code[i];
wi = factor[i];
sum += ai * wi;
}
var last = parity[sum % 11];
if (parity[sum % 11] != code[17]){
tip = "校验位错误";
pass = false;
}
}
}
if (!pass)
alert(tip);
return pass;
}
其他验证
var v = document.getElementById("xh").value;
if (v.length == 0) {
alert("学号不能为空!");
document.studentForm.xh.focus();
return false;
}
if (!/^\d+$/.test(v)) {
alert("学号只能是数字");
document.studentForm.xh.focus();
document.studentForm.xh.select();
return false;
}
var v2 = document.getElementById("xm").value;
if (v2.length == 0) {
alert("姓名不能为空!");
document.studentForm.xm.focus();
return false;
}
13. detail显示
在list.jsp最后一列添加
<td noWrap align="center"width="2%">详细信息</td>
<td align=center class=intro>
<a href="javascript:showDetail('<s:property value="xh"/>','<s:property value="xm"/>','<s:property value="zjh"/>','<s:property value="csrq"/>','<s:property value="xb"/>','<s:property value="mzs.name"/>','<s:property value="nj"/>','<s:property value="xy"/>','<s:property value="zy"/>')">
<img alt="查询信息" src="<%=path%>/images/detail.gif"border="0"></a>
</td>
点击查询信息图片后,弹出详细信息框:
<script type="text/javascript" language="javascript">
function showDetail(xh,xm,zjh,csrq,xb,mz,nj,xy,zy){
var l = window.screen.width;
var w = window.screen.height;
var width = 600;
var height = 400;
var al = (l - width) / 2;
var aw = (w - height) / 2;
var url='studentDetail.jsp?xh='+xh+'&xm='+xm+'&zjh='+zjh+'&csrq='+csrq+'&xb='+xb+'&mz='+mz+'&nj='+nj+'&xy='+xy+'&zy='+zy;
var features1 = 'height='+height+',width='+width+', top='+aw+',left='+al+', toolbar=no, menubar=no,scrollbars=no, resizable=no,location=n o, status=no';
window.open(url,'newwindow',features1);//chrome/firefox
// var features2 ='dialogHeight:'+height+';dialogWidth:'+width+';center:yes';
// window.showModalDialog(url,document.form,features2);//firefox
}
</script>
为url传参,在studentDetail.jsp中获取url传过来的参数,studentDetail.jsp为:
<%@page import="cn.cugb.action.StudentAction"%>
<%@page import="cn.cugb.service.studentsService"%>
<%@page import="cn.cugb.po.Students"%>
<%@ page language="java"import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags"prefix="s" %>
<%
Stringpath = request.getContextPath();
response.setHeader("Pragma","No-cache"); //HTTP 1.1
response.setHeader("Cache-Control","no-cache");//HTTP 1.0
response.setHeader("Expires","0"); //防止被proxy
request.setCharacterEncoding("UTF-8");
Stringxh = request.getParameter("xh");
Stringxm = newString(request.getParameter("xm").getBytes("ISO8859-1"),"UTF-8");
Stringzjh = request.getParameter("zjh");
Stringcsrq = request.getParameter("csrq");
Stringxb = request.getParameter("xb");
Stringmz = newString(request.getParameter("mz").getBytes("ISO8859-1"),"UTF-8");
Stringnj = request.getParameter("nj");
Stringxy = newString(request.getParameter("xy").getBytes("ISO8859-1"),"UTF-8");
Stringzy = newString(request.getParameter("zy").getBytes("ISO8859-1"),"UTF-8");
%>
<html>
<head>
<TITLE>发送消息</TITLE>
<meta http-equiv="Expires"content="0">
<meta http-equiv="kiben"content="no-cache">
<link type="text/css"rel="stylesheet" href="<%=path%>/css/style.css" />
<script type="text/javascript"src="<%=path%>/ckeditor/ckeditor.js""></script>
<script type="text/javascript"src="<%=path%>/js/DatePicker/WdatePicker.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.EasyInsert-4.0.js"></script>
<script type="text/javascript"src="<%=path%>/js/statInput.js"></script>
<script type="text/javascript"src="<%=path%>/js/Birthday-Calendar.js"></script>
<script type="text/javascript"src="<%=path%>/js/birthday.js"></script>
<script type="text/javascript"src="<%=path%>/js/jquery.js"></script>
<script type="text/javascript">
// function submitForm() {
// document.studentForm.action ="studentSave.action";
// document.studentForm.submit();
// }
</script>
</head>
<body leftmargin="0"topmargin="0" marginwidth="0"marginheight="0" bgcolor="#ffffff">
<div id="warp">
<div class="main">
<s:form name="studentForm" action="studentDetail" theme="simple" method="post"target="myself" enctype="multipart/form-data">
<table border="0"width="100%" class="tableClass"id="table1" cellspacing="0"cellpadding="0" >
<tr height=32>
<td width="1%"> </td>
<td>个人详细信息 :</td>
</tr>
</table>
<table width="99%" border="0"align="center" cellpadding="0"
cellspacing="1">
<tr>
<td valign=top>
<table width="100%" border="0"align="center" cellpadding="0"
cellspacing="0">
<tr height=28>
<td width=20% align=right class=tdrowhead>学号:</td>
<td class="tdcontent"width=90% align="left">
<input id ="xh" name="student.xh"value ="<%= xh%>" style="width:400px;" theme="simple"disabled="true">
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>姓名:</td>
<td class='tdcontent'width=90%>
<input name="student.xm" id="xm"value="<%= xm%>" style="width:400px;" theme="simple"disabled="true"/>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>证件号:</td>
<td class='tdcontent'width='90%'>
<input name="student.zjh" id="zjh" value="<%=zjh%>"style="width:400px;" theme="simple" disabled="true"/></td>
</tr>
<tr height=28>
<td width=10% align=right class=tdrowhead>性别:</td>
<td class="tdcontent"width=90% align="left"><font
color="#ff0000">
<input type="radio" name="csrq"value="1" <%if(csrq.equals("1"))out.print("checked");%>/>男
<input type="radio" name="csrq"value="2" <%if(csrq.equals("2"))out.print("checked");%>/>女
<input type="radio" name="csrq"value="3" <%if(csrq.equals("3"))out.print("checked");%>/>未知
</font></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>出生日期:</td>
<td class='tdcontent'width='90%'>
<input name="student.xb" id="xb"value="<%=xb%>" theme="simple"disabled="true"/>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>民族:</td>
<td class='tdcontent'width='90%'>
<input name="student.mzs" id="mzs" value="<%=mz%>"theme="simple" disabled="true"/>
</td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>年级:</td>
<td class='tdcontent'width='90%'>
<input name="student.nj" id="nj"value="<%=nj%>" theme="simple"disabled="true"/></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>学院:</td>
<td class='tdcontent'width='90%'>
<input name="student.xy" value="<%=xy%>" id="xy"theme="simple" disabled="true"/></td>
</tr>
<tr height=28>
<td class='tdrowhead'width='10%' align=right>专业:</td>
<td class='tdcontent'width='90%'>
<input name="student.zy" id="zy"value="<%=zy%>" theme="simple"disabled="true"/></td>
</tr>
</table>
</td>
</tr>
</table>
</s:form>
</div>
</div>
</body>
</html>
这为通过window.open和window.showModalDialog方式弹出信息框。
14. 上传文件
在StudentAction.java中定义文件,文件名和文件类型:
private File file;
// 文件名称
private String fileFileName;
// 文件类型
private String fileContentType;
// 注意:文件名称和文件类型的名称前缀必须相同
并添加set和get方法:
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public StringgetFileFileName() {
return fileFileName;
}
public void setFileFileName(StringfileFileName) {
this.fileFileName = fileFileName;
}
public StringgetFileContentType() {
return fileContentType;
}
public voidsetFileContentType(String fileContentType) {
this.fileContentType =fileContentType;
}
上传文件的具体函数为:
public String upload() throws Exception {
// 获取需要上传文件的文件路径
Stringpath = ServletActionContext.getServletContext().getRealPath(
"/uploadFiles");
System.out.println(path);
if (file != null) {
FilesaveFile = newFile(newFile(path), fileFileName);
if(!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
try {
FileUtils.copyFile(file, saveFile);
}catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[]t = fileContentType.split("/");
for (String s : t)
System.out.println(s);
}
this.list();
return SUCCESS;
}
在list页面点击上传文件按钮,跳转到upload.jsp,页面upload.jsp为:
<%@ page language="java"import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s"uri="/struts-tags"%>
<%
String path =request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<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">
<!--
<linkrel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="upload" method="post"enctype="multipart/form-data">
<input type="file"name="file">
<input type="submit"name="btnUpload" value="上传">
</form>
</body>
</html>
当点击选择时,弹出文件框选择,再点击上传,即进行该action里的upload()方法,所以在struts.xml中配置为:
<!-- 上传文件 -->
<action name="uploadFile" class="StudentAction">
<result>/info/upload.jsp</result>
</action>
<action name="upload" method="upload"class="StudentAction">
<result>/info/list.jsp</result>
</action>
上传文件的位置为:
…\myeclipse\workspace\.metadata\.me_tcat\webapps\studentDemo\uploadFiles
uploadFiles文件夹为自动生成,对upload()函数里:
String path = ServletActionContext.getServletContext().getRealPath(
"/uploadFiles");
错误整理
1、 页面跳转路径问题:
<!-- <basehref="<%=basePath%>"> --> 不能要
<base href="...">是用来表明当前页面的相对路径所使用的根路径的。
2、 Po缺少默认无参构造器
3、 studentService的setDAO方法缺少setBaseHibernateDAO(studentsDAO);
jsp文件格式详解
jsp文件开始:
<%@ page language="java"import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
page
page为jsp的编译指令,只针对当前页面的指令。
编译指令还包括include和taglib。
http://blog.csdn.net/microfhu/article/details/6944368
<%@ page import="org.hibernate.envers.tools.Tools"%>
表示引包
taglib
<%@ taglib prefix="s"uri="/struts-tags"%>
taglib用于定义和访问自定义标签,这里引入struts2标签:http://blog.csdn.net/wangxiaoqin00007/article/details/7000589
path/basePath
<%
String path =request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
获取相对路径和根路径。
http://www.cnblogs.com/token/archive/2012/08/13/2636287.html
标签顺序
jsp的标签顺序为:
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 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">
<!--
<linkrel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page studentDemo. <br>
</body>
</html>
http://www.runoob.com/tags/ref-byfunc.html
详细解释为:
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN"> 定义文档类型
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
http://blog.csdn.net/xiaozhao_19/article/details/2232748
… …
<link rel="stylesheet" type="text/css"href="<%=path%>/css/styles.css">
<scripttype="text/javascript" language="javascript">
</script>
</head>
<body>
This is my JSP page studentDemo. <br>
</body>
</html>
table
<table width="100%"border="0" align="center"cellpadding="0" cellspacing="0"bgcolor="#ffffff">
<tr><td colspan=5 height=8></td></tr>
<tr>
<td width="5"> </td>
<td align=left class=intro>
<!-- <inputtype="file" name="upload"> -->
<input type="button" name="btnUpload"value="上传文件" onclick="uploadFile()">
</td>
<td align="right">
<!--新增成员-->
<input type="button" name="xz" class="button"value="新 增" style="width:60px" style="cursor: hand;"onclick="addStu()">
<!--删除成员-->
<input type="button"name="sc" class="button" value="删 除" style="width:60px" style="cursor: hand;"onclick="del()">
<input type="button" name="cx" class="button"value="查 询" style="width:60px" style="cursor: hand;"onclick="search()">
<!--返回-->
<input type="button" name="fh" class="button"value="返 回" style="width:50px" style="cursor: hand;"onclick="history.go(-1)">
</td>
</tr>
</table>
table的属性设置,可参考http://www.w3school.com.cn/tags/tag_table.asp
s:hidden
<s:hidden name="OrderItems"/>
表示通过hidden隐藏值向action传递参数。可参考:
http://www.yiibai.com/struts_2/struts-2-shidden-hidden-value-example.html
a
<td align="center" width="3%"><atitle="排序此列" href="javascript:OItems('zy')">专业</a></td>
其中<td>代表表格一列,<a>代表超链接。
<a title>属性,可以让鼠标悬停在超链接上的时候,显示该超链接的文字注释。
<a href>为超链接指向的地址。这里为指向一个带参function。
input
<!— 查询-->
<input type="button"name="cx" class="button" value="查 询" style="width:60px" style="cursor: hand;"onclick="search()">
<!--返回-->
<input type="button"name="fh" class="button" value="返 回" style="width:50px" style="cursor: hand;"onclick="history.go(-1)">
Input标签包括很多type,包括button、checkbox、file、hidden、image、password、radio、reset、submit、text。具体可参考:
http://www.w3school.com.cn/tags/tag_input.asp
onMouseOver/onMouseOut
<tr height="24" onMouseOver="this.style.backgroundColor='#ffdf7e'"onMouseOut="this.style.backgroundColor='#ffffff'">
设置为表格的某一行,当鼠标放在上面时,该行的背景颜色为#ffdf7e,否则为#ffffff。
img
<img alt="编辑信息" src="<%=path%>/images/edit.gif"border="0">
<img> 标签并不会在网页中插入图像,而是从网页上链接图像。<img>标签创建的是被引用图像的占位空间。<alt>规定图像的替代文本。<src>则是图像的url。具体参考:
http://www.w3school.com.cn/tags/tag_img.asp