Struts2框架案例

实现查询客户列表、新增客户信息、客户权限控制(登录权限)

效果 :

实现代码 :

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <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>

拦截器

public class PrivilegeInterceptor extends MethodFilterInterceptor{
    @Override
    protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
        User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");
        if(user==null){
            return "login";
        }
        return actionInvocation.invoke();
    }
}

Action

//登录action
@ParentPackage(value = "test")
@Namespace("/")
@Results({
        @Result(name = "index",type = "redirect",location = "/index.jsp"),
        @Result(name = "save",type = "redirectAction",location = "customer_list.action"),
        @Result(name = "login",location = "/login.jsp"),
        @Result(name = "list",location = "/jsp/customer/list.jsp"),
        @Result(name = "none",location = "/jsp/customer/add.jsp")
})
public class UserAction extends ActionSupport implements ModelDriven<User> {
    @Action(value = "user_login")
    public String login(){
        if("hanne".equals(user.getUsername())&&"hanne".equals(user.getPassword())){
            ServletActionContext.getRequest().getSession().setAttribute("user",user);
            return "index";
        }
        return "login";
    }
    private User user = new User();
    @Override
    public User getModel() {
        return user;
    }
}

//新增客户信息跳转登录action
@ParentPackage(value = "test")
@Namespace("/")
@Results({
        @Result(name = "index",type = "redirect",location = "/index.jsp"),
        @Result(name = "save",type = "redirectAction",location = "customer_list.action"),
        @Result(name = "login",location = "/login.jsp"),
        @Result(name = "list",location = "/jsp/customer/list.jsp"),
        @Result(name = "none",location = "/jsp/customer/add.jsp")
})
public class ActionSave1 extends ActionSave {
    @Action(value = "action_save1")
    public String redirect(){
        return NONE;
    }
}

//新增客户信息action
@ParentPackage(value = "test")
@Namespace("/")
@Results({
        @Result(name = "index",type = "redirect",location = "/index.jsp"),
        @Result(name = "save",type = "redirectAction",location = "customer_list.action"),
        @Result(name = "login",location = "/login.jsp"),
        @Result(name = "list",location = "/jsp/customer/list.jsp"),
        @Result(name = "none",location = "/jsp/customer/add.jsp")
})
public class ActionSave extends ActionSupport implements ModelDriven<Customer> {
    @Action(value = "action_save")
    public String save(){
        CustomerService service = new CustomerServiceImpl();
        service.save(customer);
        return "save";
    }
    private Customer customer = new Customer();
    @Override
    public Customer getModel() {
        return customer;
    }
}

//查询客户列表action
@ParentPackage(value = "test")
@Namespace("/")
@Results({
		@Result(name = "index",type = "redirect",location = "/index.jsp"),
		@Result(name = "save",type = "redirectAction",location = "customer_list.action"),
		@Result(name = "login",location = "/login.jsp"),
		@Result(name = "list",location = "/jsp/customer/list.jsp"),
		@Result(name = "none",location = "/jsp/customer/add.jsp")
})
public class CustomerAction extends ActionSupport {
	@Action(value = "customer_list")
	public String list(){
		CustomerService customerService = new CustomerServiceImpl();
		List<Customer> customerList = customerService.findAll();
		//存储到request域
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("customerList", customerList);
		return "list";
	}
}

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <constant name="struts.devMode" value="true"></constant>
    <package name="test" namespace="/" extends="struts-default">
        <!--声明拦截器-->
        <interceptors>
            <interceptor name="privilege" class="com.itheima.action.interceptor.PrivilegeInterceptor"></interceptor>
            <interceptor-stack name="my">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="privilege">
                    <param name="excludeMethods">login,regist</param>
                </interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <!--配置默认拦截器-->
        <default-interceptor-ref name="my"></default-interceptor-ref>
        <!--全局视图-->
        <!--<global-results>
            <result name="index" type="redirect">/index.jsp</result>
            <result name="login">/login.jsp</result>
        </global-results>-->
        <!--配置资源路径-->
        <!--<action name="action_save" method="save" class="com.itheima.action.ActionSave"></action>-->
        <!--<action name="customer_*" class="com.itheima.action.CustomerAction" method="{1}">
            <result name="list">/jsp/customer/list.jsp</result>
        </action>-->
        <!--<action name="user_*" class="com.itheima.action.UserAction" method="{1}"></action>-->
    </package>
</struts>

实体类(需要get、set方法)

//JPA需要的注解
@Entity
//配置实体类与数据库表的注解
@Table(name = "cst_customer")
public class Customer {
    //数据库表中特殊的字段:id
    @Id
    //如果表字段名与实体类属性名一致,可以不需要填写name属性
    @Column(name = "cust_id")
    //主键规则
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long cust_id;//客户编号(主键)
    //配置普通字段名与属性名
    @Column(name = "cust_name")
    private String cust_name;//客户名称(公司名称)
    //当属性名与数据库中的字段名称一致时 那么@Column可以省略
    private String cust_source;//客户信息来源
    private String cust_industry;//客户所属行业
    private String cust_level;//客户级别
    private String cust_phone;//固定电话
    private String cust_mobile;//移动电话
/*
    private Set<Linkman> linkmanSet = new HashSet<Linkman>();//多的一方集合
}

Customer.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- 配置实体与表的关系 
			name: 要映射的实体的全限定名
			table: 要映射的表的名称
	-->
	<class name="com.itheima.domain.Customer" table="cst_customer">
		<!-- 配置实体的属性和表的字段的关系 
				在hibenrate中id具备特殊地位  修改、删除等默认都是根据id执行的
				id标签
					name:实体中的id的属性名称
					column:表中的id的字段名称
					
				主语:不管是id还是普通属性  当实体的属性名称 与 表的字段名称 一致时 此时column可以省略
		-->
		<id name="cust_id">
			<!-- 主键生成策略 -->
			<generator class="native"></generator>
		</id>
		
		<!-- 配置普通属性
				name:实体中的属性名称
				column:表中的字段名称
		 -->
		<property name="cust_name"></property>
		<property name="cust_source"></property>
		<property name="cust_industry" column="cust_industry"></property>
		<property name="cust_level" column="cust_level"></property>
		<property name="cust_phone" column="cust_phone"></property>
		<property name="cust_mobile" column="cust_mobile"></property>
	</class>
</hibernate-mapping>

业务层代码

public interface CustomerService {
	List<Customer> findAll();
	void save(Customer customer);
}

public class CustomerServiceImpl implements CustomerService {
	@Override
	public List<Customer> findAll() {
		CustomerDao customerDao = new CustomerDaoImpl();
		return customerDao.findAll();
	}
	@Override
	public void save(Customer customer) {
		CustomerDao dao = new CustomerDaoImpl();
		dao.save(customer);
	}
}

持久层代码

public interface CustomerDao {
    List<Customer> findAll();
    void save(Customer customer);
}

public class CustomerDaoImpl implements CustomerDao {
	@Override
	public List<Customer> findAll() {
		Session session = HibernateUtils.openSession();
		Transaction transaction = session.beginTransaction();
		Query query = session.createQuery("from Customer");
		List<Customer> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}
	@Override
	public void save(Customer customer) {
		Session session = HibernateUtils.openSession();
		Transaction transaction = session.beginTransaction();
		session.save(customer);
		transaction.commit();
		HibernateUtils.close(session);
	}

}

工具类

public class HibernateUtils {
    private static Configuration configuration = null;
    private static SessionFactory sessionFactory = null;
    static {
        configuration = new Configuration().configure();
        sessionFactory = configuration.buildSessionFactory();
    }
    public static Session openSession(){
        return sessionFactory.openSession();
    }
    public static void close(Session session){
        if(session!=null){
            session.close();
        }
    }
}

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

	<!-- 
		session工厂:造session对象
		session对象:会话对象 hibernate与数据库的连接对象
		
		session工厂内部需要配置三部分内容
			1、数据源信息
			2、hibernate其他配置参数
			3、加载映射关系	
	 -->
	<session-factory>
		<!-- 1、数据源信息 -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql:///hibernate</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		
		<!-- 2、hibernate的其他配置参数 -->
		<!-- 2.1  配置数据库方言 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 2.2 控制台是否打印sql语句 -->
		<property name="hibernate.show_sql">true</property>
		<!-- 2.3 格式化sql语句 -->
		<property name="hibernate.format_sql">true</property>
		<!-- 2.4 ddl策略 
				PS:
					ddl:数据定义语言:定义数据表和数据库
					dml:数据操作语言:对数据的增删改操作
					dql:数据查询语言:对数据的查询操作
					dcl:数据控制语言:对数据库的权限 用户等操作
				取值:
					create-drop: 创建删除  用于测试
					create:创建   用于测试
					validate: 检测  必须存在表且映射关系与表的结构一致    可以用于生产环境
					update: 更新  档映射关系与数据表结构只要不一致 自动更新表结构       可以用于生产环境(使用最多)
		-->
		<property name="hibernate.hbm2ddl.auto">update</property>
		<!-- 2.5 指定第三方的数据源 c3p0 
				导入hibernate-release-5.0.7.Final\lib\optional\c3p0\*.jar
		-->
		<!--<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>-->
		<!-- 2.6 配置session与当前线程绑定:了解
				注意:后期集成spring之后 与线程绑定这件事情不需要我们操作  spring自动操作
		 -->
		<property name="hibernate.current_session_context_class">thread</property>
		<!-- 3、加载映射 -->
		<mapping resource="com/itheima/domain/Customer.hbm.xml"/>
	</session-factory>
</hibernate-configuration>

项目代码war包:链接:https://download.csdn.net/download/aiyowei1106/10596460

猜你喜欢

转载自blog.csdn.net/aiyowei1106/article/details/81408434