查询所有客户
异步获取客户级别
ajax的代码
var url = "${pageContext.request.contextPath}/dict_findByCode.action";
var param ={"dict_type_code":"006"};
//alert(param.dict_type_code);
$.post(url,param,function(data){
//遍历
$(data).each(function(i,n){
//alert(i+":"+n);
//alert(i+":"+n.dict_item_name);
//alert(this.dict_item_name);
//先获取值栈中的值,使用EL表达式
var vsId = "${model.level.dict_id}";
//值栈中的id值和变量的id值相同,让其选中
if(vsId == n.dict_id){
//jq的dom操作
$("#levelId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
}else{
$("#levelId").append("<option value='"+n.dict_id+"' >"+n.dict_item_name+"</option>");
}
});
},"json");
DictAction的代码
public String findByCode(){
//调用业务层
// System.out.println("--------"+dict.getDict_type_code());
List<Dict> list = dictService.findByCode(dict.getDict_type_code());
// List<Dict> list = dictService.findByCode("006");
//使用fastjson把list转换成json字符串
String jsonString = FastJsonUtil.toJSONString(list);
//把json字符串写到浏览器
HttpServletResponse response = ServletActionContext.getResponse();
//输出
FastJsonUtil.write_json(response, jsonString);
return NONE;
}
CustomerAction的分页查询的代码
public String findByPage(){
//调用service业务层
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
//拼接查询的条件
String cust_name = customer.getCust_name();
if(cust_name !=null && !cust_name.trim().isEmpty()){
//说明,客户的名称输入值了
criteria.add(Restrictions.like("cust_name", "%"+cust_name+"%"));
}
//拼接客户级别
Dict level = customer.getLevel();
if(level!=null && !level.getDict_id().trim().isEmpty()){
//说明,客户的级别肯定选择了一个
criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
}
Dict source = customer.getSource();
if(source!=null && !source.getDict_id().trim().isEmpty()){
//说明,客户的级别肯定选择了一个
criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
}
//查询
PageBean<Customer> page = customerService.findByPage(pageCode,pageSize,criteria);
//压栈
ValueStack vs = ActionContext.getContext().getValueStack();
//栈顶是map<"page",page对象>
vs.set("page", page);
return "page";
}
添加客户功能(文件上传)
1、跳转到客户的添加页面,需要通过ajax来显示客户的级别,客户的来源和客户的行业
2、添加文件上传的选择项
3、客户端三个注意事项
method="post"
enctype="multipart/form-data"
<INPUT type="file" name="upload"/>
4、Struts2框架使用拦截器完成文件上传,并且底层使用也是FileUpload开源的组件
提供FileUpload拦截器,用于解析multipart/form-data编码格式请求,解析上传文件的内容
fileUpload拦截器默认在defaultStack栈中,默认会执行的
在Action中编写文件上传,需要定义三个属性
文件类型File,属性名与表单中file的name属性名一致
字符串类型String,属性名:前段是name属性名一致+ContentType
字符串类型String,属性名:前段是name属性名一致+FileName
最后需要为上述的三个属性通过set方法
可以通过FileUtils提供copyFile进行文件复制,将上传文件,保存到服务器端
5、文件上传中的问题
先配置input逻辑视图
在页面中显示错误信息
文件上传的总大小默认值是2M,如果超过了2M,程序会报出异常,可以使用<s:actionError>来查看具体信息
解决总大小的设置,找到常量
struts.multipart.parser = jakarta 默认文件上传解析器,就是FileUpload组件
struts.multipart.saveDir= 文件上传的临时文件存储目录
struts.multipart.maxSize=2097152 文件上传的最大值(总大小),默认是2M
可以在struts.xml中设置常量,修改文件上传的默认总大小
<constant name="struts.multipart.maxSize" value="20971520"></constant>
5、还可以通过配置拦截器来设置文件上传的一些属性
先在<action>标签中引入文件上传的拦截器
<interceptor-ref name="defaultStack">
<!-- 设置单个上传文件的大小 -->
<param name="fileUpload.maximumSize">2097152</param>
<!-- 决定上传文件的类型 -->
<param name="fileUpload.allowedExtensions">.jpg,.txt</param>
</interceptor-ref>
FastJsonUtil.java
package my.utils;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
public class FastJsonUtil {
/**
* 将对象转成json串
* @param object
* @return
*/
public static String toJSONString(Object object){
//DisableCircularReferenceDetect来禁止循环引用检测
return JSON.toJSONString(object,SerializerFeature.DisableCircularReferenceDetect);
}
//输出json
public static void write_json(HttpServletResponse response,String jsonString)
{
response.setContentType("application/json;utf-8");
response.setCharacterEncoding("UTF-8");
try {
response.getWriter().print(jsonString);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* ajax提交后回调的json字符串
* @return
*/
public static String ajaxResult(boolean success,String message)
{
Map map=new HashMap();
map.put("success", success);//是否成功
map.put("message", message);//文本消息
String json= JSON.toJSONString(map);
return json;
}
/**
* JSON串自动加前缀
* @param json 原json字符串
* @param prefix 前缀
* @return 加前缀后的字符串
*/
public static String JsonFormatterAddPrefix(String json,String prefix,Map<String,Object> newmap)
{
if(newmap == null){
newmap = new HashMap();
}
Map<String,Object> map = (Map) JSON.parse(json);
for(String key:map.keySet())
{
Object object=map.get(key);
if(isEntity(object)){
String jsonString = JSON.toJSONString(object);
JsonFormatterAddPrefix(jsonString,prefix+key+".",newmap);
}else{
newmap.put(prefix+key, object);
}
}
return JSON.toJSONString(newmap);
}
/**
* 判断某对象是不是实体
* @param object
* @return
*/
private static boolean isEntity(Object object)
{
if(object instanceof String )
{
return false;
}
if(object instanceof Integer )
{
return false;
}
if(object instanceof Long )
{
return false;
}
if(object instanceof java.math.BigDecimal )
{
return false;
}
if(object instanceof Date )
{
return false;
}
if(object instanceof java.util.Collection )
{
return false;
}
return true;
}
}
UploadUtils.java
/**
* 文件上传的工具类
* @author Administrator
*
*/
public class UploadUtils {
/**
* 传入文件的名称,返回的唯一的名称
* 例如:a,jpg 返回xdjfgdhjksda.jsp
* @param filename
* @return
*/
public static String getUUIDName(String filename){
//先查找
int index = filename.lastIndexOf(".");
//截取
String lastname = filename.substring(index, filename.length());
//唯一字符串
String uuid = UUID.randomUUID().toString().replace("-", "");
System.out.println(filename);
return uuid+lastname;
}
public static void main(String[] args) {
String filename = "a.jpg";
String uuid = getUUIDName(filename);
System.out.println(uuid);
}
}
dao
/**
* 分页的查询
*/
public PageBean<Customer> findByPage(Integer pageCode, Integer pageSize, DetachedCriteria criteria) {
PageBean<Customer> page = new PageBean<Customer>();
page.setPageCode(pageCode);
page.setPageSize(pageSize);
//先查询总记录数 select count(*)
criteria.setProjection(Projections.rowCount());
List<Number> list = (List<Number>) this.getHibernateTemplate().findByCriteria(criteria);
if(list!=null && list.size()>0){
int totalCount = list.get(0).intValue();
//总的记录数
page.setTotalCount(totalCount);
}
//强调:把select count(*)先清空 变成select * ...
criteria.setProjection(null);
//提供分页的查询 pageCode 当前页
List<Customer> beanList = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria, (pageCode-1)*pageSize, pageSize);
//分页查询数据,每页显示的数据 使用limit
page.setBeanList(beanList);
return page;
}
/**
* 通过主键,查询客户
*/
public Customer findById(Long cust_id) {
return this.getHibernateTemplate().get(Customer.class, cust_id);
}
/**
* 删除客户
*/
public void delete(Customer customer) {
this.getHibernateTemplate().delete(customer);
}
public class DictDaoImpl extends HibernateDaoSupport implements DictDao{
/**
* 根据客户类别编码查询字段
*/
public List<Dict> findByCode(String dict_type_code) {
return (List<Dict>) this.getHibernateTemplate().find("from Dict where dict_type_code = ?", dict_type_code);
}
}
public User login(User user) {
//QBC查询,按条件进行查询
DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
//拼接查询的条件
criteria.add(Restrictions.eq("user_code",user.getUser_code()));
criteria.add(Restrictions.eq("user_password",user.getUser_password()));
criteria.add(Restrictions.eq("user_state","1"));
//查询
List<User> list = (List<User>) this.getHibernateTemplate().findByCriteria(criteria);
if(list!=null && list.size()>0){
return list.get(0);
}
return null;
}
domain
//描述的是一客户的来源,多是客户
private Dict source;
//一客户的行业 多是客户
private Dict industry;
//一客户级别 多是客户
private Dict level;
//上传文件保存的路径
private String filepath;
service
//保存用户,密码需要加密
public void save(User user) {
String pwd = user.getUser_password();
//给密码加密
user.setUser_password(MD5Utils.md5(pwd));
//用户的状态默认是1状态
user.setUser_state("1");
//调用持久层
userDao.save(user);
}
/**
* 登录通过登录名和密码做校验
* 先给密码加密,再查询
* @return
*/
public User login(User user) {
String pwd = user.getUser_password();
//给密码加密
user.setUser_password(MD5Utils.md5(pwd));
//查询
return userDao.login(user);
}
DictAction
private Dict dict = new Dict();
public Dict getModel() {
return dict;
}
private DictService dictService;
public void setDictService(DictService dictService) {
this.dictService = dictService;
}
/**
* 通过字典的type_code值,查询客户来源或者客户级别
* @return
*/
public String findByCode(){
//调用业务层
// System.out.println("--------"+dict.getDict_type_code());
List<Dict> list = dictService.findByCode(dict.getDict_type_code());
// List<Dict> list = dictService.findByCode("006");
//使用fastjson把list转换成json字符串
String jsonString = FastJsonUtil.toJSONString(list);
//把json字符串写到浏览器
HttpServletResponse response = ServletActionContext.getResponse();
//输出
FastJsonUtil.write_json(response, jsonString);
return NONE;
}
}
CustomerAction
//需要手动new 和返回对象
private Customer customer = new Customer();
//model是CustomerAction类的属性
public Customer getModel() {
return customer;
}
//提供service的成员属性,提供set方法
private CustomerService customerService;
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
/**
* 保存客户的方法
* @return
*/
public String add(){
System.out.println("web层:保存");
/*//web工厂
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());
CustomerService service = (CustomerService) context.getBean("customerService");
// System.out.println(customer);*/
customerService.save(customer);
return NONE;
}
//属性驱动的方式
//当前页,默认值就1
private Integer pageCode= 1;
public void setPageCode(Integer pageCode) {
if(pageCode== null){
pageCode = 1;
}
this.pageCode = pageCode;
}
//每页显示的数据的条数
private Integer pageSize = 2;
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
/**
* 分页的查询方法
* @return
*/
public String findByPage(){
//调用service业务层
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
//拼接查询的条件
String cust_name = customer.getCust_name();
if(cust_name !=null && !cust_name.trim().isEmpty()){
//说明,客户的名称输入值了
criteria.add(Restrictions.like("cust_name", "%"+cust_name+"%"));
}
//拼接客户级别
Dict level = customer.getLevel();
if(level!=null && !level.getDict_id().trim().isEmpty()){
//说明,客户的级别肯定选择了一个
criteria.add(Restrictions.eq("level.dict_id", level.getDict_id()));
}
Dict source = customer.getSource();
if(source!=null && !source.getDict_id().trim().isEmpty()){
//说明,客户的级别肯定选择了一个
criteria.add(Restrictions.eq("source.dict_id", source.getDict_id()));
}
//查询
PageBean<Customer> page = customerService.findByPage(pageCode,pageSize,criteria);
//压栈
ValueStack vs = ActionContext.getContext().getValueStack();
//栈顶是map<"page",page对象>
vs.set("page", page);
return "page";
}
/**
* 初始化到添加的页面
* @return
*/
public String initAddUI(){
return "initAddUI";
}
/**
* 文件的上传,需要在CustomerAction类中定义成员的属性,命名是有规则的
* private File upload;//表示要上传的文件
* private String uoloadFileName;表示上传文件的名称(没有中文乱码)
* private String uploadContentType; 表示上传文件的MIME类型
* 提供set方法,拦截器就注入值了
*/
//要上传的文件
private File upload;
//文件的名称
private String uploadFileName;
//文件的MIME的类型
private String uploadContentType;
public void setUpload(File upload) {
this.upload = upload;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
/**
* 保存客户的方法
* @return
* @throws IOException
*/
public String save() throws IOException{
//文件的上传
if(uploadFileName!=null){
//打印
System.out.println("文件名称:"+uploadFileName);
System.out.println("文件类型"+uploadContentType);
//处理文件的名称
String uuidName = UploadUtils.getUUIDName(uploadFileName);
/*把文件上传到D:\apache-tomcat-8.5.30\webappsupload;*/
String path="D:\\apache-tomcat-8.5.30\\webapps\\upload\\";
//创建file对象
File file = new File(path+uuidName);
//简单方式
FileUtils.copyFile(upload, file);
//把上传的文件的路径,保存到客户表中
customer.setFilepath(path+uuidName);
}
//保存用户成功了
customerService.save(customer);
return "save";
}
/**
* 删除客户
* @return
*/
public String delete(){
//删除客户,获取客户的信息,上传文件的路径
customer = customerService.findById(customer.getCust_id());
//获取上传文件的连接
String filepath = customer.getFilepath();
//删除客户
customerService.delete(customer);
//删除文件
File file = new File(filepath);
if(file.exists()){
file.delete();
}
return "delete";
}
}
UserAction
private UserService userService;
public void setUserService(UserService userService) {
this.userService = userService;
}
/**
* 注册功能
*/
public String regist(){
//接受请求参数
userService.save(user);
return LOGIN;
}
/**
* 通过登录名,判断,登录名是否已经存在
*/
public String checkCode(){
//调用业务层,查询
User u = userService.checkCode(user.getUser_code());
//获取resposne对象
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=UTF-8");
try {
//获取输出流
PrintWriter writer = response.getWriter();
//进行判断
if(u!=null){
//说明,登录名查询到用户了,说明登录名已经存在了,不能注册
writer.print("no");
}else{
//说明,不存在登录名,可以注册
writer.print("yes");
}
} catch (IOException e) {
e.printStackTrace();
}
return NONE;
}
/**
* 登录功能
* @return
*/
public String login(){
User existUser = userService.login(user);
//判断,登录名或者喵喵错误了
if(existUser == null){
return LOGIN;
} else{
ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);
//登录成功
return "loginOK";
}
}
public String exit(){
ServletActionContext.getRequest().getSession().removeAttribute("existUser");
return LOGIN;
}
}
<SCRIPT language=javascript>
//提交分页的查询表单
function to_page(page){
if(page){
$("#page").val(page);
}
document.customerForm.submit();
}
//页面的加载
$(function(){
//发送ajax的请求
var url = "${pageContext.request.contextPath}/dict_findByCode.action";
var param ={"dict_type_code":"006"};
//alert(param.dict_type_code);
$.post(url,param,function(data){
//遍历
$(data).each(function(i,n){
//alert(i+":"+n);
//alert(i+":"+n.dict_item_name);
//alert(this.dict_item_name);
//先获取值栈中的值,使用EL表达式
var vsId = "${model.level.dict_id}";
//值栈中的id值和变量的id值相同,让其选中
if(vsId == n.dict_id){
//jq的dom操作
$("#levelId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
}else{
$("#levelId").append("<option value='"+n.dict_id+"' >"+n.dict_item_name+"</option>");
}
});
},"json");
//获取来源
var param={"dict_type_code":"002"};
$.post(url,param,function(data){
//遍历
$(data).each(function(i,n){
var vsId = "${model.source.dict_id}";
if(vsId == n.dict_id){
$("#sourceId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
}else{
$("#sourceId").append("<option value='"+n.dict_id+"' >"+n.dict_item_name+"</option>");
}
});
},"json");
});
</SCRIPT>
<c:forEach items="${page.beanList}" var="customer">
<TR
style="FONT-WEIGHT: normal; FONT-STYLE: normal; BACKGROUND-COLOR: white; TEXT-DECORATION: none">
<TD>${customer.cust_name }</TD>
<TD>${customer.level.dict_item_name }</TD>
<TD>${customer.source.dict_item_name }</TD>
<TD>${customer.cust_linkman }</TD>
<TD>${customer.cust_phone }</TD>
<TD>${customer.cust_mobile }</TD>
<TD>
<a href="${pageContext.request.contextPath }/customerServlet?method=edit&custId=${customer.cust_id}">修改</a>
<a href="${pageContext.request.contextPath }/customer_delete.action?cust_id=${customer.cust_id}" onclick="return window.confirm('确定删除')">删除</a>
</TD>
</TR>
</c:forEach>
<DIV
style="LINE-HEIGHT: 20px; HEIGHT: 20px; TEXT-ALIGN: right">
共[<B>${page.totalCount}</B>]条记录,共[<B>${page.totalPage}</B>]页
,每页显示
<select name="pageSize">
<option value="2" <c:if test="${page.pageSize==2 }">selected</c:if>>2</option>
<option value="3" <c:if test="${page.pageSize==3 }">selected</c:if>>3</option>
</select>
条
<c:if test="${page.pageCode>1 }">
[<A href="javascript:to_page(${page.pageCode-1})">前一页</A>]
</c:if>
<B>${page.pageCode}</B>
<c:if test="${page.pageCode<page.totalPage }">
[<A href="javascript:to_page(${page.pageCode+1})">后一页</A>]
</c:if>
到
<input type="text" size="3" id="page" name="pageCode" />
页
<input type="button" value="Go" onclick="to_page()"/>
</DIV>
<SCRIPT language=javascript>
//页面的加载
$(function(){
//发送ajax的请求
var url = "${pageContext.request.contextPath}/dict_findByCode.action";
var param ={"dict_type_code":"006"};
//alert(param.dict_type_code);
$.post(url,param,function(data){
//遍历
$(data).each(function(i,n){
//值栈中的id值和变量的id值相同,让其选中
//jq的dom操作
$("#levelId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
});
},"json");
//获取来源
var param={"dict_type_code":"002"};
$.post(url,param,function(data){
//遍历
$(data).each(function(i,n){
$("#sourceId").append("<option value='"+n.dict_id+"' selected>"+n.dict_item_name+"</option>");
});
},"json");
});
</SCRIPT>