데이터베이스jdbc_페이지 나누기 사례
package cn.itcast.dao;
import java.util.List;
import cn.itcast.domain.Customer;
import cn.itcast.domain.QueryResult;
public interface CustomerDao {
// 1: Customer , void
void add(Customer c);
// 2: Customer , void
void update(Customer c);
// 3: Customer , void
void delete(Customer c);
// 4: id Customer
Customer find(String id);
// 5: Customer
List<Customer> getAll();
// 6: SQL, N M , (N,M),
// , QueryResult !
public QueryResult pageQuery(int startIndex,int pageSize);
}
CustomerDaoImpl은 Dao에 있습니다.impl 패키지
package cn.itcast.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import cn.itcast.dao.CustomerDao;
import cn.itcast.domain.Customer;
import cn.itcast.domain.QueryResult;
import cn.itcast.exception.DaoException;
import cn.itcast.utils.JdbcUtils;
public class CustomerDaoImpl implements CustomerDao {
// 1: Customer , void
public void add(Customer c){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String fields="id,name,gender,birthday,cellphone,email,preference,type,description";
String sql="insert into customer("+fields+") values(?,?,?,?,?,?,?,?,?)";
st=conn.prepareStatement(sql);
st.setString(1, c.getId());
st.setString(2, c.getName());
st.setString(3, c.getGender());
// ,setDate sql.Date
st.setDate(4, new java.sql.Date(c.getBirthday().getTime()));
st.setString(5, c.getCellphone());
st.setString(6, c.getEmail());
st.setString(7, c.getPreference());
st.setString(8, c.getType());
st.setString(9, c.getDescription());
st.executeUpdate();
}catch (Exception e) {
// Dao , !
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
// 2: Customer , void
public void update(Customer c){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String fields="name=?,gender=?,birthday=?,cellphone=?,email=?,preference=?,type=?,description=?";
String sql="update customer set "+fields+" where id=?";
st=conn.prepareStatement(sql);
st.setString(1, c.getName());
st.setString(2, c.getGender());
// ,setDate sql.Date
st.setDate(3, new java.sql.Date(c.getBirthday().getTime()));
st.setString(4, c.getCellphone());
st.setString(5, c.getEmail());
st.setString(6, c.getPreference());
st.setString(7, c.getType());
st.setString(8, c.getDescription());
st.setString(9, c.getId());
st.executeUpdate();
}catch (Exception e) {
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
// 3: Customer , void
public void delete(Customer c){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String sql="delete from customer where id=?";
st=conn.prepareStatement(sql);
st.setString(1, c.getId());
st.executeUpdate();
}catch (Exception e) {
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
// 4: id Customer
public Customer find(String id){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String sql="select * from customer where id=?";
st=conn.prepareStatement(sql);
st.setString(1, id);
rs=st.executeQuery();
if (rs.next()) {
Customer c=new Customer();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
// util.Date, sql.Date, !
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getString("cellphone"));
c.setEmail(rs.getString("email"));
c.setPreference(rs.getString("preference"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
return c;
}
return null;
}catch (Exception e) {
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
// 5: Customer
public List<Customer> getAll(){
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String sql="select * from customer";
st=conn.prepareStatement(sql);
rs=st.executeQuery();
List<Customer> list=new ArrayList<Customer>();
while (rs.next()) {
Customer c=new Customer();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
// util.Date, sql.Date, !
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getString("cellphone"));
c.setEmail(rs.getString("email"));
c.setPreference(rs.getString("preference"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
list.add(c);
}
return list;
}catch (Exception e) {
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
// 6: SQL, N M , (N,M), list
// , SQL QueryResult !
public QueryResult pageQuery(int startIndex,int pageSize){
//SQL (sql_s)
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
QueryResult qr = null;
try {
conn = JdbcUtils.getConnection();
// 1 ? , 2 ?
String sql = "select * from customer limit ?,?";
st = conn.prepareStatement(sql);
st.setInt(1, startIndex);
st.setInt(2, pageSize);
rs = st.executeQuery();
// 1 SQL list, QueryResult( )
List<Customer> list=new ArrayList<Customer>();
while (rs.next()) {
Customer c=new Customer();
c.setId(rs.getString("id"));
c.setName(rs.getString("name"));
c.setGender(rs.getString("gender"));
// util.Date, sql.Date, !
c.setBirthday(rs.getDate("birthday"));
c.setCellphone(rs.getString("cellphone"));
c.setEmail(rs.getString("email"));
c.setPreference(rs.getString("preference"));
c.setType(rs.getString("type"));
c.setDescription(rs.getString("description"));
list.add(c);
}
// list QueryResult( )
qr=new QueryResult();
qr.setList(list);
// 2 sql, , QueryResult
sql="select count(*) from customer";
st=conn.prepareStatement(sql);
rs=st.executeQuery();
// , if
if (rs.next()) {
// QueryResult( )
qr.setTotalRecord(rs.getInt(1));// int
// rs.getInt("count(*)");
//qr.setTotalRecord(rs.getInt("count(*)"));
}
// (list, ) QueryResult( )
return qr;
} catch (Exception e) {
throw new DaoException(e);
} finally {
JdbcUtils.release(conn, st, rs);
}
}
}
/*JDBCIMPL !
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String sql="?";
st=conn.prepareStatement(sql);
st.setString(1, "");
int num=st.executeUpdate();
rs=st.executeQuery();
}catch (Exception e) {
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
*/
domain 패키지에 있는 Customer
package cn.itcast.domain;
import java.util.Date;
public class Customer {
// , Getter Setter
private String id;
private String name;
private String gender;
private Date birthday;
private String cellphone;
private String email;
private String preference;
private String type;
private String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPreference() {
return preference;
}
public void setPreference(String preference) {
this.preference = preference;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
PageBean은 domain 패키지에 있음
package cn.itcast.domain;
import java.util.List;
/*PageBean , !
PageBean ,
(QueryInfo ) (QueryResult ),
4 */
public class PageBean {
private List list;//QueryResult , select limit
private int totalRecord;//QueryResult , select count(*) !
private int pageSize;//QueryInfo ,
private int currentPage;//QueryInfo ,
// 4 setter,
private int totalPage;// (totalRecord,pageSize)!
private int previousPage;// ( currentPage<2)!
private int nextPage;// ( currentPage+1>=totalPage)!
private int[] pageBar;// ! , 10 ( totalPage,currentPage)
// , getter !
public int getTotalPage() {
// , , !
// 100 5 20
// 101 5 21
// 99 5 20
int mod=totalRecord%pageSize;//
if (mod==0) {
// 0, , A/B
totalPage=totalRecord/pageSize;
} else {
// , A/B+1;
totalPage=totalRecord/pageSize+1;
}
/* 2 :
totalPage = (totalRecord+(pageSize-1))/pageSize;
*/
return totalPage;
}
public int getPreviousPage() {
// , !
// ( currentPage<2)!
if (currentPage<2) {
previousPage=1;
} else {
previousPage=currentPage-1;
}
return previousPage;
}
public int getNextPage() {
// , !
// ( currentPage+1>=totalPage)!
if (currentPage+1>=totalPage) {
nextPage=totalPage;
} else {
nextPage=currentPage+1;
}
return nextPage;
}
public int[] getPageBar() {
/* , 10 ( totalpage,currentpage )
: 10 , 1,
: 4( 15-4=11)
5( 15+5=20)
11,12,...19,20
:
1, 4 , <1, 1, 10
2, 5 , > ,
, 9*/
int start;
int end;
int pb[] = null;
if(totalPage<=10){
pb = new int[totalPage];
start = 1;
end = totalPage;
}else{
pb = new int[10];
start = currentPage - 4;
end = currentPage + 5;
// =30 3 3-4=-1 1 10
// =30 29 29+5=34 21 30
if(start<1){
start = 1;
end = 10;
}
if(end>totalPage){
start = totalPage - 9;
end = totalPage;
}
}
// pageBar ,
int index = 0;
for(int i=start;i<=end;i++){
pb[index++] = i;
}
this.pageBar = pb;
return pageBar;
/* : pagebar[]
int pb[] = new int[totalPage];
for(int i=1;i<=totalPage;i++){
// 1 , 0, 1;
pb[i-1] = i;
}
this.pageBar = pb;
return pageBar;
*/
}
// getter setter
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
domain 패키지에 QueryInfo 위치
package cn.itcast.domain;
//QueryInfo jsp servlet 2 !
public class QueryInfo {
// ! !
private int currentPage=1; //
private int pageSize=5;// ,
private int startIndex;//select * from limit X,Y; 1 ,
// , ( , )
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getStartIndex() {
// , , setter!
//select * from limit , ;
startIndex=(currentPage-1)*pageSize;
// 1 , 0 ,
// 2 , 5 ,
return startIndex;
}
}
domain 패키지에 QueryResult 위치
package cn.itcast.domain;
import java.util.List;
//QueryResult SQL !
public class QueryResult {
private List list;// select * from limit , ;
private int totalRecord;// select count(*) from ;
// getter setter !
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
}
exception 패키지에 DaoException 위치
package cn.itcast.exception;
public class DaoException extends RuntimeException {
//1,
//2, ,
public DaoException() {
}
public DaoException(String message) {
super(message);
}
public DaoException(Throwable cause) {
super(cause);
}
public DaoException(String message, Throwable cause) {
super(message, cause);
}
public DaoException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
DaoFactory는 factory 패키지에 있음
package cn.itcast.factory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class DaoFactory {
/*
* 1,
* 2, src dao.properties
* 3, , !*/
private static Properties pro=new Properties();
// 1 , ,
private DaoFactory(){
//dao.properties 1
String pro_name="dao.properties";
InputStream in=DaoFactory.class.getClassLoader().getResourceAsStream(pro_name);
try {
pro.load(in);
} catch (IOException e) {
//
throw new RuntimeException(e);
}
}
// 2 ,
private static DaoFactory instance=new DaoFactory();
// 3 ,
public static DaoFactory getInstance(){
return instance;
}
// ! ! ( ), !
public <T> T createDao(Class<T> clazz){
// CustomerDao=cn.itcast.dao.impl.CustomerDaoImpl
//String full_name=clazz.getName();//cn.itcast.dao.CustomerDao
String simple_name=clazz.getSimpleName();//CustomerDao
//simple_name dao.properties , impl_name
String impl_name=pro.getProperty(simple_name);
try {
T dao=(T) Class.forName(impl_name).newInstance();
// new cn.itcast.dao.impl.CustomerDaoImpl()
return dao;
} catch (Exception e) {
//
throw new RuntimeException(e);
}
}
}
FormBean은 formbean 패키지에 있음
package cn.itcast.formbean;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
public class FormBean {
/* FormBean
* String */
private String name;
private String gender;
private String birthday;
private String cellphone;
private String email;
private String preference;
private String type;
private String description;
// Map errors
private Map errors = new HashMap();
public boolean validate(){
// , ,flag
boolean flag = true;
//1, , 2-10 (\u4e00-\u9fa5)
if(name==null || name.trim().equals("")){
flag = false;
errors.put("name", " !");
}else if(!name.matches("^([\u4e00-\u9fa5]{2,10})$") && !name.matches("[A-Za-z]{2,10}")){
// ,
flag = false;
errors.put("name", " 2-10 !");
}
/*2, , ,
* SimpleDateFormat 12 32 2
* BeanUtils DateLocaleConverter
* , !*/
if(this.birthday!=null && !this.birthday.trim().equals("")){
try{
DateLocaleConverter conv= new DateLocaleConverter();
conv.convert(this.birthday, "yyyy-MM-dd");
}catch (Exception e) {
// ,
flag = false;
errors.put("birthday", " !");
}
}
//3, , 7-11
if(!this.cellphone.matches("\\d{7,11}") && cellphone!=null && !cellphone.trim().equals("")){
flag = false;
errors.put("cellphone", " 7-11 !");
}
//4, ,
if(this.email==null || this.email.trim().equals("")){
flag = false;
errors.put("email", " !");
}else{
if(!this.email.matches("\\w+@\\w+(\\.\\w+)+")){
flag = false;
errors.put("email", " !");
}
}
return flag;
}
// jsp EL${} getter and setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPreference() {
return preference;
}
public void setPreference(String preference) {
this.preference = preference;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Map getErrors() {
return errors;
}
public void setErrors(Map errors) {
this.errors = errors;
}
}
서비스 팩에 있는 BusinessService
package cn.itcast.service;
import java.util.List;
import cn.itcast.domain.Customer;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.QueryInfo;
public interface BusinessService {
// 1: Customer , void
void add(Customer c);
// 2: Customer , void
void update(Customer c);
// 3: Customer , void
void delete(Customer c);
// 4: id Customer
Customer find(String id);
// 5: Customer
List<Customer> getAll();
// 6: dao ! dao !
// QueryInfo PageBean , PageBean jsp
public PageBean pageQuery(QueryInfo info);
}
BusinessServiceImpl은 서비스에 있습니다.impl 패키지
package cn.itcast.service.impl;
import java.util.List;
import cn.itcast.dao.CustomerDao;
import cn.itcast.dao.impl.CustomerDaoImpl;
import cn.itcast.domain.Customer;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.QueryInfo;
import cn.itcast.domain.QueryResult;
import cn.itcast.factory.DaoFactory;
import cn.itcast.service.BusinessService;
public class BusinessServiceImpl implements BusinessService {
/* web ,
* web , BusinessServiceImpl
* BusinessServiceImpl CustomDao
* !
* Dao ,
* 1, factory , DaoFactory ( )
* 2,src dao.properties ,
* CustomerDao, cn.itcast.dao.impl.CustomerDaoImpl
* 3,DaoFactory , CustomerDao
* dao.properties , !
* 4, BusinessServiceImpl CustomerDao*/
//private CustomerDao dao=new CustomerDaoImpl();
private CustomerDao dao=DaoFactory.getInstance().createDao(CustomerDao.class);
// 1: Customer , void
public void add(Customer c){
dao.add(c);
}
// 2: Customer , void
public void update(Customer c){
dao.update(c);
}
// 3: Customer , void
public void delete(Customer c){
dao.delete(c);
}
// 4: id Customer
public Customer find(String id){
return dao.find(id);
}
// 5: Customer
public List<Customer> getAll(){
return dao.getAll();
}
// 6: dao ! dao !
// QueryInfo PageBean , PageBean jsp
public PageBean pageQuery(QueryInfo info){
int startIndex=info.getStartIndex();
int pageSize=info.getPageSize();
// dao
QueryResult qr=dao.pageQuery(startIndex, pageSize);
// PageBean, ( QueryInfo QueryResult), jsp !
PageBean bean=new PageBean();
bean.setList(qr.getList());
bean.setTotalRecord(qr.getTotalRecord());
bean.setCurrentPage(info.getCurrentPage());
bean.setPageSize(info.getPageSize());
return bean;
}
}
Global은 Utils 패키지에 있음
package cn.itcast.utils;
public class Global {
public static String genders[] = {" "," "};
public static String preferences[] = {" "," "," "," "," "," "," "," "};
public static String types[] = {" "," "," "," "," "," "," "," "," "};
}
Utils 패키지에 있는 JdbcUtils
package cn.itcast.utils;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtils {
private static Properties pro=new Properties();
/*
* Properties
* : ,
* 1:
* 2:
* ,
* db.properties src
*/
static{
String pro_name="db.properties";
InputStream in=JdbcUtils.class.getClassLoader().getResourceAsStream(pro_name);
try {
pro.load(in);
Class.forName(pro.getProperty("driver"));
} catch (Exception e) {
//
throw new ExceptionInInitializerError(e);
}
}
// 1:
public static Connection getConnection() throws SQLException{
String url=pro.getProperty("url");
String user=pro.getProperty("user");
String password=pro.getProperty("password");
Connection conn=DriverManager.getConnection(url, user, password);
return conn;
}
// 2:
public static void release(Connection conn,Statement st,ResultSet rs){
if (conn!=null) {
try {
conn.close();
}catch (Exception e) {
// ! , 2 if
e.printStackTrace();
}
conn=null;
}
if (st!=null) {
try {
st.close();
}catch (Exception e) {
// ! , 1 if
e.printStackTrace();
}
st=null;
}
if (rs!=null) {
try {
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs=null;
}
}
}
MyEL은 Utils 패키지에 있음
package cn.itcast.utils;
/* EL , web java
* 1,
* 2,tld , Tomcat tld
* 3,jsp taglib */
public class MyEL {
// EL , 1, !
public static String leftStr(String str,Integer len){
if(str.trim().length()>len){
return str.substring(0, len) + "......";
}
return str;
}
}
WebUtils는 utils 패키지에 있음
package cn.itcast.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import sun.misc.BASE64Encoder;
import cn.itcast.formbean.FormBean;
public class WebUtils {
// 1 : formbean , !
public static FormBean request2FormBean(HttpServletRequest request,
Class<FormBean> beanClass) {
try{
//1, bean , request !
FormBean bean=beanClass.newInstance();
//2, BeanUtils request bean
Enumeration e = request.getParameterNames();//
while(e.hasMoreElements()){
String name = (String) e.nextElement(); //name gender birthday
String value = request.getParameter(name);
// 8 , FormBean string!
BeanUtils.setProperty(bean, name, value);
}
//3, FormBean
return bean;
}catch (Exception e) {
//
throw new RuntimeException(e);
}
}
// 2 : formbean , !
public static<T> T request2FormBean(HttpServletRequest request,
Class<T> beanClass) {
try{
//1, bean , request !
T bean=beanClass.newInstance();
//2, BeanUtils request bean
Enumeration e = request.getParameterNames();//
while(e.hasMoreElements()){
String name = (String) e.nextElement(); //name gender birthday
String value = request.getParameter(name);
BeanUtils.setProperty(bean, name, value);
}
//3, FormBean
return bean;
}catch (Exception e) {
//
throw new RuntimeException(e);
}
}
// 3 : FormBean ( string) domain Bean
public static void copyBean(Object src,Object dest){
//
//( FormBean Bean :Date )
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) {
/* :( value type )
*1, value null
*2, value String
*3, value
*4, SimpleDateFormat parse
*5, */
if(value==null){
return null;
}
String date=(String)value;
if("".equals(date.trim())){
return null;
}
// , Date
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(date);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}, Date.class);
try {
// BeanUtils bean
BeanUtils.copyProperties(dest, src);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 4, domain Bean
// new ,
public static <T> T request2Bean(HttpServletRequest request,Class<T> beanClass){
try{
//1, bean , request !
T bean = beanClass.newInstance();
//2, request ( )
Map map = request.getParameterMap();
//map{name=aa,password=bb,birthday=1990-09-09} bean(name=aa,password=dd,birthday=Date)
//3,
//( value Object Customer :Date )
ConvertUtils.register(new Converter(){
public Object convert(Class type, Object value) {
if(value==null){
return null;
}
String str = (String) value;
if(str.trim().equals("")){
return null;
}
// , Date
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(str);
} catch (Exception e) {
// ,
throw new RuntimeException(e);
}
}
}, Date.class);
//4, , map bean ( Customer)
// 8
BeanUtils.populate(bean, map);
//5, bean
return bean;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
// 5, id(UUID.randomUUID().toString())
public static String generateId(){
return UUID.randomUUID().toString();
}
// 6, md5 !
public static String md5(String message){
/*ServiceUtils ,
* md5 4 ( )*/
try {
MessageDigest md=MessageDigest.getInstance("md5");
byte[] md5=md.digest(message.getBytes());
BASE64Encoder encoder=new BASE64Encoder();
return encoder.encode(md5);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
AddCustomerServlet은 웹에 있습니다.controller 패키지
package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Customer;
import cn.itcast.formbean.FormBean;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
import cn.itcast.utils.Global;
import cn.itcast.utils.WebUtils;
public class AddCustomerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* :
* 1, Global ( ) request
* 2, WEB-INF/jsp/addcustomer.jsp*/
request.setAttribute("genders", Global.genders);
request.setAttribute("preferences", Global.preferences);
request.setAttribute("types", Global.types);
request.getRequestDispatcher("/WEB-INF/jsp/addcustomer.jsp").forward(request, response);
}
//
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//1,
request.setCharacterEncoding("utf-8");
//2, FormBean , validate
FormBean form=WebUtils.request2FormBean(request, FormBean.class);
boolean b=form.validate();
//2.1 , ,
if(!b){
// form map errors
request.setAttribute("form", form);
//request.getRequestDispatcher("/servlet/AddCustomerServlet").forward(request, response);
doGet(request, response);
return;
//request.setAttribute("message", "validate !");
//request.getRequestDispatcher("/message.jsp").forward(request, response);
}
//request.setAttribute("message", "validate !");
//2.2 , customer
Customer c =WebUtils.request2Bean(request, Customer.class);
c.setDescription(c.getDescription().trim());
//Customer :id, UUID ID
c.setId(WebUtils.generateId());
//3, Customer ,
BusinessService service=new BusinessServiceImpl();
service.add(c);
request.setAttribute("message", " !");
} catch (Exception e) {
// : ,
e.printStackTrace();
request.setAttribute("message", " !");
}
// ,
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
CopyOfListCustomerServlet은 웹에 있습니다.controller 패키지
package cn.itcast.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
public class CopyOfListCustomerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// !
try {
// , !
BusinessService service = new BusinessServiceImpl();
List list = service.getAll();
// list request jsp
request.setAttribute("list", list);
request.getRequestDispatcher("/WEB-INF/jsp/listcustomer.jsp").forward(request, response);
} catch (Exception e) {
// , , !
e.printStackTrace();
request.setAttribute("message", " !!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
DeletecustomerServlet은 웹에 있습니다.controller 패키지
package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
public class DeleteCustomerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//servlet doPost try [try_post]
// !
try {
String id=request.getParameter("id");
// service ! , !
BusinessService service = new BusinessServiceImpl();
service.delete(service.find(id));
// , message request jsp !
request.setAttribute("message", " ");
request.getRequestDispatcher("/message.jsp").forward(request,
response);
} catch (Exception e) {
// , , !
e.printStackTrace();
request.setAttribute("message", " ");
request.getRequestDispatcher("/message.jsp").forward(request,
response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
EditCustomerServlet은 웹에 있습니다.controller 패키지
package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Customer;
import cn.itcast.formbean.FormBean;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
import cn.itcast.utils.Global;
import cn.itcast.utils.WebUtils;
public class EditCustomerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* :
* 1, c.id Customer , request
* 1, Global ( ) request
* 2, WEB-INF/jsp/editcustomer.jsp*/
String id=request.getParameter("id");
// , Customer
BusinessService service=new BusinessServiceImpl();
Customer c=service.find(id);
request.setAttribute("c", c);
// , jsp
request.setAttribute("genders", Global.genders);
request.setAttribute("preferences", Global.preferences);
request.setAttribute("types", Global.types);
request.getRequestDispatcher("/WEB-INF/jsp/editcustomer.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
//1, Post , !
request.setCharacterEncoding("utf-8");
//2, FormBean , validate
FormBean form=WebUtils.request2FormBean(request, FormBean.class);
boolean b=form.validate();
//2.1 , ,
if(!b){
// form map errors
request.setAttribute("form", form);
//request.getRequestDispatcher("/servlet/AddCustomerServlet").forward(request, response);
doGet(request, response);
return;
//request.setAttribute("message", "validate !");
//request.getRequestDispatcher("/message.jsp").forward(request, response);
}
//request.setAttribute("message", "validate !");
//2.2 , customer
Customer c =WebUtils.request2Bean(request, Customer.class);
//3, Customer ,
BusinessService service=new BusinessServiceImpl();
service.update(c);
request.setAttribute("message", " !");
} catch (Exception e) {
// : ,
e.printStackTrace();
request.setAttribute("message", e);
}
// ,
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
ListCustomerServlet은 웹에 있습니다.controller 패키지
package cn.itcast.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.QueryInfo;
import cn.itcast.service.BusinessService;
import cn.itcast.service.impl.BusinessServiceImpl;
import cn.itcast.utils.WebUtils;
public class ListCustomerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// !
try {
// , QueryInfo !
QueryInfo info=WebUtils.request2Bean(request, QueryInfo.class);
// , !
BusinessService service = new BusinessServiceImpl();
PageBean pb=service.pageQuery(info);
//PageBean , request jsp
request.setAttribute("pb", pb);
request.getRequestDispatcher("/WEB-INF/jsp/listcustomer.jsp").forward(request, response);
} catch (Exception e) {
// , , !
e.printStackTrace();
request.setAttribute("message", e);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
batchinsert는 Junit에 있습니다.테스트 패키지
package junit.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import cn.itcast.exception.DaoException;
import cn.itcast.utils.JdbcUtils;
import cn.itcast.utils.WebUtils;
public class batchinsert {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
try {
conn=JdbcUtils.getConnection();
// String sql, PreparedStatement
String fields="id,name,gender,preference,type";
String sql="insert into customer("+fields+") values(?,?,?,?,?)";
st=conn.prepareStatement(sql);
//
for(int i=0;i<200;i++){
st.setString(1, WebUtils.generateId() + i);
st.setString(2, " " + i);
st.setString(3, " ");
st.setString(4, " ");
st.setString(5, " ");
st.addBatch();
if(i%50==0){
// , 50 !
st.executeBatch();
st.clearBatch();
}
}
st.executeBatch();
} catch (Exception e) {
// Dao , !
throw new DaoException();
}finally{
JdbcUtils.release(conn, st, rs);
}
}
}
테스트 위치는 Junit.test
싸다
package junit.test;
import java.util.HashMap;
import java.util.Map;
public class test {
private static Map errors=new HashMap();
public static void main(String[] args) {
System.out.println(validate("1231232121"));
}
public static boolean validate(String cellphone){
// , ,flag
boolean flag = true;
//3, 7-11
if(!cellphone.matches("\\d{7,11}") && cellphone!=null && !cellphone.trim().equals("")){
flag = false;
errors.put("cellphone", " 7-11 !");
}
// if(!name.matches("^([\u4e00-\u9fa5]+)$") || !name.matches("[A-Za-z]{2,10}"))
return flag;
}
public static boolean validate1(String name){
// , ,flag
boolean flag = true;
// , 2-10 (\u4e00-\u9fa5)
if(name==null || name.trim().equals("")){
flag = false;
errors.put("name", " !");
}else if(!name.matches("^([\u4e00-\u9fa5]{2,})$") && !name.matches("[A-Za-z]{2,10}")){
flag = false;
errors.put("name", " 2-10 !");
}
// if(!name.matches("^([\u4e00-\u9fa5]+)$") || !name.matches("[A-Za-z]{2,10}"))
return flag;
}
}
dao.properties는 src 클래스 디렉터리에 있습니다
CustomerDao=cn.itcast.dao.impl.CustomerDaoImpl
#CustomerDao=cn.itcast.dao.impl.UserDaoXmlImpl
db.properties는 src 클래스 디렉터리에 있습니다
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day14_customer?useUnicode=true&characterEncoding=utf-8
user=root
password=root
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=system
#password=itcast
사용된 제3자jar 패키지
jstl.jar
standard.jar
commons-beanutils-1.8.0.jar
commons-logging.jar
MySQL :mysql-connector-java-5.0.8-bin.jar
head.WebRoot 디렉토리에 jsp 위치
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> </title>
</head>
<body style="text-align: center;">
<h1> </h1>
<a href="${pageContext.request.contextPath}/servlet/AddCustomerServlet" target="main"> </a>
<a href="${pageContext.request.contextPath}/servlet/ListCustomerServlet" target="main"> </a>
</body>
</html>
index.WebRoot 디렉토리에 jsp 위치
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> </title>
<!-- :frameset body , -->
</head>
<frameset rows="20%,*">
<frame name="head" src="${pageContext.request.contextPath}/head.jsp" scrolling="no" noresize="noresize"/>
<frame name="main" src="#">
</frameset>
</html>
message.WebRoot 디렉토리에 jsp 위치
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> , </title>
</head>
<body>
${message }
${requestScope.message }
${form.errors.name }
</body>
</html>
ShowCalendar.js는 WebRoot/js 디렉토리에 있습니다.
//
// By Ziyue(http://www.web-v.com/)
// :
// <script type="text/javascript" src="${pageContext.request.contextPath }/js/ShowCalendar.js"></script>
// <input name="birthday" type="text" id="birthday" title=" " onClick="showCalendar(this.id)">
var today;
document.writeln("<div id='Calendar' style='position:absolute; z-index:1; visibility: hidden; filter:\"progid:DXImageTransform.Microsoft.Shadow(direction=135,color=#999999,strength=3)\"'></div>");
function getDays(month, year)
{
var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//
if (1 == month)
return ((0 == year % 4) && (0 != (year % 100))) || (0 == year % 400) ? 29 : 28;
else
return daysInMonth[month];
}
function getToday()
{
// , ,
this.now = new Date();
this.year = this.now.getFullYear();
this.month = this.now.getMonth();
this.day = this.now.getDate();
}
function getStringDay(str)
{
// , ,
var str=str.split("-")
this.now = new Date(parseFloat(str[0]),parseFloat(str[1])-1,parseFloat(str[2]));
this.year = this.now.getFullYear();
this.month = this.now.getMonth();
this.day = this.now.getDate();
}
function newCalendar() {
var parseYear = parseInt(document.all.Year.options[document.all.Year.selectedIndex].value);
var newCal = new Date(parseYear, document.all.Month.selectedIndex, 1);
var day = -1;
var startDay = newCal.getDay();
var daily = 0;
if ((today.year == newCal.getFullYear()) &&(today.month == newCal.getMonth()))
day = today.day;
var tableCal = document.all.calendar;
var intDaysInMonth =getDays(newCal.getMonth(), newCal.getFullYear());
for (var intWeek = 1; intWeek < tableCal.rows.length;intWeek++)
for (var intDay = 0;intDay < tableCal.rows[intWeek].cells.length;intDay++)
{
var cell = tableCal.rows[intWeek].cells[intDay];
if ((intDay == startDay) && (0 == daily))
daily = 1;
if(day==daily) // , Class
{
cell.style.background='#6699CC';
cell.style.color='#FFFFFF';
//cell.style.fontWeight='bold';
}
else if(intDay==6) //
cell.style.color='green';
else if (intDay==0) //
cell.style.color='red';
if ((daily > 0) && (daily <= intDaysInMonth))
{
cell.innerText = daily;
daily++;
}
else
cell.innerText = "";
}
}
function GetDate(InputBox)
{
var sDate;
//
if (event.srcElement.tagName == "TD")
if (event.srcElement.innerText != "")
{
sDate = document.all.Year.value + "-" + document.all.Month.value + "-" + event.srcElement.innerText;
eval("document.all."+InputBox).value=sDate;
HiddenCalendar();
}
}
function HiddenCalendar()
{
//
document.all.Calendar.style.visibility='hidden';
}
function showCalendar(InputBox)
{
var months = new Array(" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ");
var days = new Array(" "," ", " ", " ", " ", " ", " ");
var x,y,intLoop,intWeeks,intDays;
var DivContent;
var year,month,day;
var o=eval("document.all."+InputBox);
var thisyear; //
thisyear=new getToday();
thisyear=thisyear.year;
today = o.value;
if(isDate(today))
today = new getStringDay(today);
else
today = new getToday();
//
x=o.offsetLeft;
y=o.offsetTop;
while(o=o.offsetParent)
{
x+=o.offsetLeft;
y+=o.offsetTop;
}
document.all.Calendar.style.left=x+2;
document.all.Calendar.style.top=y+20;
document.all.Calendar.style.visibility="visible";
// (border-color:#9DBAF7)
DivContent="<table border='0' cellspacing='0' style='border:1px solid #0066FF; background-color:#EDF2FC'>";
DivContent+="<tr>";
DivContent+="<td style='border-bottom:1px solid #0066FF; background-color:#C7D8FA'>";
//
DivContent+="<select name='Year' id='Year' onChange='newCalendar()' style='font-family:Verdana; font-size:12px'>";
for (intLoop = thisyear - 35; intLoop < (thisyear + 2); intLoop++)
DivContent+="<option value= " + intLoop + " " + (today.year == intLoop ? "Selected" : "") + ">" + intLoop + "</option>";
DivContent+="</select>";
//
DivContent+="<select name='Month' id='Month' onChange='newCalendar()' style='font-family:Verdana; font-size:12px'>";
for (intLoop = 0; intLoop < months.length; intLoop++)
DivContent+="<option value= " + (intLoop + 1) + " " + (today.month == intLoop ? "Selected" : "") + ">" + months[intLoop] + "</option>";
DivContent+="</select>";
DivContent+="</td>";
DivContent+="<td style='border-bottom:1px solid #0066FF; background-color:#C7D8FA; font-weight:bold; font-family:Wingdings 2,Wingdings,Webdings; font-size:16px; padding-top:2px; color:#4477FF; cursor:hand' align='center' title=' ' onClick='javascript:HiddenCalendar()'>S</td>";
DivContent+="</tr>";
DivContent+="<tr><td align='center' colspan='2'>";
DivContent+="<table id='calendar' border='0' width='100%'>";
//
DivContent+="<tr>";
for (intLoop = 0; intLoop < days.length; intLoop++)
DivContent+="<td align='center' style='font-size:12px'>" + days[intLoop] + "</td>";
DivContent+="</tr>";
//
for (intWeeks = 0; intWeeks < 6; intWeeks++)
{
DivContent+="<tr>";
for (intDays = 0; intDays < days.length; intDays++)
DivContent+="<td onClick='GetDate(\"" + InputBox + "\")' style='cursor:hand; border-right:1px solid #BBBBBB; border-bottom:1px solid #BBBBBB; color:#215DC6; font-family:Verdana; font-size:12px' align='center'></td>";
DivContent+="</tr>";
}
DivContent+="</table></td></tr></table>";
document.all.Calendar.innerHTML=DivContent;
newCalendar();
}
function isDate(dateStr)
{
var datePat = /^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/;
var matchArray = dateStr.match(datePat);
if (matchArray == null) return false;
var month = matchArray[3];
var day = matchArray[5];
var year = matchArray[1];
if (month < 1 || month > 12) return false;
if (day < 1 || day > 31) return false;
if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;
if (month == 2)
{
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) return false;
}
return true;
}
igg.tld는 WebRoot/WEB-INF 디렉토리에 있음
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>SimpleTagLibrary</short-name>
<uri>www.igg.com</uri>
<function>
<name>leftStr</name>
<function-class>cn.itcast.utils.MyEL</function-class>
<function-signature>java.lang.String leftStr( java.lang.String , java.lang.Integer)</function-signature>
</function>
</taglib>
addcustomer.jsp는 WebRoot/WEB-INF/jsp 디렉토리에 있음
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> </title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/ShowCalendar.js"></script>
<script type="text/javascript">
//js , , form
function joinStr(){
var o1=document.getElementsByName("pre");
var str="";
for(var i=0;i<o1.length;i++){
//alert(o1[i].value);
if(o1[i].checked){
str+=o1[i].value+",";
}
}
str=str.substr(0,str.length-1);
var form=document.getElementById("form_id");
var hiddenInput=document.createElement("input");
hiddenInput.type="hidden";
hiddenInput.name="preference";
hiddenInput.value=str;
//alert(str);
form.appendChild(hiddenInput);
return true;
}
</script>
</head>
<body style="text-align: center;">
<form id="form_id" action="${pageContext.request.contextPath }/servlet/AddCustomerServlet" method="post" onsubmit="return joinStr()">
<table border="1" width="50%">
<tr>
<td> </td>
<td>
<input type="text" name="name" value="${param.name }">
<span>${form.errors.name }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="g" items="${genders}">
<input type="radio" name="gender" value="${g }" ${param.gender==g?'checked':'' }/>${g }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="birthday" id="birthday" onClick="showCalendar(this.id)" value="${param.birthday }" >
<span>${form.errors.birthday }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="cellphone" value="${param.cellphone }">
<span>${form.errors.cellphone }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="email" value="${param.email }">
<span>${form.errors.email }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="pre" items="${preferences}">
<input type="checkbox" name="pre" value="${pre }" ${fn:contains(param.preference,pre)?'checked':'' }/>${pre }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="t" items="${types}">
<input type="radio" name="type" value="${t }" ${param.type==t?'checked':'' }>${t }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<textarea rows="5" cols="60" name="description">
${fn:trim(param.description) }
</textarea>
</td>
</tr>
<tr>
<td>
<input type="reset" value=" ">
</td>
<td>
<input type="submit" value=" ">
</td>
</tr>
</table>
</form>
</body>
</html>
editcustomer.jsp는 WebRoot/WEB-INF/jsp 디렉토리에 있음
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title> </title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/ShowCalendar.js"></script>
<script type="text/javascript">
//js , , form
function joinStr(){
var o1=document.getElementsByName("pre");
var str="";
for(var i=0;i<o1.length;i++){
//alert(o1[i].value);
if(o1[i].checked){
str+=o1[i].value+",";
}
}
str=str.substr(0,str.length-1);
var form=document.getElementById("form_id");
var hiddenInput=document.createElement("input");
hiddenInput.type="hidden";
hiddenInput.name="preference";
hiddenInput.value=str;
//alert(str);
form.appendChild(hiddenInput);
return true;
}
</script>
</head>
<body style="text-align: center;">
<form id="form_id" action="${pageContext.request.contextPath }/servlet/EditCustomerServlet" method="post" onsubmit="return joinStr()">
<table border="1" width="50%">
<input type="hidden" name="id" value="${c.id }">
<tr>
<td> </td>
<td>
<input type="text" name="name" value="${c.name }">
<span>${form.errors.name }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="g" items="${genders}">
<input type="radio" name="gender" value="${g }" ${c.gender==g?'checked':'' }/>${g }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="birthday" id="birthday" onClick="showCalendar(this.id)" value="${c.birthday }" >
<span>${form.errors.birthday }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="cellphone" value="${c.cellphone }">
<span>${form.errors.cellphone }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="text" name="email" value="${c.email }">
<span>${form.errors.email }</span>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="pre" items="${preferences}">
<input type="checkbox" name="pre" value="${pre }" ${fn:contains(c.preference,pre)?'checked':'' }/>${pre }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<c:forEach var="t" items="${types}">
<input type="radio" name="type" value="${t }" ${c.type==t?'checked':'' }>${t }
</c:forEach>
</td>
</tr>
<tr>
<td> </td>
<td>
<textarea rows="5" cols="60" name="description">
${fn:trim(c.description) }
</textarea>
</td>
</tr>
<tr>
<td>
<input type="reset" value=" ">
</td>
<td>
<input type="submit" value=" ">
</td>
</tr>
</table>
</form>
</body>
</html>
listcustomer.jsp는 WebRoot/WEB-INF/jsp 디렉토리에 있음
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="/WEB-INF/igg.tld" prefix="igg"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> </title>
<style type="text/css">
.even{background-color: #FFFF00}
.odd{background-color: #FFCCFF}
tr:hover{background-color: #FF99FF}
a:link{text-decoration: none}
</style>
<script type="text/javascript">
function deleteById(id){
if(window.confirm(" ?")){
window.location.href='${pageContext.request.contextPath}/servlet/DeleteCustomerServlet?id='+id;
}
}
</script>
</head>
<body style="text-align: center;">
<table frame="border" width="86%" >
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<c:forEach var="c" items="${requestScope.pb.list}" varStatus="status">
<tr class="${status.count%2==0?'even':'odd' }">
<td>${c.name }</td>
<td>${c.gender }</td>
<td>${c.birthday }</td>
<td>${c.cellphone }</td>
<td>${c.email }</td>
<td>${c.preference }</td>
<td>${c.type }</td>
<td>${igg:leftStr(c.description,10) }</td>
<td>
<a href="${pageContext.request.contextPath }/servlet/EditCustomerServlet?id=${c.id }"> </a>
<a href="javascript:void(0)" onclick="deleteById('${c.id }')"> </a>
</td>
<tr>
</c:forEach>
</table>
<hr/>
<script type="text/javascript">
function go(page){
// page 0 , ''
var total_page=document.getElementById("totalPage_id").innerHTML;
// ${pb.totalPage}
var page_size=document.getElementById("pageSize_id").value;
//alert(page);
//alert(total_page);
//alert(page>parseInt(total_page));
if(page<1){
alert(" ");
document.getElementById("gotoPage_id").value='';
}else if(page>${pb.totalPage}){
alert(" "+total_page+" ");
document.getElementById("gotoPage_id").value='';
}else if(page==parseInt(page)){
//alert(" ");
window.location="${pageContext.request.contextPath}/servlet/ListCustomerServlet?currentPage="+page+"&pageSize="+page_size;
}
}
function changeSize(oldSize,newSize){
// size 0 99, oldsize
if(newSize<1){
alert(" ");
document.getElementById("pageSize_id").value=oldSize;
}else if(newSize>99){
alert(" 100 ");
document.getElementById("pageSize_id").value=oldSize;
}else if(newSize==parseInt(newSize)){
//alert(" ");
location.href = '${pageContext.request.contextPath}/servlet/ListCustomerServlet?pageSize=' + newSize;
}
}
</script>
${pb.totalRecord }
<input type="text" id="pageSize_id" value="${pb.pageSize }" style="width: 15px;" maxlength="2" onchange="changeSize('${pb.pageSize }',this.value)"/>
${pb.pageSize }
<span id="totalPage_id">${pb.totalPage }</span>
${pb.currentPage}
<c:if test="${pb.currentPage>5}">
<a href="javascript:void(0)" onclick="go(1)"> </a>
</c:if>
<c:if test="${pb.currentPage!=1}">
<a href="javascript:void(0)" onclick="go(${pb.previousPage})"> </a>
</c:if>
<c:forEach var="i" items="${pb.pageBar}">
<c:if test="${i==pb.currentPage}">
<font color='red'>${i}</font>
</c:if>
<c:if test="${i!=pb.currentPage}">
<a href="javascript:void(0)" onclick="go(${i})">
${i }</a>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage!=pb.totalPage}">
<a href="javascript:void(0)" onclick="go(${pb.nextPage})"> </a>
</c:if>
<c:if test="${pb.currentPage<pb.totalPage-5}">
<a href="javascript:void(0)" onclick="go(${pb.totalPage} )"> </a>
</c:if>
<input type="text" id="gotoPage_id" style="width: 20px" onchange="go(this.value)"/>
</body>
</html>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
SQLite의 query로 망설임이것은 내가 처음 안드로이드 응용 프로그램 개발에서 망설이고, 그 후 해결 된 방법을 비망록으로 철자하고 있습니다. java에서 SQLite를 이용한 애플리케이션을 작성하는 동안 EditText에 입력된 item이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.