天天看点

Struts2入门简单CRUD

文章目录

    • 环境搭建
        • 下载jar包
    • Web.xml配置中央控制器
    • 创建struts.xml
    • 创建通用struts.base.xml文件
    • 实现CRUD
    • 效果图

环境搭建

下载jar包

struts2 : 2.5.13 (没有maven之前,手动添加;现在用maven添加依赖即可)

链接: https://mvnrepository.com/artifact/org.apache.struts/struts2-core.

Struts2入门简单CRUD
Struts2入门简单CRUD

pom.xml配置文件

<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.liuchunming</groupId>
  <artifactId>struts</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>struts Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
	<dependency>
	    <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-core</artifactId>
	    <version>2.5.16</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
	<dependency>
	    <groupId>mysql</groupId>
	    <artifactId>mysql-connector-java</artifactId>
	    <version>5.1.49</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/jstl/jstl -->
	<dependency>
	    <groupId>jstl</groupId>
	    <artifactId>jstl</artifactId>
	    <version>1.2</version>
	</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-servlet-api</artifactId>
    <version>8.0.46</version>
</dependency>
	<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jsp-api -->
<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jsp-api</artifactId>
    <version>8.0.46</version>
</dependency>
	
  </dependencies>
  <build>
    <finalName>struts</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.7.0</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>
           

配置完成后记得Update Maven Project更新一下项目

Web.xml配置中央控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <display-name>struts</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <!-- 配置中央控制器 -->
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
</web-app>
           

创建struts.xml

因为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>
	<include file="struts-list.xml"></include>
</struts>
           

创建通用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>
	<!-- 开启开发者模式 -->
	<constant name="struts.devMode" value="true"></constant>
	<!-- 开启自动加载配置文件 -->
	<constant name="struts.configuration.xml.reload" value="true"></constant>
	<!-- 
		name:包名
		extends:继承
		abstract:是否抽象类
		namespace:命名空间
	 -->
	<package name="struts-base" extends="struts-default" abstract="true">
	<!-- 动态调用 -->
		<global-allowed-methods>regex:.*</global-allowed-methods>
	</package>
</struts>
           

实现CRUD

首先创建实体类与数据库列字段匹配

package com.liuchunming.entity;

public class Student {
	private int sid;
	private String sname;
	private int sage;
	private String sex;
	private String remark;
	private String image;
	public String getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public int getSage() {
		return sage;
	}
	public void setSage(int sage) {
		this.sage = sage;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	/**
	 * @param sid
	 * @param sname
	 * @param sage
	 * @param sex
	 * @param remark
	 * @param image
	 */
	public Student(int sid, String sname, int sage, String sex, String remark, String image) {
		super();
		this.sid = sid;
		this.sname = sname;
		this.sage = sage;
		this.sex = sex;
		this.remark = remark;
		this.image = image;
	}
	public Student() {
		super();
	}
	@Override
	public String toString() {
		return "Student [sid=" + sid + ", sname=" + sname + ", sage=" + sage + ", sex=" + sex + ", remark=" + remark
				+ ", image=" + image + "]";
	}
}

           

数据库字段

Struts2入门简单CRUD

创建StudentDao方法

package com.liuchunming.dao;

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

import com.liuchunming.entity.Student;
import com.liuchunming.util.BaseDao;
import com.liuchunming.util.PageBean;
import com.liuchunming.util.StringUtils;

public class StudentDao extends BaseDao<Student>{
	/**
	 * 查询方法
	 * @param student
	 * @param pageBean
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public List<Student> list(Student student,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
		String sql="select sid,sname,sage,sex,remark,image from tb_student where true";
		String sname = student.getSname();
		if(StringUtils.isNotBlank(sname)) {
			sql+=" and sname like '%"+sname+"%'";
		}
			sql+=" ORDER BY sid desc";
		return super.executeQuery(sql, Student.class, pageBean);
	}
	/**
	 * 增加
	 * @param student
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int add(Student student) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="insert into tb_student(sname,sage,sex,remark) values(?,?,?,?)";
		return super.executeUpdate(sql, student, new String [] {"sname","sage","sex","remark"});
	}
	/**
	 * 删除
	 * @param student
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int del(Student student) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="delete from tb_student where sid=?";
		return super.executeUpdate(sql, student, new String [] {"sid"});
	}
	/**
	 * 查询单个
	 * @param student
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	
	public List<Student> fin(Student student) throws InstantiationException, IllegalAccessException, SQLException {
		String sql="select sid,sname,sage,sex,remark,image from tb_student where  sid="+student.getSid();
		return  super.executeQuery(sql, Student.class, null);
	}
	
	/**
	 * 修改
	 * @param student
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public int edit(Student student) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		String sql="update tb_student set sname=?,sage=?,sex=?,remark=?  where sid=?";
		return super.executeUpdate(sql, student, new String [] {"sname","sage","sex","remark","sid"});
	}
	
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, SQLException {
		StudentDao sd=new StudentDao();
		Student s=new Student();
		s.setSid(2);
		List<Student> fin = sd.fin(s);
		for (Student sa : fin) {
			System.out.println(sa);
		}
	}
}
           

编写web层

package com.liuchunming.action;

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

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

import org.apache.struts2.ServletActionContext;

import com.liuchunming.dao.StudentDao;
import com.liuchunming.entity.Student;
import com.liuchunming.util.PageBean;
import com.opensymphony.xwork2.ModelDriven;

public class StudentAction implements ModelDriven<Student>{
	private HttpServletRequest req=ServletActionContext.getRequest();
	private HttpServletResponse resp=ServletActionContext.getResponse();
	private StudentDao studentDao=new StudentDao();
	private Student student=new Student();
	@Override
	public Student getModel() {
		// TODO Auto-generated method stub
		return student;
	}
	/***
	 * 查询
	 * @return
	 */
	public String list(){
		PageBean pageBean=new PageBean();
		List<Student> list;
		try {
			list = this.studentDao.list(student, pageBean);
			req.setAttribute("list", list);
			req.setAttribute("pageBean", pageBean);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return "success";
	}
	
	/**
	 * 增加
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public String add() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.studentDao.add(student);
		return list();
	}
	/**
	 * 删除
	 * @return
	 * @throws NoSuchFieldException
	 * @throws SecurityException
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public String del() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.studentDao.del(student);
		return list();
	}
	/**
	 * 查单个
	 * @return
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws SQLException
	 */
	public String fin() throws InstantiationException, IllegalAccessException, SQLException {
		List<Student> fin = this.studentDao.fin(student);
		req.setAttribute("fin", fin);
		return "toedit";
	}
	public String edit() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, SQLException {
		this.studentDao.edit(student);
		return list();
	}
}
           

编写struts.list.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 name="struts-list"  extends="struts-base" >
		<action name="studentAction_*" method="{1}" class="com.liuchunming.action.StudentAction">
		<!-- 
			name:跳转路径
			type:默认是转发=dispatcher 重定向=redirect
		 -->
			<result name="success" type="dispatcher">/list.jsp</result>
			 <result name="toedit" type="dispatcher">/edit.jsp</result> 
		</action>
	</package>
</struts>
           

添加页面: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="l" uri="/liuchunming" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	  <form action="${pageContext.request.contextPath}/studentAction_list.action" method="post">
		名称:<input type="text" name="sname"/>
		<input type="submit" value="搜索"/>
		<a href="add.jsp" target="_blank" rel="external nofollow" >增加</a>
	</form>  
	
	<table  style="width: 100%;">
	
		<tr>
			<td>学生编号</td>
			<td>学生姓名</td>
			<td>学生年龄</td>
			<td>学生性别</td>
			<td>备注</td>
			<td>头像</td>
			<td>操作</td>
		</tr>
		<c:forEach items="${list}" var="i">
		<tr>
			<td>${i.sid }</td>
			<td>${i.sname }</td>
			<td>${i.sage }</td>
			<td>${i.sex }</td>
			<td>${i.remark }</td>
			<td>${i.image }</td>
			<td>
				 <a onclick="return confirm('您确定要删除吗?')" href="${pageContext.request.contextPath}/studentAction_del.action?sid=${i.sid}" target="_blank" rel="external nofollow" >删除</a>
				 <a href="${pageContext.request.contextPath}/studentAction_fin.action?sid=${i.sid}" target="_blank" rel="external nofollow" >修改</a>  
			</td>
		</tr>
		</c:forEach>
	</table>
	<l:page pageBean="${pageBean }"></l:page>
</body>
</html>
           

效果图

Struts2入门简单CRUD