How to build a Struts database application with landing page
[Related Links]
"JavaWebstudio Series Development Tools Visaul Struts Version" http://dev.9cbs.net/develop/Article/28/28871.shtm
"How to achieve the simplest Struts program" http://dev.9cbs.net/develop/Article/28/28946.shtm
"The implementation of the Struts drop-down box" http://dev.9cbs.net/develop/Article/28/28956.shtm
"The implementation of the Sruts radio box" http://dev.9cbs.net/develop/Article/29/29042.shtm
"Struts check box" http://dev.9cbs.net/develop/Article/29/29043.shtm
"The relationship between the Struts programs (1)" http://dev.9cbs.net/develop/Article/29/29131.shtm
The relationship between the "Struts program each file (2)" http://dev.9cbs.net/develop/Article/29/29133.shtm
"How to implement Struts database application (1) http://dev.9cbs.net/develop/Article/29/29151.shtm
"How to implement Struts database applications (2)" http://dev.9cbs.net/develop/Article/29/29138.shtm
"How to implement pagination display in the Struts database application (1)" http://dev.9cbs.net/develop/Article/29/29139.shtm
"How to implement pagination display in the Struts database application (2)" http://dev.9cbs.net/develop/Article/29/29140.shtm
"How to implement records in the Struts database application" http://dev.9cbs.net/develop/Article/29/29219.SHTM
"How to implement records in the Struts database application (continued)" http://dev.9cbs.net/develop/Article/29/29222.shtm
"How to achieve records in the Struts database application" http://dev.9cbs.net/develop/Article/29/29224.shtm
"How to implement records in the Struts database application (continued)" http://dev.9cbs.net/develop/Article/29/29227.shtm
"How to build a Struts database application with landing page"
"How to build a Struts database application with landing page and role"
http://community.9cbs.net/expert/topic/3084/3084548.xml?temp=.9735529
http://dev.9cbs.net/user/kui
The above example development environment: Java Web Studio Series Development Environment Visual Strutst version.
The latest JavaWebStudio download address: ftp: //210.36.64.79/kui
The above example source program download address: ftp: //210.36.64.79/kui
[the goal]
The goal of this example is to implement a user login application. Save user information with SQL Server 2000 database. Implement the user login page, user login verification, login check tag and other functions.
Define a field named "Users" table:
Enter some test data:
[effect]
Welcome page:
Log in page: Login is completed, the main menu page:
If you do not log in but run the main menu page user query page, you will automatically go to the user login page, and no longer give a show.
[background knowledge]
[step]
This example is compared with the steps in the "How to Struts Database Application", in addition to a selection "Struts Database Application Template" with Login Page "when establishing a new project, another selection" empty struts database application template ", and The JSP page needs to be checked if the user has logged in to add a label "
1. Open the Visual Struts development environment:
Start JavaWebStudio.exe files from the desktop JavaWebstudio fast or bin directory launched the Visual Struts development environment of JavaWebStudio.
2. Create an "empty Struts database application template application" application:
Select the menu "File" - "New" - "New Project", pop up the new project dialog, as shown in Figure 1 below:
Select "Empty Struts Database Application Template" in the dialog box, enter "Logon", Package (Package ", and location (path path) in the project name, which is of course changed as needed. Finally, click the "OK" button to complete the establishment of the new project.
In the root of the Logon project, you contain four subdirectories and two files, which is the standard structure of the JavaWebStudio project, it is best not to change their default names, otherwise there will be problems.
With the "Struts Database Application Template" with Login Page, the logon.jsp and LogonAction.java files required for the user login are automatically generated, and also generates files for user login demo, where index.htm is with There is a "landing" button, click the "Login" button to go to the logon.jsp login input page, the login input is completed and submit, and if you log in, go to the MainMenu.jsp main menu page. Add a tab when the main menu page head> tag is added to check if the user has already logged in. If you have logged in, continue the page, otherwise you will automatically go to the login page.
Logon.jsp file:
INDEX.HTM file:
MainMenu.jsp file:
3. Use the Struts Database Application File Wizard to establish a new application:
To click the right mouse button in the JavaWebStudio file manager, select the Struts Database Application File Wizard to enter the Struts File Wizard dialog box, or select the menu "file" - "Struts Database Application File Wizard" The Struts File Wizard dialog box.
Enter the "Useredit" file name in the filename input field under the Struts file wizard dialog jsp file, other files use the default settings.
(1) Enter the file name:
(2) Import the field information of the SQL statement and the data table from the data source (field name, and field type):
(3) Select the desired table "User" from the data table.
It is important to note that the "Field information of the SQL statement and data table from the data source" and "Select the table from the data table" is merely generated to automatically generate SQL statements and read field information, here Complete can be manually entered directly, unrelated to the configuration of the database connection pool, below, and then configure the database connection pool separately.
Next, configure the database connection pool, and other property pages can be used by default, and the data connection configuration property page is directly turned directly. (4) JSPOUT property page settings:
The setting of the JSPOUT property page is the only step in the "How to Implement Struts Database Application", which is the core content of this example. As can be seen from the figure, we have to do it just to add the "Record Operation" selection in the settings of the "Record Operation" selection item.
(5) Configure the database connection pool:
Here you need to note that the user login is also used to use this database connection configuration.
(6) Plus the user login check label in the newly generated JSP file
The newly generated JSP file has three, query conditions Enter file useerEdit.jsp, add new record input files UserEditInsert.jsp and query results display file useritout.jsp. Add the user login check tag
4, project file structure
Project directory structure analysis See "How to achieve the simplest struts program", this Struts database application file wizard automatically generates six files, where the web directory is input, output two JSP files, the SRC directory is a Java file. All program source code is automatically generated by the file wizard except that the file name is automatically generated, and all configurations are also automatically completed.
Refresh the JavaWebStudio file manager, then the three files are automatically generated in the web directory, which is useeredit.jsp and useeredit.jsp and useritinsert.jsp, the former is an input JSP file, the middle is output JSP file, the latter is adding a record Page file; SRC / EMPTYPRJ directory automatically generates four files, which are useeredit action.java, useeredit form.java, the former is an action file, the latter is a formaction file; there is a database operation file Useredit.java and Usereditdao. Java, the former is used to save the bean recorded by the data table, and the latter is a database operation DAO file.
4.1, modify the DAO file:
If the data is selected, SQL Server 2000, you need to put the following code in the DAO file:
// Please join the down with SQL Server:
//con.setautoCommit (true);
// SQL Server
Both rewritten into the following code:
// Please join the down with SQL Server:
Con.SetAutocommit (True); // Note !! This is this line, it turned out to be annotated, now you have to get your annotation !!
// SQL Server
Through the above rewriting, the SQL Server 2000 can be recorded, deleted, and adding the SQL Server 2000 by JDBC.
4.2 Join the login identification label on the place where the user login identification is required
(1) Useredit.jsp file:
Plus
<% @ page contenttype = "text / html; charset = GB2312" Language = "java"%>
<% @ Taglib Uri = "/ Web-INF / STRUTS-Bean.tld" prefix = "bean"%>
<% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "HTML"%> <% @ Taglib URI = "/ Web-inf / struts-logic.tld" prefix = "logic"%>
<% @ Taglib URI = "/ Web-INF / STRUTS-TEMPLATE.TLD" prefix = "template"%>
hEAD>
Please enter the username you want to find:
html: form>
html: form>
body>
html: html>
4.3 Join a new menu item "User Check" in the left page of the MainMenu.jsp Main Menu page Left.htm:
5, compile, start the server, run:
Compile the project and start the server by the buttons on the toolbar, then open index.htm and run index.htm through the "Run" button on the toolbar and enter the corresponding data:
Click "Login":
Enter the correct username and password, select "Send", go to the main menu page:
If you do not log in but run the mainmenu.jsp main menu page or the UseRedit.jsp Query page, you will automatically go to the user login page, which is no longer demonstrated.
Through the above steps, the estimated target function is achieved.
[Program source code]
Compared with "How to Implement Struts Database Applications", this example is mainly a logon.jsp, logonaction.java file that users need to log in, and custom label files used to check if the user has logged in Checklogontag.java, due to Logon The .jsp file does not have a special place, so it is not listed here.
LogonAction.java file:
Package EmptyPRJ;
Import emptyprj.jdbc.util.ConnectionPool; import java.util.locale;
Import javax.servlet.http.httpservletRequest;
Import javax.servlet.http.httpsession;
Import javax.servlet.http.httpservletResponse;
Import org.apache.commons.logging.log;
Import org.apache.commons.logging.logfactory;
Import org.apache.struts.Action.action;
Import org.apache.struts.Action.Actionerror;
Import org.apache.struts.Action.Actionerro;
Import org.apache.struts.Action.actionform;
Import org.apache.struts.Action.actionForward;
Import org.apache.struts.action.actionmapping;
Import org.apache.struts.util.moduleException;
Import org.apache.struts.util.MessageResources;
Import org.apache.commons.beanutils.propertyUtils;
Import java.sql.connection;
Import java.sql.preparedStatement;
Import java.sql.resultset;
Import java.sql.sqlexception;
Import java.util.hashmap;
Import java.util.collection;
Public Final Class LogonAction Extends Action {
Private log log =
Logfactory.getlog ("Org.apache.struts.WebApp.example");
PRIVATE CONNECTIONPOOL POOL;
Public logonAction () {
Pool = connectionPool.getInstance ();
}
Public ActionForward Execute (ActionMapping Mapping,
Actionform Form,
HTTPSERVLETREQUEST REQUEST,
Httpservletresponse response
Throws exception {
// Extract Attributes We Will Need
Locale locale = getLocale (request);
MessageResources Messages = GetResources (Request);
// Validate the Request Parameters Specified by The User
ActionerroS Errors = new actionerrors ();
String UserName = (String)
PropertyUtils.getsimpleProperty (Form, "UserName");
String password = (string)
PropertyUtils.getsimpleProperty (Form, "Password");
IF (! Checkuser (username, password))
{
Errors.add (ActionerRors.global_ERROR, New Actionerror ("Error.Password.mismatch));
}
// Report Any Erroors We Have Discovered Back to the Original Form
IF (! errors.isempty ()) {
SaveerRors (Request, Errors);
Mapping.getInputForward ());
}
// Save Our Logged-in User In the session
HttpSession session = request.getations ();
Session.SetaTRibute (constants.user_key, username);
IF (log.Indebugeload ()) {
Log.debug ("LogonAction: User '" UserName
"'logged on in session" session.getID ());
}
// Remove the Obsolete form bean
IF (mapping.getattribute ()! = null) {
IF ("REQUEST" .Equals (mapping.getscope ()))))
Request.Removettribute (mapping.getattribute ());
Else
Session.Removettribute (mapping.getattribute ());
}
// forward control to the specified surcess URI
Mapping.Findforward ("Success"));
}
Public Boolean Checkuser (String Username, String Password)
{
Connection con = NULL;
Try
{
Con = pool.getConnection ();
String SQL = "SELECT * from DBo.Users where username =? And password =?";
PreparedStatement PS = NULL;
ResultSet RS = NULL;
Try {
IF (con?isclosed ()) {
Throw new IllegalStateException ("Error.con.isClosed");
}
PS = con.preparestatement (SQL);
ps.setstring (1, username);
Ps.setstring (2, password);
RS = ps.executeQuery ();
IF (rs.next ())
{
Return True;
}
Return False;
} catch (sqlexception e) {
E.PrintStackTrace ();
Throw new runtimeException ("Error.ps.executeQuery);
} finally {
Try {
IF (PS! = NULL)
ps.close ();
IF (rs! = null)
Rs.close ();
} catch (sqlexception e) {
E.PrintStackTrace ();
Throw new runtimeException ("error.rs.close");}
}
}
Catch (SQLException E)
{
E.PrintStackTrace ();
Throw new runtimeException ("Unable to get connection.");
}
Finally
{
Try
{
IF (con! = null)
C. close ();
}
Catch (SQLException E)
{
Throw new runtimeException (E.GetMessage ());
}
}
}
}
Checklogontag.java file:
Used to check if the user has logged in the custom tag original code.
Package EmptyPRJ;
Import java.io.ioException;
Import javax.servlet.servletException;
Import javax.servlet.http.httpsession;
Import javax.servlet.jsp.jspexception;
Import javax.servlet.jsp.tageXt.tagsupport;
Import org.apache.struts.config.moduleconfig;
Public final class checklogontag outs tagsupport {
PRIVATE STRING NAME = constants.user_key;
Private string Page = "/logon.jsp";
Public string getname () {
Return (this.name);
}
Public void setname (String name) {
THIS.NAME = Name;
}
Public string getpage () {
Return (this.page);
}
Public void setpage (string page) {
THIS.PAGE = Page;
}
Public int desartTartTag () throws jspexception {
Return (SKIP_BODY);
}
PUBLIC INT DOENDTAG () THROWS JSPEXCEPTION {
// Is there a valid user logged on?
Boolean Valid = False;
HttpSession session = pageContext.getations ();
IF ((session! = null) && (session.getattribute (name)! = NULL)) {
VALID = TRUE;
}
// forward control based on the results
IF (Valid) {
Return (Eval_Page);
} else {
ModuleConfig CONFIG =
(ModuleConfig) PageContext.getServletContext (). GetaTtribute (
Org.apache.struts.globals.Module_Key);
Try {
PageContext.Forward (config.getprefix () page);
} catch (servletexception e) {
Throw new JSPEXCEPTION (E.TOString ());
} catch (ioexception e) {
Throw new JSPEXCEPTION (E.TOString ());
Return (SKIP_PAGE);
}
}
Public void release () {
Super.release ();
THIS.NAME = constants.user_key;
THIS.PAGE = "/logon.jsp";
}
}