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