在后台action中初始化数据,把数据返回到前台,并显示。进而对数据进行删,改。

5 篇文章 1 订阅

效果图:

 

项目结构:

概述项目:

1、创建一个动物类,类中有属性,编号(int),名字(String),年龄(int),颜色(boolean),重量(Float),出生日期(Date)
   在后台action中初始化至少三条记录,也就是封装三个对象,然后存放到集合中,把数据返回到前台,并显示。
(使用request把数据返回页面,使用jstl标签库显示数据)

2、使用jquery动态的在页面选中一条数据,可进行删除。实现的效果为当前页面记录删除,后台获取前台删除的这条记录的id.

3、选中一条记录,进行修改, 跳转到另一个页面, 把除了id字段设置成不可修改,其它字段都显示出来,并可修改。在后台获取修改后的数据。

代码:

动物列表页面Animal_list.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
    body{
    	margin-left: 200pt;
    }
    table,table tr th, table tr td 
    	{
    		border: 1px solid grey
   		 }
    </style>

</head>
<body>
 

 <c:if test="${list!=null}">
		<table cellpadding="0" cellspacing="0">
			<tr>
				<th>序号</th>
				<th>名字</th>
				<th>年龄</th>
				<th>颜色</th>
				<th>重量</th>
				<th>出生日期</th>
				<th>操作</th>
			</tr>
			<c:forEach items="${list}" var="u">
				<tr  id="del">
					<td>${u.id}</td>
					<td>${u.name}</td>
					<td>${u.age}</td>
					
					<c:if test="${u.color==true }">
					<td>白色</td>
					</c:if>
					<c:if test="${u.color==false }">
					<td>红色</td>
					</c:if>
										
					<td>${u.weight}</td>
					<td>
					<fmt:formatDate value="${u.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate>
					</td>
					<td>
					<input type="button" value="删除"  onclick="del(${u.id})"/>
					<a href="Animal_select?id=${u.id }"><input type="button" value="修改" /></a>
					</td>
				</tr>
			</c:forEach>
		</table>
	</c:if>
	<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
	<script type="text/javascript">
		
			function del(id){
				if(confirm("确定要删除吗?")){
				$.ajax({
				    type: "post",
				    dataType: "json",
				    url:'Animal_delete?id='+id,
					success:function(data){
					    if(data==1){
					    	$("#del").remove();
					    }
					}
				});
				}else{
					 return false;
				}
		}
	</script>
</body>
</html>

修改动物列表页面Animal_update.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>更新数据</title>
</head>
<body>
	<h3>更新数据</h3>
	<form action="Animal_update" method="post">
		编号:<input type="text" name="id" value="${str.id}" readonly="readonly"/><br/>
		名字:<input type="text" name="name" value="${str.name}"/><br/>
		年龄:<input type="text" name="age" value="${str.age}"/><br/>
		颜色:<input type="text" name="color" value="${str.color}"/><br/>
		重量:<input type="text" name="weight" value="${str.weight}"/><br/>
		出生日期:<input type="text" name="birthday" value="${str.birthday}"/><br/>
		<input type="submit" value="更新"/>
	</form>
	${updateSuccess}
	
	${updateError}
</body>
</html>


创建实体类Animal.java:

package cn.xxs.entity;

import java.io.Serializable;
import java.util.Date;
/**
 * Animal 类
 * @author xxs
 *
 */
public class Animal implements Serializable{
	
	private static final long serialVersionUID = 1L;
	
	private int id;
	private String name;
	private int age;
	private boolean color;
	private float weight;
	private Date birthday;
	public Animal() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Animal(int id, String name, int age, boolean color, float weight, Date birthday) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.color = color;
		this.weight = weight;
		this.birthday = birthday;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isColor() {
		return color;
	}
	public void setColor(boolean color) {
		this.color = color;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return "Animal [id=" + id + ", name=" + name + ", age=" + age + ", color=" + color + ", weight=" + weight
				+ ", birthday=" + birthday + "]";
	}
	
	
	
}

BaseAction.java:

package cn.xxs.action;

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

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport{
	/**
	 * 获取request
	 * @return
	 */
public HttpServletRequest getRequest() {
		
		return ServletActionContext.getRequest();
	}
	/**
	 * 获取Response
	 * @return
	 */
	public HttpServletResponse getResponse() {
		
		return ServletActionContext.getResponse();
	}
	
	/**
	 * 获取HttpSession
	 */
	public HttpSession getSession() {
		
		return getRequest().getSession();
		
	}
}

AnimalAction.java:

package cn.xxs.action;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.glass.ui.SystemClipboard;

import cn.xxs.entity.Animal;

/**
 * 
 * @author xxs
 *
 */
public class AnimalAction extends BaseAction{
	
	private int id;
	private String name;
	private int age;
	private boolean color;
	private float weight;
	private Date birthday;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isColor() {
		return color;
	}
	public void setColor(boolean color) {
		this.color = color;
	}
	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String list() throws ParseException{
		//转换日期类型
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		//初始化至少三条记录,也就是封装三个对象			
		Animal	animal1 = new Animal(1,"cat",3,false,5,df.parse("2017-12-30"));
		Animal animal2 = new Animal(2,"dog",2,false,5,df.parse("2017-12-30"));	
		Animal	animal3 = new Animal(3,"tiger",2,true,5,df.parse("2017-10-30"));
		//定义一个集合
		List<Animal> list= new ArrayList<Animal>();
		//把三个Animal对象存放到集合中
		list.add(animal1);
		list.add(animal2);
		list.add(animal3);		
		//把数据返回到前台
		getSession().setAttribute("list", list);
	    System.out.println(list.toString());
		return "list";
	}
	private Integer result;
	
	public Integer getResult() {
		return result;
	}

	public void setResult(Integer result) {
		this.result = result;
	}

	/**
	 * 
	 * @return
	 */
	public String delete() {
		System.out.println(id);
		if(id!=0) {
			result=1;
		}					
		return "delete";
		
	}
	public String select() {
		Animal a = new Animal();
		a.setId(id);
		a.setName(name);
		a.setAge(age);
		a.setColor(color);
		a.setWeight(weight);
		a.setBirthday(birthday);

		getRequest().setAttribute("str", a);
		
		return "select";
		
	}
	public String update() throws ParseException {
		//获取数据
		String id1 = getRequest().getParameter("id");
		String name = getRequest().getParameter("name");	
		String age1 = getRequest().getParameter("age");
		String color1 = getRequest().getParameter("color");
		String weight1 = getRequest().getParameter("weight");
		String birthday1 = getRequest().getParameter("birthday");
		//判断
		if(!id1.equals("") && !id1.isEmpty() && !name.equals("") && !name.isEmpty() 
				&& !age1.equals("") && !age1.isEmpty() && !color1.equals("") && !color1.isEmpty() 
				&& !weight1.equals("") && !weight1.isEmpty() && !birthday1.equals("") && !birthday1.isEmpty()) {
			//转换数据类型
			Integer id = Integer.valueOf(id1);				
			Integer age= Integer.valueOf(age1);
			Boolean color= Boolean.parseBoolean(color1);		
			Float weight= Float.valueOf(weight1);
			//转换日期类型
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Date birthday = df.parse(birthday1);
			//对象实例化
			Animal a = new Animal();
			//修改数据
			a.setId(id);
			a.setName(name);
			a.setAge(age);
			a.setColor(color);
			a.setWeight(weight);
			a.setBirthday(birthday);
			//前台测试
			System.out.println(a.toString());
			//更新成功信息
			getRequest().setAttribute("updateSuccess", "更新成功"+a.toString());					
		
		}else {
			getRequest().setAttribute("updateError", "信息不能为空,更新失败");
		}
		
		return "update";
		
	}
	
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>Animal_list.jsp</welcome-file>
</welcome-file-list>
 
<filter>
<filter-name>struts2</filter-name>
<filter-class>
         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
 
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

struts.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <package name="default" extends="struts-default,json-default">
     
    <!--  <action name="Animal_*" 
            class="cn.xxs.action.AnimalAction" 
            method="{1}">
            <result name="{1}">
            	/Animal_{1}.jsp        	           	
            </result>           
      </action>-->
      <action name="Animal_list" 
            class="cn.xxs.action.AnimalAction" 
            method="list">
            <result name="list">
            	/Animal_list.jsp        	           	
            </result>           
      </action>
      
      <action name="Animal_select" 
      			class="cn.xxs.action.AnimalAction" 
				method="select">
				<result name="select">/Animal_update.jsp</result>
			</action>
      <action name="Animal_update" 
            class="cn.xxs.action.AnimalAction" 
            method="update">
            <result name="update">
            	/Animal_update.jsp       	           	
            </result>           
      </action>
      
	 <action name="Animal_delete" 
            class="cn.xxs.action.AnimalAction" 
            method="delete">
            <result name="delete" type="json">
            	<param name="root">result</param>
            	     	           	
            </result>           
      </action>
     

   </package>
</struts>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值