欢迎光临散文网 会员登陆 & 注册

action运行,拼接下拉框,商品展示,STRUTS2,密码,MD5,代码改后未起效【诗书画唱】

2021-01-10 00:26 作者:诗书画唱  | 我要投稿

CTRL+F:STRUTS2登录注册加载下拉框中的数据的讲义,视频笔记 ,MD5介绍,登录注册的例子视频笔记 ,struts2框架,action中跳转界面且用EL表达式获取传过来的变量的方法。加载下拉框例子。关于eclipse的卡顿问题,代码改后未起效问题(eclipse,Java Web项目有时就是有这种bug和缺陷)。项目删除干净的方法。关于空指针异常等JDBC链接数据库报错问题。如何判断你真正掌握应该掌握的内容了。登录注册的SQL代码。action运行成功的必要条件。作业和自己给出的答案。商品展示和商品详情的例子。




提示:密码是不能明文地存放在数据库中的,而应该通过MD5加密然后保存在数据库中。

struts2框架中使用ajax技术。个人为视频笔记很重要,值得记录和搜索查看。

一般先记录例子,后做视频笔记(或者反着来,总之这2项记录一般基本都要做),可以视频笔记和例子结合起来,一起记录。

可以先看教程视频,之后截图步骤和各个例子要的文件和要注意的事等。例子分开记,方便以后更灵活,自由地组合。

如何判断你真正掌握应该掌握的内容了 START

自己改写代码的变量名等后仍然可以运行正确。就是说你可以根据原来内容创作并记录下修改后仍然可以用,有效,不会报错,至少有原来的内容的运行效果。


如何判断你真正掌握应该掌握的内容了 END


项目删除干净的方法 START

项目删除干净的方法 END

关于空指针异常等JDBC链接数据库报错问题 START


关于空指针异常等JDBC链接数据库报错问题 END



STRUTS2登录注册加载下拉框中的数据的讲义 START


理应实现:

登录注册功能。

加载下拉框。


密码是不能明文地存放在数据库中的,而应该通过MD5加密然后保存在数据库中。

struts2框架中使用ajax技术




STRUTS2登录注册加载下拉框中的数据的讲义 END

视频笔记 START


MD5介绍 START

MD5是baimessage-digest algorithm 5(信息-摘要算法)的缩写,被广泛用于加密和解密技术上,它可以说是文件的“数字指纹”。任何一个文件,无论是可执行程序、图像文件、临时文件或者其他任何类型的文件,也不管它体积多大,都有且只有一个独一无二的MD5信息值,并且如果这个文件被修改过,它的MD5值也将随之改变。因此,我们可以通过对比同一文件的MD5值,来校验这个文件是否被“篡改”过。






MD5介绍 END


登录注册的例子视频笔记 START


一般来说,防止其要写的属性太多,所以这里一般就是set,get一个bean类。


登录注册的例子视频笔记  END



struts2框架,action中跳转界面且用EL表达式获取传过来的变量的方法 START

struts2框架,action中跳转界面且用EL表达式获取传过来的变量的方法 END



视频笔记 END




例子 START

加载下拉框例子 START

package com.jy.action;


import java.util.List;


import com.jy.bean.Addr;

import com.jy.dao.AddrDao;


public class AddrAction {

private String html;

private AddrDao addrDao = new AddrDao();

public String getHtml() {

return html;

}

public void setHtml(String html) {

this.html = html;

}

//http://localhost:8080/J190802/pub/addrAc.action

    public String toAddr(){

    List<Addr>list = addrDao.selectByPid(0);

    StringBuilder sb = new StringBuilder();

    for(Addr a : list) {

    sb.append("<option value=" + a.getId() 

    + ">" + a.getName() + "</option>");

    }

    html = sb.toString();

    return "success";

    }

}

package com.jy.bean;


public class Addr {

    private Integer id;

    private Integer pid;

    private String name;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public Integer getPid() {

return pid;

}

public void setPid(Integer pid) {

this.pid = pid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

package com.jy.dao;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


import com.jy.bean.Addr;

import com.jy.utils.DbUtil;


public class AddrDao {

    public List<Addr>selectByPid(Integer pid){

    String sql = "select * from addr where pid = ?";

   

    Connection conn = null;

    PreparedStatement pstm = null;

    ResultSet rs = null;

    List<Addr>list = new ArrayList<Addr>();

    try {

        conn = DbUtil.getConn();

pstm = conn.prepareStatement(sql);

    pstm.setInt(1, pid);

    rs = pstm.executeQuery();

    while(rs.next()) {

    Addr a = new Addr();

    a.setId(rs.getInt("id"));

    a.setPid(rs.getInt("pid"));

    a.setName(rs.getString("name"));

    list.add(a);

    }

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DbUtil.close(rs, pstm, conn);

}

    return list;

    }

}


package com.jy.utils;


import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Properties;


public class DbUtil {

private static String driverName;

    private static String url;

    private static String user;

    private static String pwd;

    

    static {

    //读取properties文件

    Properties prop = new Properties();

    //将db.properties文件读取到内存中去

    InputStream is = DbUtil.class.getClassLoader()

    .getResourceAsStream("db.properties");

    //加载内容

    try {

prop.load(is);

//读取内容

driverName = prop.getProperty("drivername");

url = prop.getProperty("url");

user = prop.getProperty("username");

pwd = prop.getProperty("password");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

    

    //获取数据库连接对象的方法

    public static Connection getConn(){

    Connection conn = null;

    try {

Class.forName(driverName);

conn = DriverManager.getConnection(url,user,pwd);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   

    return conn;

    }

    

    public static void close(ResultSet rs,PreparedStatement pstm

    ,Connection conn){

        try {

        if(rs != null) {

            rs.close();

            }

            if(pstm != null) {

            pstm.close();

            }

            if(conn != null) {

            conn.close();

            }

        } catch(Exception e) {

        e.printStackTrace();

        }

    }

}

drivername=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&amp;characterEncoding=GBK2312

username=root

password=root




<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

     <package name="user" namespace="/pub" extends="struts-default">

         <action name="loginAc" class="com.jy.action.PubAction"

             method="doLogin">

             <result>/manage.jsp</result>

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

         </action>

         

         <action name="regAc" class="com.jy.action.PubAction"

             method="doReg">

             <result>/login.jsp</result>

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

         </action>

         

         <action name="addrAc" class="com.jy.action.AddrAction"

             method="toAddr">

             <result>/addr.jsp</result>

         </action>

     </package>

</struts>














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

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

    </head>

    <body>

        <label>省份:</label>

        <select id="prov">${html }</select>

    </body>

</html>







加载下拉框例子 END



关于eclipse的卡顿问题,代码改后未起效问题 START

关于eclipse的卡顿问题,代码改后未起效问题 END

登录注册 START



package com.jy.action;


import org.apache.struts2.ServletActionContext;


import com.jy.bean.Userinfo;

import com.jy.dao.UserinfoDao;


public class PubAction {

private Userinfo u;

private UserinfoDao userinfoDao = new UserinfoDao();

private String msg;

    public Userinfo getU() {

return u;

}

public void setU(Userinfo u) {

this.u = u;

}

public UserinfoDao getUserinfoDao() {

return userinfoDao;

}

public void setUserinfoDao(UserinfoDao userinfoDao) {

this.userinfoDao = userinfoDao;

}

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

public String doLogin(){

    u = userinfoDao.selectByActAndPwd(u);

    if(u.getId() != null) {

    //将用户的账号放到session中去

    ServletActionContext.getRequest()

        .getSession().setAttribute("_user", u);

    return "success";

    } else {

    msg = "账号或者密码错误";

    return "fail";

    }   

    }

 

public String doReg(){

Integer count = userinfoDao.add(u);

if(count > 0) {

    return "success";

} else {

return "fail";

}

}

}



package com.jy.bean;


public class Userinfo {

    private Integer id;

    private String act;

    private String pwd;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getAct() {

return act;

}

public void setAct(String act) {

this.act = act;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

}











package com.jy.dao;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;


import com.jy.bean.Userinfo;

import com.jy.utils.DbUtil;


public class UserinfoDao {

    public Userinfo selectByActAndPwd(Userinfo u){

    String sql = "select * from userinfo where act = ? and pwd = ?";

   

    Connection conn = null;

    PreparedStatement pstm = null;

    ResultSet rs = null;

   

    try {

        conn = DbUtil.getConn();

pstm = conn.prepareStatement(sql);

pstm.setString(1, u.getAct());

            pstm.setString(2, u.getPwd());

            rs = pstm.executeQuery();

            if(rs.next()) {

            Integer id = rs.getInt("id");

            u.setId(id);

            }

    } catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DbUtil.close(rs, pstm, conn);

}

    return u;

    }

    

    public Integer add(Userinfo u){

    return 0;

    }

}





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

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            *{

                font-size: 50px;

            }

        </style>

    </head>

    <body>

        <form action="pub/loginAc.action" method="post">

            <table border="1">

                <tr>

                    <td>账号:</td>

                    <td><input type="text" name="u.act" /></td>

                </tr>

                <tr>

                    <td>密码:</td>

                    <td><input type="password" name="u.pwd" /></td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <input type="submit" value="提交" />

                        <input type="button" value="注册" />

                    </td>

                </tr>

            </table>

            <div>${msg }</div>

        </form>

    </body>

</html>


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

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            *{

                font-size: 50px;

            }

        </style>

        <script type="text/javascript">

            //表单验证

            function valid(){

            var flag = true;

            //账号和密码的长度必须在6到30位之间

            var act = document.getElementById('act').value;

            var len = act.length;

            if(len > 30 || len < 6) {

            flag = false;

            alert('账号的长度必须在6到30位之间');

            }

            //两次输入的密码必须一致     

            var pwd = document.getElementById('pwd').value;

            var cpwd = document.getElementById('cpwd').value;

            if(pwd !== cpwd) {

            flag = false;

            alert('两次输入的密码不一致');

            }

            return flag;

            }

        </script>

    </head>

    <body>

        <form action="pub/regAc.action" method="post" onsubmit="return valid();">

            <table border="1">

                <tr>

                    <td>账号:</td>

                    <td><input type="text" name="u.act" id="act" /></td>

                </tr>

                <tr>

                    <td>密码:</td>

                    <td><input type="password" name="u.pwd" id="pwd" /></td>

                </tr>

                <tr>

                    <td>确认密码:</td>

                    <td><input type="password" name="cpwd" id="cpwd"/></td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <input type="submit" value="提交" />

                    </td>

                </tr>

            </table>

        </form>

    </body>

</html>

登录时从jsp界面运行,之后表单提交到action的,通过action的路径运行action。


登录注册的SQL代码:




create table Addr(

id int primary key auto_increment,


pid int,

name  varchar(100)

);

select *   from Addr

select * from addr where pid =0

————


create table Userinfo(

id int primary key auto_increment,


act  varchar(100),

pwd  varchar(100)

);


insert into  Userinfo(


act,

pwd ) values("1","1");



select *   from Userinfo

drop table Userinfo







登录注册 END

例子 END



作业和自己给出的答案 START

一:

1、创建一个Product类,包含pname和price属性

2、创建一个商品展示页面pro.jsp,页面中有一个超链接显示为浏览商品,当点击这个超链接时会跳转到商品详情页面detail.jsp。

3、将pro.jsp页面中的商品名称和商品价格传递到detail页面中去并显示出来,要求使用action实现。


action运行成功的必要条件 START

action运行成功的必要条件 END

商品展示和商品详情的例子 START




create table Product(

pid int primary key auto_increment,



pname  varchar(100),

price double

);

insert into  Product(


pname ,

price) values("sshc","1");

insert into  Product(


pname ,

price) values("sshc2","2");

select *   from Product



package Action;


import java.util.List;


import org.apache.struts2.ServletActionContext;


import Bean.Product;

import Dao.ProductDao;


public class DetailAction {


// private Product a = new Product();

// public Product getA() {

// return a;

// }

//

// public void setA(Product a) {

// this.a = a;

// }

private Integer pid;

private Double price;

private String pname;

public Integer getPid() {

return pid;

}

public void setPid(Integer pid) {

this.pid = pid;

}

public Double getPrice() {

return price;

}

public void setPrice(Double price) {

this.price = price;

}

public String getPname() {

return pname;

}

public void setPname(String pname) {

this.pname = pname;

}

    public String toDetail(){

   

//    Product Product = a;

//    ServletActionContext.getRequest()

//     .getSession().setAttribute("a", a);

    return "success";

    }




}

package Action;


import java.util.List;


import Bean.Product;


import Dao.ProductDao;


public class ProductAction {

private String html;

private ProductDao ProductDao = new ProductDao();


public String getHtml() {

return html;

}


public void setHtml(String html) {

this.html = html;

}


public ProductDao getProductDao() {

return ProductDao;

}


public void setProductDao(ProductDao productDao) {

ProductDao = productDao;

}


//http://localhost:8080/STRUTS2homework1/pub/ProductActionName.action

    public String toProduct(){

    List<Product>list = ProductDao.selectAllProduct();

    StringBuilder sb = new StringBuilder();

   

    sb.append("<table border='1'>"

    + "<tr><th>商品编号</th><th>商品名称</th>"

    + "<th>商品价格</th><th>浏览商品</th></tr>");

   

    for(Product a : list) {

    sb.append("<tr><td>"+

    a.getPid()+

    "</td><td>"+

    a.getPname()

    + "</td><td>"+

    a.getPrice()

    + "</td><td><a href='"

    + "pub/DetailActionName.action?"

//    + "a="

//    +a

    + "pid="

    +a.getPid()

    + "&pname="+a.getPname()

    + "&price="+a.getPrice()

    + "'>"

    + "点击后浏览该商品详情"

    + "</a></td></tr>");

    }

   

    sb.append("</table>");

   

   

    html = sb.toString();

    System.out.println("html:"+html);

    return "success";

    }

}

package Bean;


public class Product {

 

    private Integer pid;

    private String pname;

    private Double price;

public Integer getPid() {

return pid;

}

public void setPid(Integer pid) {

this.pid = pid;

}

public String getPname() {

return pname;

}

public void setPname(String pname) {

this.pname = pname;

}

public Double getPrice() {

return price;

}

public void setPrice(Double price) {

this.price = price;

}

}


package Dao;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


import Utils.DbUtil;

import Bean.Product;



public class ProductDao {

    public List<Product>selectAllProduct(){

    String sql = "select * from Product";

   

    Connection conn = null;

    PreparedStatement pstm = null;

    ResultSet rs = null;

    List<Product>list = new ArrayList<Product>();

    try {

        conn = DbUtil.getConn();

pstm = conn.prepareStatement(sql);

//     pstm.setInt(1, pid);

    rs = pstm.executeQuery();

    while(rs.next()) {

    Product a = new Product();

   

    a.setPid(rs.getInt("pid"));

    a.setPname(rs.getString("Pname"));

    a.setPrice(rs.getDouble("Price"));

    list.add(a);

    }

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

DbUtil.close(rs, pstm, conn);

}

    return list;

    }

}

package Utils;


import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Properties;


public class DbUtil {

private static String driverName;

    private static String url;

    private static String user;

    private static String pwd;

    

    static {

    //读取properties文件

    Properties prop = new Properties();

    //将db.properties文件读取到内存中去

    InputStream is = DbUtil.class.getClassLoader()

    .getResourceAsStream("db.properties");

    //加载内容

    try {

prop.load(is);

//读取内容

driverName = prop.getProperty("drivername");

url = prop.getProperty("url");

user = prop.getProperty("username");

pwd = prop.getProperty("password");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

    

    //获取数据库连接对象的方法

    public static Connection getConn(){

    Connection conn = null;

    try {

Class.forName(driverName);

conn = DriverManager.getConnection(url,user,pwd);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   

    return conn;

    }

    

    public static void close(ResultSet rs,PreparedStatement pstm

    ,Connection conn){

        try {

        if(rs != null) {

            rs.close();

            }

            if(pstm != null) {

            pstm.close();

            }

            if(conn != null) {

            conn.close();

            }

        } catch(Exception e) {

        e.printStackTrace();

        }

    }

}

drivername=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&amp;characterEncoding=GBK2312

username=root

password=root

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">

<struts>

     <package name="SSHC" namespace="/pub" extends="struts-default">

         

         <action name="ProductActionName" class="Action.ProductAction"

             method="toProduct">

             <result>/pro.jsp</result>

         </action>

         

         

         <action name="DetailActionName" class="Action.DetailAction"

             method="toDetail">

             <result>/detail.jsp</result>

         </action> 

         

        

     </package>

</struts>

<?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>STRUTS2homework1</display-name>

  <!-- struts2框架的配置 -->

  <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>

  <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>

</web-app>

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

    pageEncoding="UTF-8"%>

<!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>商品详情</title>

</head>

<body>

<h1>商品详情</h1>


商品编号:${pid }

<br>

商品名称:${pname }

<br>

商品价格:${price }

</body>

</html>

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

    pageEncoding="UTF-8"%>

<!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>商品列表</title>

</head>

<body><h1>商品列表</h1>

${html}

</body>

</html>

启动服务器后,地址栏输入http://localhost:8080/STRUTS2homework1/pub/ProductActionName.action后按回车键得到的运行效果:



商品展示和商品详情的例子 END



二:


4、创建一个页面,将addr表中的所有城市名称拼接成一个下拉框

(见上面的拼接下拉框的例子)




作业和自己给出的答案 END


action运行,拼接下拉框,商品展示,STRUTS2,密码,MD5,代码改后未起效【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律