使用struts2实现CRUD和文件上传

文件目录

action类

FileAction包

package com.zking.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ModelDriven;
import com.zking.dao.FileDao;
import com.zking.entity.MyFile;

public class FileAction implements  ModelDriven<MyFile>{
	private  FileDao  fileDao=new FileDao();
	private MyFile  my=new  MyFile();
	
	@Override
	public MyFile getModel() {
		// TODO Auto-generated method stub
		return my;
	}
	
	private File  img;//这个名字必须和提交的页面name属性名一样
	
	private String imgContentType;
	
	private String imgFileName;

	public File getImg() {
		return img;
	}

	public void setImg(File img) {
		this.img = img;
	}

	public String getImgContentType() {
		return imgContentType;
	}

	public void setImgContentType(String imgContentType) {
		this.imgContentType = imgContentType;
	}

	public String getImgFileName() {
		return imgFileName;
	}

	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}
	
	
	
	public  String testUpload() throws Exception {
		//System.out.println("file"+this.img);
		//System.out.println(this.imgContentType+","+this.imgFileName);
		MyFile mf=new  MyFile();
		//使用当前文件上传的时间戳做为数据库的主键保存确保唯一性
		Long  fid=System.currentTimeMillis();//获得时间戳
		//设置数据的值
		mf.setFileId(fid+"");
		mf.setRealName(this.imgFileName);
		mf.setContentType(this.imgContentType);
		//用户的文件在这里,然后调用方法传过去
		this.uploadImg(this.img,fid+"");
		//上传成功后,把图片信息保存到数据库
		fileDao.save(mf);
		return "tolist";
	}
	
	
	private   void uploadImg(File  file,String fileId) throws Exception {
		//将用户传递过来的文件分解成io流
		//在写入到本地服务器中
		
		File  f=new File("E:\\x\\"+fileId);//保存的路径
		
		try {
			FileInputStream fis=new  FileInputStream(file);//读的字节流
			FileOutputStream  fos=new  FileOutputStream(f);//写给他
			byte[] b=new  byte[100];
			while(fis.read(b)!=-1) {
				fos.write(b);
				fos.flush();
			}
			fis.close();
			fos.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public  String list() {
		HttpServletRequest req = ServletActionContext.getRequest();
		HttpSession session = req.getSession();
		   List<MyFile> myFilelist = fileDao.list();
		   session.setAttribute("files", myFilelist);
		return "uploadIndex";
	}
	
	
	//文件下载,接收uploadIndex传过来的值
	public  String  downLoad() {
		HttpServletResponse resp = ServletActionContext.getResponse();
		//内容类型
	      resp.setContentType(my.getContentType());
	      //设置响应头
	      resp.setHeader("Content-Disposition","attachment;filename=" + my.getRealName());//文件名
		  File   file=new  File("E:\\x\\"+my.getFileId());
	      try {
			FileInputStream  fis=new  FileInputStream(file);
			//响应带着这个字节流去用户
			//将服务器上面的文件通过读取字节流读取到,然后写入到响应的字节流中发给用户
			OutputStream os = resp.getOutputStream();
			byte[] bs=new  byte[100];
			while(fis.read(bs)!=-1) {
				os.write(bs);
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	      
		return null;
	}

	
	
	
	

}

LfAction包

package com.zking.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ModelDriven;
import com.zking.dao.LfDao;
import com.zking.entity.UserLf;

public class LfAction  implements  ModelDriven<UserLf>{

	private  UserLf  l=new  UserLf();
	private  LfDao  lfDao=new  LfDao();
	@Override
	public UserLf getModel() {
		// TODO Auto-generated method stub
		return l;
	}
	
	public String save() {
		int n = lfDao.save(l);
		if(n>0) {
			return  "success";
		}else {
			return  "add";
		}
	}
	
	
	public String  list() {
		HttpServletRequest req = ServletActionContext.getRequest();
		List<UserLf> lisst = lfDao.list(l, null);
		req.getSession().setAttribute("lfs", lisst);
		return "index";
	}
	
	
	public String  delete() throws IOException {
		int n = lfDao.delete(l);
		HttpServletResponse resp = ServletActionContext.getResponse();
		if(n>0) {
			return "success";
		}else {
			PrintWriter  out=resp.getWriter();
			out.write("<script>alert('删除失败')</script>");
			return "index";
		}
	}
	
	
	
	public  String  update() {
		int n = lfDao.update(l);
		if(n>0) {
			return  "success";
		}else {
			return "goUpdate";
		}
	}
	
	
	public  String  goUpdate() {
		UserLf f = lfDao.getById(l);
		ServletActionContext.getRequest().getSession().setAttribute("b", f);
		return "goUpdate";
	}
	
	

}

dao类

 BaseDao包

package com.zking.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.zking.util.DBAccess;
import com.zking.util.PageBean;




public class BaseDao<T> {
	
	public static interface CallBack<E>{
		public List<E> forEach(ResultSet rs) throws SQLException;
	}
	
	public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack){
		//1.绗竴娆℃煡璇㈣繑鍥炴?昏褰曟暟
		//2.绗簩娆℃煡璇㈣繑鍥炴寚瀹氶〉鐮佹暟骞舵弧瓒虫潯浠剁殑璁板綍闆?
		
		Connection conn=null;
		PreparedStatement stmt=null;
		ResultSet rs=null;
		try {
			conn=DBAccess.getConnection();
			//鍒ゆ柇鏄惁鍒嗛〉
			if(null!=pageBean&&pageBean.isPagination()) {
				//绗竴娆℃煡璇㈣繑鍥炴?昏褰曟暟
				String countSql=this.getCountSql(sql);
				stmt=conn.prepareStatement(countSql);
				rs=stmt.executeQuery();
				if(rs.next()) {
					Object obj=rs.getObject(1);
					pageBean.setTotal(Integer.parseInt(obj.toString()));
				}
				//绗簩娆℃煡璇㈣繑鍥炴寚瀹氶〉鐮佹暟骞舵弧瓒虫潯浠剁殑鍒嗛〉缁撴灉闆?
				sql=this.getPagerSql(sql, pageBean);
			}
			stmt=conn.prepareStatement(sql);
			rs=stmt.executeQuery();
			//閬嶅巻缁撴灉闆?
			return callBack.forEach(rs);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			DBAccess.close(conn, stmt, rs);
		}
		return null;
	}
	
	/**
	 * 灏嗘櫘閫歋QL璇彞杞崲鎴愭煡璇㈡?昏褰曟暟鐨凷QL璇彞
	 * @param sql
	 * @return
	 */
	private String getCountSql(String sql) {
		return "select count(1) from ("+sql+") t1";
	}
	
	/**
	 * 灏嗘櫘閫歋QL璇彞杞崲鎴愭煡璇㈠垎椤佃褰曢泦鐨凷QL璇彞
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getPagerSql(String sql,PageBean pageBean) {
		return sql+" Limit "+pageBean.getStartIndex()+","+pageBean.getRows();
	}
	/**
	 * 增删改用到的半成品方法
	 * @param sql
	 * @return
	 */
	protected int executeUpdate(String sql) {
		int n=0;
		Connection con=null;
		PreparedStatement ps=null;
		try {
			//连接数据库
			con=DBAccess.getConnection();
			ps=con.prepareStatement(sql);
			n=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			DBAccess.close(con, ps, null);
		}
		return n;
	}
	
	
	
	
	
}

FileDao包

package com.zking.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zking.entity.MyFile;

public class FileDao extends  BaseDao<MyFile>{
	
	
	//保存到数据库
	public  int save(MyFile  mf) {
		String sql="insert  into  t_file(file_id,real_name,content_type) values('"+mf.getFileId()+"','"+mf.getRealName()+"','"+mf.getContentType()+"')  ";
		return this.executeUpdate(sql);
	}
	
	//查询出来给用户下载
	public  List<MyFile>  list(){
		String  sql="select  *  from  t_file";
		return  this.executeQuery(sql, null, new  CallBack<MyFile>() {

			@Override
			public List<MyFile> forEach(ResultSet rs) throws SQLException {
				List<MyFile>  myfiles=new  ArrayList<MyFile>();
			     MyFile  m=new  MyFile();
			     while(rs.next()) {
			    	 m=new MyFile();
			    	 m.setFileId(rs.getString("file_id"));
			    	 m.setContentType(rs.getString("content_type"));
			    	 m.setRealName(rs.getString("real_name"));
			    	 m.setUpdateDatetime(rs.getTimestamp("update_datetime"));
			    	 myfiles.add(m);
			     }
				return myfiles;
			}
			
		});
	}
	

}

LfDao包

package com.zking.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.zking.entity.UserLf;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;

public class LfDao extends BaseDao<UserLf> {

	/**
	 * 增加
	 * 
	 * @param l
	 * @return
	 */
	public int save(UserLf userLf) {
		String sql = "insert  into  user_lf(user_name,user_age,user_sex,user_bz)  values('" + userLf.getUserName() + "','"
				+ userLf.getUserAge() + "','" + userLf.getUserSex() + "','" + userLf.getUserBz() + "')";
		return this.executeUpdate(sql);
	}

	/**
	 * 修改
	 * 
	 * @param l
	 */
	public int update(UserLf userLf) {
		String sql = "update user_lf set user_name='" + userLf.getUserName() + "',user_age='" + userLf.getUserAge()
				+ "',user_sex='" + userLf.getUserSex() + "',user_bz='" + userLf.getUserBz() + "' where  user_id="
				+ userLf.getUserId();
		return this.executeUpdate(sql);
	}

	/**
	 * 删除
	 * 
	 * @param l
	 * @return
	 */
	public int delete(UserLf userLf) {
		String sql = "delete from user_lf where  user_id="+userLf.getUserId();
		return this.executeUpdate(sql);
	}

	/**
	 * 查询全部
	 * 
	 * @param l
	 * @return
	 */
	public List<UserLf> list(UserLf userLf, PageBean pageBean) {
		String sql = "select  *  from user_lf  where  1=1  ";
		if (StringUtils.isNotBlank(userLf.getUserName())) {
			sql += " and  user_name  like  '%" + userLf.getUserName() + "%'";
		}
		return this.executeQuery(sql, pageBean, new CallBack<UserLf>() {

			@Override
			public List<UserLf> forEach(ResultSet rs) throws SQLException {
				List<UserLf> userList = new ArrayList<>();
				UserLf user = null;
				while (rs.next()) {
					user = new UserLf();
					user.setUserId(rs.getLong("user_id"));
					user.setUserName(rs.getString("user_name"));
					user.setUserAge(rs.getString("user_age"));
					user.setUserSex(rs.getString("user_sex"));
					user.setUserBz(rs.getString("user_bz"));
					userList.add(user);
				}
				return userList;
			}
		});

	}

	public UserLf getById(UserLf userLf) {
		String sql = "select  *   from user_lf  where  user_id="+userLf.getUserId();
		List<UserLf> lf = this.executeQuery(sql, null, new CallBack<UserLf>() {

			@Override
			public List<UserLf> forEach(ResultSet rs) throws SQLException {
				List<UserLf> usreList = new ArrayList<>();
				UserLf user = null;
				while (rs.next()) {
					user = new UserLf();
					user.setUserId(rs.getLong("user_id"));
					user.setUserName(rs.getString("user_name"));
					user.setUserAge(rs.getString("user_age"));
					user.setUserSex(rs.getString("user_sex"));
					user.setUserBz(rs.getString("user_bz"));
					usreList.add(user);
				}

				return usreList;
			}
		});
		if (null != lf && lf.size() > 0) {
			return lf.get(0);
		} else {
			return null;
		}

	}

}

entity类

MyFile包

package com.zking.entity;

import java.sql.Timestamp;

public class MyFile {

	private  String fileId;
	
	private  String realName;
	
	private  String contentType;
	
	private  Timestamp updateDatetime;

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public String getRealName() {
		return realName;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public Timestamp getUpdateDatetime() {
		return updateDatetime;
	}

	public void setUpdateDatetime(Timestamp updateDatetime) {
		this.updateDatetime = updateDatetime;
	}

	@Override
	public String toString() {
		return "MyFile [fileId=" + fileId + ", realName=" + realName + ", contentType=" + contentType
				+ ", updateDatetime=" + updateDatetime + "]";
	}
	
	
}

UserLf包

package com.zking.entity;


public class UserLf {
	
	private Long  userId;
	
	private String userName;
	
	private String userAge;
	
	private  String userSex;
	
	private  String  userBz;

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserAge() {
		return userAge;
	}

	public void setUserAge(String userAge) {
		this.userAge = userAge;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
	}

	public String getUserBz() {
		return userBz;
	}

	public void setUserBz(String userBz) {
		this.userBz = userBz;
	}

	@Override
	public String toString() {
		return "UserLf [userId=" + userId + ", userName=" + userName + ", userAge=" + userAge + ", userSex=" + userSex
				+ ", userBz=" + userBz + "]";
	}

	
	
	
	
	
	

}

util类

 DBAccess帮助类

package com.zking.util;

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 DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.jdbc.Driver".equals(driver);
	}

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

EncodingFilter帮助类

package com.zking.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 中文乱码处理
 * 
 */
public class EncodingFilter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFilter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		req.setCharacterEncoding(this.encoding);
//		if (req.getMethod().equalsIgnoreCase("post")) {
//			req.setCharacterEncoding(this.encoding);
//		} else {
//			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
//			Set set = map.keySet();// 取出所有参数名
//			Iterator it = set.iterator();
//			while (it.hasNext()) {
//				String name = (String) it.next();
//				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
//				for (int i = 0; i < values.length; i++) {
//					values[i] = new String(values[i].getBytes("ISO-8859-1"),
//							this.encoding);
//				}
//			}
//		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

PageBean帮助类

package com.zking.util;

import java.io.Serializable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean implements Serializable {

	//页码
	private int page=1;
	//每页显示条数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页标记
	private boolean pagination=true;
	//上一次请求的路径
	private String url;
	//请求参数Map集合
	private Map<String,String[]> map;
	
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public Map<String, String[]> getMap() {
		return map;
	}
	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}
	public int getPage() {
		return page;
	}
	public void setPage(int page) {
		this.page = page;
	}
	public int getRows() {
		return rows;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}
	public int getTotal() {
		return total;
	}
	public void setTotal(int total) {
		this.total = total;
	}
	public boolean isPagination() {
		return pagination;
	}
	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}
	
	//重载setPage/setRows/setPagination方法
	public void setPage(String page) {
		if(null!=page&&!"".equals(page))
			this.page=Integer.parseInt(page);
	}
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows))
			this.rows=Integer.parseInt(rows);
	}
	public void setPagination(String pagination) {
		if(null!=pagination&&!"".equals(pagination))
			this.pagination=Boolean.parseBoolean(pagination);
	}
	
	public void setRequest(HttpServletRequest req) {
		//获取前端提交的page/rows/pagination参数
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		
		//设置属性
		this.setPage(page);
		this.setPagination(pagination);
		this.setRows(rows);
		
		//设置上一次请求的路径
		//第一次请求:
		//http://localhost:8080/项目名/请求路径.action?page=1
		//第二次请求:下一页  page=2
		//项目名+请求路径.action
		//req.getContextPath()+req.getServletPath()==req.getRequestURI()
		this.url=req.getRequestURI();
		
		//获取请求参数集合
		// checkbox name='hobby'
		// Map<String,String[]> hobby==key  value==new String[]{"篮球","足球",..}
		this.map=req.getParameterMap();
	}
	
	/**
	 * 获取分页的起始位置
	 * @return
	 */
	public int getStartIndex() {
		//第1页:(1-1)*10  ==0    limit 0,10
		//第2页:(2-1)*10  ==10   limit 10,10
		//..
		return (this.page-1)*this.rows;
	}
	
	//获取末页、上一页、下一页
	/**
	 * 获取末页
	 * @return
	 */
	public int getMaxPager() {
		int maxPager=this.total/this.rows;
		if(this.total%this.rows!=0)
			maxPager++;
		return maxPager;
	}
	
	/**
	 * 获取上一页
	 * @return
	 */
	public int getPreviousPager() {
		int previousPager=this.page-1;
		if(previousPager<=1)
			previousPager=1;
		return previousPager;
	}
	
	/**
	 * 获取下一页
	 * @return
	 */
	public int getNextPager() {
		int nextPager=this.page+1;
		if(nextPager>getMaxPager())
			nextPager=getMaxPager();
		return nextPager;
	}
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", url=" + url + ", map=" + map + "]";
	}
	
}











PingYinUtil

package com.zking.util;

import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;


/**
 * 拼音工具类,能将汉字转换成拼音的首字母
 */
public class PinYinUtil {
	/* 用于中文判断的正则表达式 */
	private static final String regexStr = "[\u4e00-\u9fa5]";

	/**
	 * 将一个字符串中的汉字转换成拼音首字母、非汉字则不变
	 * 
	 * @param cn
	 *            String
	 * @return String
	 */
	public static String toPinyin(String cn) {
		String pinyin = null;
		if (null == cn || 0 == cn.trim().length()) {
			return pinyin;
		}

		/* 去掉字符串前后的空格 */
		cn = cn.trim();
		char[] chineseCharacterArr = cn.toCharArray(); // 转换成汉字字符数组
		char[] letteCharacterArr = new char[chineseCharacterArr.length]; // 字母字符数组
		for (int i = 0; i < chineseCharacterArr.length; i++) {
			// 得到汉字拼音的首字母
			letteCharacterArr[i] = getFirstLetterFromPinyin(chineseCharacterArr[i]);
		}

		if (0 != letteCharacterArr.length) {
			pinyin = new String(letteCharacterArr);
			pinyin = pinyin.toUpperCase();
		}
		return pinyin;
	}

	/* 得到一个汉字的拼音的首字母 */
	private static char getFirstLetterFromPinyin(char cn) {
		// 判断cn是否为一个合法的汉字,不是则直接返回cn
		if (!isChineseCharacters(cn)) {
			return cn;
		}

		String[] pyArr = PinyinHelper.toHanyuPinyinStringArray(cn);
		char py = pyArr[0].charAt(0);
		return py;
	}

	/**
	 * 判断字符是否为一个汉字
	 * 
	 * @param cn
	 *            char
	 * @return boolean
	 */
	public static boolean isChineseCharacters(char cn) {
		boolean b = false;
		if (Pattern.matches(regexStr, String.valueOf(cn))) {
			b = true;
		}
		return b;
	}

	public static void main(String[] args) {
		String s = "任保存并加入题库";
		System.out.println(PinYinUtil.toPinyin(s).toLowerCase());
	}

}

StringUtils

package com.zking.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

config

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=123


#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123


#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888


#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/t264?useUnicode=true&characterEncoding=UTF-8&useSSL=false
user=root
pwd=123



struts-base.xml

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
	"http://struts.apache.org/dtds/struts-2.5.dtd">
	<!-- 根标签 -->
   <struts>
        <!-- name=是否国际化   value=编码-->
       <constant value="UTF-8" name="struts.i18n.encoding"/>
       <!-- name=是否使用开发模式  -->
       <constant value="true" name="struts.devMode"/>
      <!-- name=是否热加载   -->
      <constant value="true" name="struts.configuration.xml.reload"/>
       <!-- name=国际化热加载 -->
       <constant value="true" name="struts.i18n.reload"/>
       <!-- name动态运行前端用户传的方法 -->
       <constant value="true" name="struts.enable.DynamicMethodInvocation"/>
        
        <!-- name=名字    extends=继承了struts-default.xml的常量    abstract=这个包是抽象的 -->
	    <package name="base" abstract="true" extends="struts-default">
         <!-- 全局变量,怎么调方法    .* -->
          <global-allowed-methods>regex:.*</global-allowed-methods>
  
        </package>
   </struts>

 struts-sys.xml

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

	<package extends="base" namespace="/sys" name="tese">
		<action name="LfAction_*" method="{1}" class="com.zking.action.LfAction">

			<result name="index" type="redirect">/index.jsp</result>

			<result name="success" type="redirectAction">/LfAction_list</result>

			<result name="goUpdate" type="redirect">/update.jsp</result>

			<result name="add" type="redirect">/addLf.jsp</result>

		</action>
	</package>

	<package extends="base" name="fileupload">
		<action name="fileAction_*" method="{1}"
			class="com.zking.action.FileAction">
			<result name="tolist" type="redirectAction">/fileAction_list</result>
			<result name="uploadIndex" type="redirect">/uploadIndex.jsp</result>
		</action>
	</package>


</struts>

struts.xml(核心配置文件)

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

用的Mven项目,导入的依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zking</groupId>
    <artifactId>struts04</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>struts04 Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>

        <junit.version>4.12</junit.version>

        <struts.version>2.5.13</struts.version>

        <mysql.version>5.1.44</mysql.version>

        <pinyin4j.version>2.5.1</pinyin4j.version>

        <jstl.version>1.2</jstl.version>

        <standard.version>1.1.2</standard.version>

    </properties>


    <dependencies>


        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>${junit.version}</version>

            <scope>test</scope>

        </dependency>

        <!-- struts2 -->

        <dependency>

            <groupId>org.apache.struts</groupId>

            <artifactId>struts2-core</artifactId>

            <version>${struts.version}</version>

        </dependency>

        <!-- pinyin4j -->

        <dependency>

            <groupId>com.belerweb</groupId>

            <artifactId>pinyin4j</artifactId>

            <version>${pinyin4j.version}</version>

        </dependency>

        <!-- mysql -->

        <dependency>

            <groupId>mysql</groupId>

            <artifactId>mysql-connector-java</artifactId>

            <version>${mysql.version}</version>

        </dependency>

        <!-- C Tag -->

        <dependency>

            <groupId>jstl</groupId>

            <artifactId>jstl</artifactId>

            <version>${jstl.version}</version>

        </dependency>


        <dependency>

            <groupId>taglibs</groupId>

            <artifactId>standard</artifactId>

            <version>${standard.version}</version>

        </dependency>

    </dependencies>


    <build>

        <finalName>struts02</finalName>


        <plugins>


            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <version>3.7.0</version>


                <configuration>

                    <source>1.7</source>

                    <target>1.7</target>

                    <encoding>UTF-8</encoding>

                </configuration>

            </plugin>

        </plugins>

    </build>

</project>
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值