Simple Struts application development

Source: Internet
Author: User
Tags config copy join sql error stmt trim tld tomcat
Finally, I have finished this test. Hope to be helpful to beginners who want to learn struts.


Directory structure (mystruts application)
Mystruts
|-web-inf
| |-lib
| | | | |-STRUTS.JAR
| | |-CLASSES
| | | | |-ConnectionPool
| | | | | |-GETDBCONNECTION.CLASS
| | | |-mystruts
| | | | |-USER1ACTION.CLASS
| | | | |-USERACTION.CLASS
| | | | |-USERACTIONFORM.CLASS
| | | | |-USERDAO.CLASS
| |-struts-bean.tld
| |-struts-config.xml
| |-struts-html.tld
| |-struts-logic.tld
| |-struts-template.tld
|-adduser.jsp
|-index.jsp
|-viewuser.jsp

First step: Development environment Configuration

(If you do not have the relevant software, please go to http://www.apache.org to download)

tomcat5.0 configuration (Create a mystruts application and copy related files)

Please locate the Confcatalinalocalhost subdirectory in your Tomcat installation directory. New Mystruts.xml File
The contents of the document are as follows. In this file. We will configure a join pool. Please put the relevant driver. Database user, password change to your own native configuration.
And make a copy of the JDBC driver to the Tomcat 5.0commonlib directory. Please put the Struts.jar mystrutsweb-inflib the catalogue.

<context path= "/mystruts" docbase= "d:wwwmystrutsmystrutsmystruts" debug= "0" privileged= "true" >

<resource name= "Jdbc/testdb"
Auth= "Container"
Type= "Javax.sql.DataSource"/>

<resourceparams name= "Jdbc/testdb" >
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>

<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>

<parameter>
<name>maxIdle</name>
<value>5</value>
</parameter>

<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<parameter>
<name>username</name>
<value>sa</value>
</parameter>
<parameter>
<name>password</name>
<value>test</value>
</parameter>

<parameter>
<name>driverClassName</name>
<value>net.sourceforge.jtds.jdbc.Driver</value>
</parameter>

<parameter>
<name>url</name>
<value>jdbc:jtds:sqlserver://192.168.10.223:1433/mystruts</value>
</parameter>
</ResourceParams>
</Context>

Web-inf/web.xml (support for joining Struts Tag library)

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD ">
<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<taglib>
<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/WEB-INF/struts-template.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-template.tld</taglib-location>
</taglib>
</web-app>

Step Two: Configure the database

1. First create the data-join bean and package it to ConnectionPool, which will get the available joins from our configured join pool.

Java Document
Package ConnectionPool;
Import javax.naming.*;
Import javax.sql.*;
Import java.sql.*;
Import java.io.*;
Import java.util.*;

public class Getdbconnection {

Connection Conn;
Statement stmt;
ResultSet Rs=null;

String foo = "Not Connected";
int bar =-1;

Public Getdbconnection () {
try{
Context ctx = new InitialContext ();
if (CTX = null)
throw new Exception ("boom-no context");

DataSource ds =
(DataSource) Ctx.lookup (
"Java:comp/env/jdbc/testdb");

if (ds!= null) {
conn = Ds.getconnection ();

}
}
catch (Exception e) {
E.printstacktrace ();
}
}

Public Connection Getcon ()
{
Return conn;
}


public void D_close () throws SQLException
{
if (Rs!= null) {
try {rs.close ();} catch (SQLException e) {;}
rs = null;
}
if (stmt!= null) {
try {stmt.close ();} catch (SQLException e) {;}
stmt = null;
}
IF (conn!= null) {
try {conn.close ();} catch (SQLException e) {;}
conn = null;
}

}

protected void Finalize () throws Throwable
{
try {d_close ();} catch (SQLException e) {;}
}

}

2. Create a database.

Database name: mystruts

Department Table: MYDEP

_______________________________________
dep_id Dep_name
_______________________________________
1 DEP1
2 DEP2
3 DEP3
4 DEP4
_______________________________________

User table: MyUser
______________________________________________
USER_ID USER_NAME DEP Tel
______________________________________________
1, Jack 1, 0769-2454042.
2 Max 2 0769-2454043
______________________________________________

(Note: The above fields are convenient for testing. All use character type)


Step Three: Create Actionform (Useractionform.java)



Package mystruts; Please pack it down to mystruts.

Import org.apache.struts.action.*;
Import javax.servlet.http.*;

public class Useractionform extends Actionform {
Private String action= "add";
Private String DEP;
Private String Tel;
Private String user_id;
Private String user_name;
Public String getaction () {
Return action;
}
public void Setaction (String action) {
This.action = action;
}
Public String GETDEP () {
return DEP;
}
public void Setdep (String dep) {
THIS.DEP = DEP;
}
Public String Gettel () {
return Tel;
}
public void Settel (String tel) {
This.tel = Tel;
}
Public String getuser_id () {
return user_id;
}
public void setuser_id (String user_id) {
this.user_id = user_id;
}
Public String Getuser_name () {
return user_name;
}
public void Setuser_name (String user_name) {
This.user_name = user_name;
}
Public actionerrors Validate (actionmapping actionmapping, HttpServletRequest httpservletrequest) {

return null;
}
public void Reset (actionmapping actionmapping, HttpServletRequest httpservletrequest) {
}
}


Fourth step: Establish the Database Operation object (completes to the table the deletion modification and the inquiry)

Package mystruts;

Import java.sql.*;
Import connectionpool.*;
Import java.util.*;

public class Userdao {
Getdbconnection Db=null;
Connection Con=null;

Public Userdao () {
}
//-------------------------------------------------------------------
public void Userinsert (Useractionform uaf1)
{
Db=new getdbconnection ();
Con=db.getcon ();
Useractionform UAF=UAF1;
PreparedStatement PS = null;
String sql= "INSERT into MyUser (User_id,user_name,dep,tel) VALUES (?,?,?,?)";
try {

PS = con.preparestatement (SQL);
Ps.setstring (1,uaf.getuser_id ());
Ps.setstring (2,uaf.getuser_name ());
Ps.setstring (3,UAF.GETDEP ());
Ps.setstring (4,uaf.gettel ());
Ps.executeupdate ();
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
}
//---------------------------------------------
public void Userupdate (Useractionform uaf1)
{
Db=new getdbconnection ();
Con=db.getcon ();
Useractionform UAF=UAF1;
PreparedStatement PS = null;
String sql= "Update myuser set user_name=?,dep=?,tel=?" where user_id=? ";
try {

PS = con.preparestatement (SQL);
Ps.setstring (1,uaf.getuser_name ());
Ps.setstring (2,UAF.GETDEP ());
Ps.setstring (3,uaf.gettel ());
Ps.setstring (4,uaf.getuser_id ());
Ps.executeupdate ();
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
}
//---------------------------------------------
Public Useractionform GetUser (String key)
{
Db=new getdbconnection ();
Con=db.getcon ();
ResultSet Rs=null;
Useractionform uaf=new useractionform ();
PreparedStatement PS = null;
String sql= "SELECT * from MyUser where user_id=?";
try {
PS = con.preparestatement (SQL);
Ps.setstring (1,key.trim ());
Rs=ps.executequery ();
if (Rs.next ())
{
UAF.SETUSER_ID (rs.getstring ("user_id"));
Uaf.setuser_name (rs.getstring ("user_name"));
UAF.SETDEP (rs.getstring ("DEP"));
Uaf.settel (Rs.getstring ("tel"));
Uaf.setaction ("edit");
}
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
System.out.println ("mod" +key);
return UAF;
}
//----------------------------------------
public void Deluser (String key)
{
Db=new getdbconnection ();
Con=db.getcon ();
PreparedStatement PS = null;
String sql= "Delete from MyUser where user_id=?";
try {
PS = con.preparestatement (SQL);
Ps.setstring (1,key.trim ());
Ps.executeupdate ();
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
System.out.println ("del" +key);
}
//----------------------------------
Public Collection Getalluser ()
{
Db=new getdbconnection ();
Con=db.getcon ();
ResultSet Rs=null;
Useractionform uaf=new useractionform ();
PreparedStatement PS = null;

ArrayList rslist = new ArrayList ();

String sql= "SELECT * from MyUser u,mydep D where u.dep=d.dep_id";
try {
PS = con.preparestatement (SQL);
Rs=ps.executequery ();
while (Rs.next ())
{
HashMap Rscol = new HashMap ();
Rscol.put ("user_id", Rs.getstring ("user_id"));
Rscol.put ("user_name", rs.getstring ("user_name"));
Rscol.put ("Dep", Rs.getstring ("DEP"));
Rscol.put ("Dep_name", Rs.getstring ("Dep_name"));
Rscol.put ("Tel", rs.getstring ("tel"));
Rslist.add (Rscol);
}
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
return rslist;
}
//----------------------------------
}

Step Fifth: Create action (Useraction.java)

Here we will build two action.

Useraction.java will complete the following tasks.
1. Add (Preliminary data preparation. The main is to extract departmental information. and passed to adduser.jsp)
2. Revise (preliminary data preparation)
3. Delete
4. View all user information.

User1action.java will complete the following tasks
1. Add user (to MyUser table operation)
2. Modify user (to MyUser table operation)

Package mystruts;

Import org.apache.struts.action.*;
Import javax.servlet.http.*;
Import mystruts.*;
Import java.util.*;
Import java.sql.*;
Import connectionpool.*;

public class Useraction extends Action {
Public Actionforward Execute (actionmapping actionmapping, Actionform actionform, HttpServletRequest HttpServletRequest, HttpServletResponse httpservletresponse) throws Exception
{
Userdao dao=new Userdao ();
HttpServletRequest Request=httpservletrequest;
String Action;
if (Request.getparameter ("action"). Equals ("") | | Request.getparameter ("action") ==null)
{
action= "Add";
}
Else
{
Action=request.getparameter ("action");
}
if (Action.equals ("add")
{
Request.setattribute ("Dep", THIS.GETDEP ());
Return (Actionmapping.findforward ("add"));
}
if (action.equals ("edit")
{
String key=request.getparameter ("key");
Request.setattribute ("Dep", THIS.GETDEP ());
Request.setattribute ("Useractionform", Dao.getuser (key));
Return (Actionmapping.findforward ("add"));
}
if (Action.equals ("Del"))
{
String key=request.getparameter ("key");
Dao.deluser (key);
Return (Actionmapping.findforward ("Delview"));
}
if (Action.equals ("View"))
{
Request.setattribute ("RS", Dao.getalluser ());
Return (Actionmapping.findforward ("View"));
}

return null;
}
//---------------------------------------------
Public Collection GETDEP ()
{
Getdbconnection db=new getdbconnection ();
Connection Con=db.getcon ();
ResultSet Rs=null;

PreparedStatement PS = null;

ArrayList rslist = new ArrayList ();

String sql= "SELECT * from MYDEP";
try {
PS = con.preparestatement (SQL);
Rs=ps.executequery ();
while (Rs.next ())
{
HashMap Rscol = new HashMap ();
Rscol.put ("id", rs.getstring ("dep_id"));
Rscol.put ("Name1", Rs.getstring ("Dep_name"));
Rslist.add (Rscol);
}
}
catch (SQLException e)
{
SYSTEM.OUT.PRINTLN ("SQL Error");
}
Finally
{
try{
Con.close ();
Db.d_close ();
}
catch (Exception e) {}
}
return rslist;
}
}



Package mystruts;

Import org.apache.struts.action.*;
Import javax.servlet.http.*;

public class User1action extends Action {
Public Actionforward Execute (actionmapping actionmapping, Actionform actionform, HttpServletRequest HttpServletRequest, HttpServletResponse httpservletresponse) throws Exception
{
Useractionform UAF = (useractionform) actionform;
if (Uaf.getaction (). Equals ("Add")
{
New Userdao (). Userinsert (UAF);
Return (Actionmapping.findforward ("View"));
}
if (Uaf.getaction (). Equals ("edit")
{
New Userdao (). Userupdate (UAF);
Return (Actionmapping.findforward ("View"));
}
return null;
}
}


Step Sixth: Create a JSP view page (there are two main JSP files.) add page. adduser.jsp View page viewuser.jsp)

adduser.jsp

<%@ taglib uri= "/web-inf/struts-logic.tld" prefix= "logic"%>
<%@ taglib uri= "/web-inf/struts-template.tld" prefix= "template"%>
<%@ taglib uri= "/web-inf/struts-bean.tld" prefix= "Bean"%>
<%@ taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>
<%@ page contenttype= "text/html; charset=gb2312 "%>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">
<title>
AddUser
</title>
<body>
<p>
<br>
Department:
<br>
Id:
<logic:equal name= "Useractionform" property= "action" scope= "request" value= "Add" >
</logic:equal>
<logic:equal name= "Useractionform" property= "action" scope= "request" value= "edit" >
</logic:equal>
<br>
Name: <br>
Tel: <br>
</body>

viewuser.jsp

<%@ taglib uri= "/web-inf/struts-logic.tld" prefix= "logic"%>
<%@ taglib uri= "/web-inf/struts-template.tld" prefix= "template"%>
<%@ taglib uri= "/web-inf/struts-bean.tld" prefix= "Bean"%>
<%@ taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>
<%@ page contenttype= "text/html; CHARSET=GBK "%>
<title>
Viewuser
</title>
<body>
<div align= "center" ><a href= "Useraction.do?action=add" >add </a></div>
<table width= "60%" border= "1" align= "Center" >
<tr bgcolor= "#CCCCCC" >
<td>ID</td>
<td>user_name</td>
<td>dep</td>
<td>tel</td>
<td>modify</td>
<td>del</td>
</tr>
<logic:iterate name= "rs" id= "user" scope= "request" type= "Java.util.HashMap" >
<tr>
<td><bean:write name= "user" property= "user_id"/> </td>
<td><bean:write name= "user" property= "user_name"/> </td>
<td><bean:write name= "user" property= "dep_name"/> </td>
<td><bean:write name= "User" property= "tel"/> </td>
<td><a href= "Useraction.do?action=edit&key=<bean:write name=" user "property=" user_id "/>" > Modify</a></td>
<td><a href= "Useraction.do?action=del&key=<bean:write name=" user "property=" user_id "/>" >del </a></td>
</tr>
</logic:iterate>
</table>
</body>

Build a Steering page (index.jsp)
<%@ page contenttype= "text/html; charset=gb2312 "%>
<title>untitled document</title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

<body>
<% response.sendredirect ("Useraction.do?action=view"); %>
</body>

Seven steps: Build struts configuration file (Web-inf/config-struts.xml)

<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE struts-config Public "-//apache Software foundation//dtd struts Configuration 1.1//en" "http:// Jakarta.apache.org/struts/dtds/struts-config_1_1.dtd ">
<struts-config>
<form-beans>
<form-bean name= "Useractionform" type= "Mystruts.useractionform"/>
</form-beans>
<action-mappings>
<action type= "mystruts.useraction" scope= "Request" path= "/useraction" >
<forward name= "View" path= "/viewuser.jsp"/>
<forward name= "Add" path= "/adduser.jsp"/>
<forward name= "Delview" path= "/useraction.do?action=view"/>
</action>
<action name= "Useractionform" type= "mystruts.user1action" scope= "Request" path= "/user1action" >
<forward name= "View" path= "/useraction.do?action=view"/>
</action>
</action-mappings>
</struts-config>

To run the program:
Start Tomcat
Start IE in the address bar input: http://localhost:8080/mystruts

Ok.....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.