structs实验

Posted GitHub_流星剑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了structs实验相关的知识,希望对你有一定的参考价值。

实验一 熟悉Struts2框架

实验任务:

1)实现基于Struts2的登录系统(需要访问数据库)

参考代码:

登录页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

    <form method="post" action="login">

            用户名:<input name="userName" type="text" size="24">

            <br>

            密 码:<input name="passWord" type="password" size="26">

            <br>

            <input type="submit" value="登录">

       </form>

</body>

</html>

登录成功页面success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<hr>

 <h1>你登录成功,欢迎你!</h1>

</hr>

</body>

</html>

LoginAction类代码如下:

package loginAction;

import loginBean.LoginBean;

public class LoginAction

    private String userName;

    private String passWord;

    public String getUserName()

        return userName;

   

    public void setUserName(String userName)

        this.userName = userName;

   

    public String getPassWord()

        return passWord;

   

    public void setPassWord(String passWord)

        this.passWord = passWord;

   

    public String execute() throws Exception

        LoginBean lb=new LoginBean();

        if(lb.login(userName, passWord))

               

            return "success";

               

                else

            return "error";

               

   

实现数据库登录功能的LoginBean类代码如下:

package loginBean;

import java.sql.*;

public class LoginBean

    private String userName;

    private String passWord;

    public String getUserName()

        return userName;

   

    public void setUserName(String userName)

        this.userName = userName;

   

    public String getPassWord()

        return passWord;

   

    public void setPassWord(String passWord)

        this.passWord = passWord;

   

    //处理用户登录的方法

    public boolean login(String userName,String passWord)

        boolean b=false;

        Connection con=null;

Statement st=null;

ResultSet rs=null;

try

       Class.forName("com.mysql.cj.jdbc.Driver");           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shiyan1?useSSL=false&serverTimezone=UTC","root","123456");

       st=con.createStatement();

       String sql="select * from user where username='"+userName+"'";

       rs=st.executeQuery(sql);

       if(rs.next())

               String pass=rs.getString("password");

               if(pass.equals(passWord))

                       b=true;

          

             

        return b;

catch(Exception e)  return b;      

配置文件struts.xml代码如下:

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

    <package name="login" extends="struts-default">

        <action name="login" class="loginAction.LoginAction">

            <result name="error">login.jsp</result>

            <result name="success">success.jsp</result>

        </action>

     </package>

</struts>

实验二 Struts2核心组件的应用

实验任务:

(1)修改实验一登录系统代码,页面使用Struts2标签,登录成功页面使用OGNL表达式显示登录用户名称,并显示是系统第几位登录成功的用户。

参考代码:

登录页面login1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>   

<%@taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

</head>

<body>

<s:form action="login1" method="post">

            <s:textfield name="userName" label="用户名称" size="16"/>

            <br>

            <s:password name="passWord" label="用户密码" size="18"/>

            <br>

            <s:submit value="登录"/>

</s:form>

</body>

</html>

登录成功页面success1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>   

<%@taglib prefix="s" uri="/struts-tags"%>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title><s:text name="登录成功页面"/></title>

</head>

<body>

<s:property value="#userName"/>,您好!欢迎访问本站,您是第<s:property value="#application.counter"/>位成功登录的客人!

</body>

</html>

LoginAction1类代码如下:

package loginAction1;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction1 extends ActionSupport

    private String userName;

    private String passWord;

    public String getUserName()

        return userName;

   

    public void setUserName(String userName)

        this.userName = userName;

   

    public String getPassWord()

        return passWord;

   

    public void setPassWord(String passWord)

        this.passWord = passWord;

   

    public String execute() throws Exception

        LoginBean lb=new LoginBean();

        if(lb.login(userName, passWord))

               

                ServletContext application= ServletActionContext.getServletContext();

                 Integer count= (Integer)application.getAttribute("counter");

                if(count==null)

                   count=new Integer(0);

                count=new Integer(count.intValue()+1);

                application.setAttribute("counter",count); 

                return SUCCESS;

           

            else

                         return ERROR;

           

   

实现数据库登录功能的LoginBean类代码如下:

package loginBean;

import java.sql.*;

public class LoginBean

    private String userName;

    private String passWord;

    public String getUserName()

        return userName;

   

    public void setUserName(String userName)

        this.userName = userName;

   

    public String getPassWord()

        return passWord;

   

    public void setPassWord(String passWord)

        this.passWord = passWord;

   

    //处理用户登录的方法

    public boolean login(String userName,String passWord)

        boolean b=false;

        Connection con=null;

Statement st=null;

ResultSet rs=null;

try

       Class.forName("com.mysql.cj.jdbc.Driver");           con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shiyan1?useSSL=false&serverTimezone=UTC","root","123456");

       st=con.createStatement();

       String sql="select * from user where username='"+userName+"'";

       rs=st.executeQuery(sql);

       if(rs.next())

               String pass=rs.getString("password");

               if(pass.equals(passWord))

                       b=true;

          

             

        return b;

catch(Exception e)  return b;      

 

配置文件struts.xml代码如下:

<!DOCTYPE struts PUBLIC

"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"

"http://struts.apache.org/dtds/struts-2.5.dtd">

<struts>

    <package name="login" extends="struts-default">

        <action name="login1" class="loginAction1.LoginAction1">

            <result name="error">login1.jsp</result>

            <result name="success">success1.jsp</result>

        </action>

     </package>

</struts>

实验三 Struts2高级组件的应用

实验任务:

(1)使用自定义拦截器实现网站页面登录权限控制,登录页面实现国际化

自定义拦截器LoginInterceptor.java的代码:

package interceptor;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

public class LoginInterceptor extends AbstractInterceptor

        public String intercept(ActionInvocation ai) throws Exception

        //获取session,判断session中是否有用户

        HttpSession session=ServletActionContext.getRequest().getSession();

        //没用户返回到input页面

        Object obj=session.getAttribute("user");

        if(obj==null)

            return "input";

                

        String result=ai.invoke();

        return result;

   

DemoAction类的代码:

package action;

import com.opensymphony.xwork2.ActionSupport;

import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpSession;

public class DemoAction extends ActionSupport

    //登陆方法,向session中设置

    public String login()

        HttpSession session=ServletActionContext.getRequest().getSession();

        session.setAttribute("user", "user");

        return SUCCESS;

       

    public String execute() throws Exception

        return SUCCESS;

 

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>

<constant name="struts.custom.i18n.resources" value="globalMessages" />

        <constant name="struts.i18n.encoding" value="utf-8" />

   <package name="login" extends="struts-default">

                    <!--定义拦截器-->

                    <interceptors>

                        <interceptor name="logininterceptor" class="interceptor.LoginInterceptor"></interceptor>

                    </interceptors>

                    <action name="login" class="action.DemoAction" method="login">

                        <!--登陆成功,直接跳转到main页面-->

                        <result type="redirectAction">main</result>

                    </action>

                    <!--执行main动作时,需要拦截器拦截-->

                    <action name="main" class="action.DemoAction">

                        <result>/main.jsp</result>

                        <result name="input">/login.jsp</result>

                        <!--使用默认拦截器和我们的拦截器-->

                        <interceptor-ref name="defaultStack"></interceptor-ref>

                        <interceptor-ref name="logininterceptor"></interceptor-ref>

                    </action>

    </package>   

</struts>

登录页面login.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

<html>

    <head>

        <!-- 使用text标签输出国际化消息 -->

        <title><s:text name="loginTitle"/></title>

    </head>

    <body>

        <s:form action="login" method="post">

            <!--表单元素的key值与资源文件的key对应-->

            <s:textfield name="userName" size="20" key="loginName"/>

            <s:password name="userPassWord" size="20" key="loginPassword"/>

            <s:submit key="loginSubmit"/>           

            </s:form>

    </body>

</html>

主页面main.jsp:

<%@ page contentType="text/html; charset=UTF-8" %>

<html>

    <head>

       <title>系统主页面</title>

    </head>

<body>

<h1>

         欢迎来到本网站主页面!

</h1>

    </body>

</html>

globalMessages_zh_CN.properties代码如下:

loginTitle=\\u7528\\u6237\\u767b\\u5f55

loginName=\\u7528\\u6237\\u540d\\u79f0

loginPassword=\\u7528\\u6237\\u5bc6\\u7801

loginSubmit=\\u767b\\u5f55

globalMessages_en_US.properties代码如下:

loginTitle=UserLogin

loginName=LoginName

loginPassword=LoginPassword

loginSubmit=Login

实验四 基于Struts2+Hibernate5的系统实现

实验任务:

基于Struts2+Hibernate5框架实现一个教师信息管理系统。

参考代码:

配置文件hibernate.cfg.xml代码如下:

<!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<!--Hibernate配置文件的根元素,其它元素应在其中-->

<hibernate-configuration>

        <!-- 设置初始化Hibernate参数的元素,其中指定Hibernate初始化参数,表明以下的配置是针对session-factory配置,SessionFactoryHibernate中的一个接口,这个接口主要负责保存Hibernate的配置信息,以及对Session的操作 -->

    <session-factory>

        <!-- 设置连接数据库所用的驱动 ,本例中的com.mysql.jdbc.Driver MySQL的驱动名字-->

        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>

        <!--设置数据库连接使用的url“jdbc:mysql://localhost(IP):port/test”,其中,localhost(IP)表示MySQL服务器名称,即连接地址,此处为本机。port代表MySQL服务器的端口号,默认是3306test是数据库名,即要连接的数据库名-->

        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/teacher?useSSL=false&amp;serverTimezone=UTC&amp;allowPublicKeyRetrieval=true&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>

        <!-- 设置数据库的用户名(登录名) -->

        <property name="hibernate.connection.username">root</property>

        <!-- 设置数据库的连接密码 -->

        <property name="hibernate.connection.password">123456</property>

        <!-- 设置数据库的方言,每种数据库都有对应的方言 -->

        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

               

        <!-- 加入映射文件,可以加入多个映射文件 -->

        <mapping resource="PO/Teachinfo.hbm.xml"/>   

    </session-factory>

</hibernate-configuration>

类HibernateSessionFactory的代码如下:

package addHibernateFile;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory

    private static SessionFactory sessionFactory;

    public static Session getSession()

        return getSessionFactory().openSession();

   

    public static SessionFactory getSessionFactory()

        if (sessionFactory == null || sessionFactory.isClosed())

            sessionFactory = new Configuration().configure().buildSessionFactory();

       

        return sessionFactory;

   

持久化类Teachinfo的代码如下:

package PO;

public class Teachinfo

        private String id;

        private String name;

        private String sex;

        private int age;

        private String department;

        public String getId()

                return this.id;

       

        public void setId(String id)

                this.id = id;

       

        public String getName()

                 return name;

       

        public void setName(String name)

                 this.name = name;

       

        public String getSex()

                 return sex;

       

        public void setSex(String sex)

                 this.sex = sex;

       

        public int getAge()

                 return age;

       

        public void setAge(int age)

                 this.age = age;

       

        public String getDepartment()

                 return department;

       

        public void setDepartment(String department)

                 this.department = department;

              

映射文件Teachinfo.hbm.xml的代码如下:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="PO.Teachinfo" table="teachinfo" catalog="teacher">

        <id name="id" type="string">

            <column name="id" length="20" />

            <generator class="assigned" />

        </id>

        <property name="name" type="string">

            <column name="name" length="20" not-null="true" />

        </property>

        <property name="sex" type="string">

            <column name="sex" length="5" />

        </property>

        <property name="age" type="int">

            <column name="age"  />

        </property>

        <property name="department" type="string">

            <column name="department" />

        </property>

    </class>

</hibernate-mapping>

TeacherDao类的代码如下:

package Dao;

import addHibernateFile.HibernateSessionFactory;

import PO.Teachinfo;

import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

public class TeacherDao

    private Transaction transaction;

    private Session session;

    private Query query;

    public TeacherDao()

   

    public boolean  saveInfo(Teachinfo info)

        try

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            session.save(info);

            transaction.commit();

            session.close();

            return true;

        catch(Exception e)

            message("saveInfo.error:"+e);

            e.printStackTrace();

            return false;

       

   

    public List findInfo(String type,Object value)

        session=HibernateSessionFactory.getSession();

        try

            transaction=session.beginTransaction();

            String queryString="from Teachinfo as model where model."+type+"=?";

            query=session.createQuery(queryString);

            query.setParameter(0, value);

            List list=query.list();

            transaction.commit();

            session.close();

            return list;

        catch(Exception e)

            message("findInfo.error:"+e);

            e.printStackTrace();

            return null;

       

   

    public List findAllInfo()

        session=HibernateSessionFactory.getSession();

        try

            transaction=session.beginTransaction();

            String queryString="from Teachinfo";

            query=session.createQuery(queryString);

            List list=query.list();

            transaction.commit();

            session.close();

            return list;

        catch(Exception e)

            message("findInfo.error:"+e);

            e.printStackTrace();

            return null;

       

   

    public boolean deleteInfo(String id)

        try

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            Teachinfo info=new Teachinfo();

            info=(Teachinfo)session.get(Teachinfo.class, id);

            session.delete(info);

            transaction.commit();

            session.close();

            return true;

        catch(Exception e)

            message("deleteInfo.error:"+e);

            e.printStackTrace();

            return false;

       

   

    public boolean updateInfo(Teachinfo info)

        try

            session=HibernateSessionFactory.getSession();

            transaction=session.beginTransaction();

            session.update(info);

            transaction.commit();

            session.close();

            return true;

        catch(Exception e)

            message("updateInfo.error:"+e);

            e.printStackTrace();

            return false;

       

   

    public void message(String mess)

        int type=JOptionPane.YES_NO_OPTION;

        String title="提示信息";

        JOptionPane.showMessageDialog(null, mess, title, type);

   

主页面index.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@taglib  prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title><

实验了一下对于struct引用的成员的改动

今天写代码的时候,不确定struct用引用传递给函数的时候,他的成员在函数里面改变的时候,是否能影响到外面。

 

实验了一下

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

typedef struct _ABC {
    int id;
    _ABC() :
    id(0)
    {
    }
} ABC;

void func(ABC & abc) {
    abc.id = 3;
} 

int main() {

    ABC abc;
    func(abc);

    printf("abc id: %d\n", abc.id);
    return 0;
}

 

发现是可以改变的:

abc id: 3

 

以上是关于structs实验的主要内容,如果未能解决你的问题,请参考以下文章

Struct2笔记

struct2_拦截器知识点.

Struts2基础01

struct 2 基本知识

Java web struct入门基础知识

struts2--笔记