How to build a Struts database application with landing pages and roles
[aims]
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:
For example, the above data may have a role or multiple roles. For multiple characters, you can use multiple records to indicate that a record represents a role or a record represents a plurality of roles, each role is separated by ";".
[effect]
Welcome page:
login page:
The main menu page after the landing is completed:
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 "Struts Database Application", in addition to a selection "Struts Database Application Template" with Land and Roles "when establishing a new project, another selection" empty struts database application template ", And in the JSP page, you need to check if the user has logged in. "
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.
Using the project generated by the Struts Database Application Template with Logging Page and Roles, the logon.jsp and logonaction.java file required for the user login, and also generates files for user login demo, where Index.htm It is a "landing" button, click the "Log" button to go to the Logon.jsp Enter the input page, the login input is completed and submit, and if you log in, go to the MainMenu.jsp main menu page. Add a label after the main menu page head> tag "
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 tab 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, run the mainmenu.jsp main menu page or the useerEdit.jsp Query page, will automatically go to the user login page, not here Reemptory.
Also, if the user doesn't have this, I can't log in to the page.
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;
/ **
* Implementation of action strong> That Validates a User Logon.
*
* @Author craig R. McClanahan
* @version $ revision: 1.14 $ $ date: 20
03/01/11
03:08:23 $
* /
Public Final Class LogonAction Extends Action {
/ / -------------------------------------------------------------------------------------------- ----- Instance Variables
/ **
* The log code> instance for this application.
* /
Private log log =
Logfactory.getlog ("Org.apache.struts.WebApp.example"); Private ConnectionPool Pool;
Public logonAction () {
Pool = connectionPool.getInstance ();
}
/ / -------------------------------------------------------------------------------------------- --------- Public Methods
/ **
* Process The Specified Http Request, and Create The Corresponding HTTP
* Response (or Forward to another Web Component That Will Create IT).
* Return AN Actionforward code> Instance Describing Where and how
* Control SHOULD BE Forwarded, or Null code> if The Response HAS
* Already Been Completed.
*
* @Param mapping the actionMapping use to select this instance
* @Param Form The Optional Actionform Bean for this Request (if any)
* @Param Request The Http Request WE Are Processing
* @Param Response The Http Response We Are Creating
*
* @Exception Exception if Business Logic THROWS AN Exception
* /
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");
String getUsername = Checkuser (username, password);
IF ("" .equals (getusername))
{
Errors.Add (actionerroS.Global_ERROR,
New ActionError ("Error.Password.mismatch))));
}
GetUsername = username getusername;
// Report Any Errors We Have Discovered Back to The Original Formif (! Errors.Isempty ()) {
SaveerRors (Request, Errors);
Mapping.getInputForward ());
}
// Save Our Logged-in User In the session
HttpSession session = request.getations ();
Session.SetaTRibute (constants.user_
Key
GetUsername;
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"));
}
/ / -------------------------------------------------------------------------------------------- ------ Protected Methods
/ **
* Look Up The User, throwing an exception to simulate business logic
* Rule Exceptions.
*
* @Param Database Database in Which to Look Up The User
* @Param Username UserName Specified On The Logon Form
*
* @Exception ModuleException if a business logic rule is violated
* /
Public String 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 ();
String Returnstr = ""
While (rs.next ())
{
Returnstr = ";" rs.getstring ("role");}
Return Returnstr;
} 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 org.apache.struts.util.RequestUtils;
Import org.apache.struts.util.responseutils;
Import javax.servlet.jsp.jspexception;
Import javax.servlet.jsp.tageXt.tagsupport;
Import org.apache.struts.config.moduleconfig;
/ **
* Check for a valid user logged on in the current session. If there is no
* Such User, Forward Control to the Logon Page.
*
* @Author craig R. McClanahan
* @Author Marius Barduta
* @version $ revision: 1.8 $ $ date: 20
03/04/09
02:28:24 $
* /
Public final class checklogontag outs tagsupport {
Private string role = "";
/ / -------------------------------------------------------------------------------------------- --- Instance Variables
/ **
* The key of the session-scope bean we look for.
* /
Private string name = constants.user_
Key
;
/ **
* The page to which we should forward for the user to log on.
* /
Private string Page = "/logon.jsp";
/ / -------------------------------------------------------------------------------------------- ----------- Properties / **
* Return the bean name.
* /
Public string getname () {
Return (this.name);
}
/ **
* Set the bean name.
*
* @Param Name the New Bean Name
* /
Public void setname (String name) {
THIS.NAME = Name;
}
/ **
* Return The Forward Page.
* /
Public string getpage () {
Return (this.page);
}
/ **
* SET The Forward Page.
*
* @Param Page The New Forward Page
* /
Public void setpage (string page) {
THIS.PAGE = Page;
}
Public void setrole (String newrole)
{
Role = newrole;
}
Public String getRole ()
{
Return role;
}
/ / -------------------------------------------------------------------------------------------- ------- Public Methods
/ **
* Defer we checking untric the end of this tag is encountered.
*
* @Exception JSPEXCEPTION IF A JSP Exception Has Occurre
* /
Public int desartTartTag () throws jspexception {
Return (SKIP_BODY);
}
/ **
* Performur Logged-in User CHECK BY LOOKING FOR THE EXISTENCE OF
* a session scope bean under the specified name. if this bean is not
* Present, Control is Forwarded to the specified logon page.
*
* @Exception JSPEXCEPTION IF A JSP Exception Has Occurre
* /
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)) {
String str = "null";
String getUsername = "null";
String getrole = "null";
Try
{
Str = (string) session.getattribute (name);
GetUsername = str.substring (0, str.indexof (";"));
Getrole = str.substring (Str.Indexof (";") 1, str.length ()). Trim ();
IF (Checkrole (Role, Getrole) {
VALID = TRUE;
}
}
Catch (Exception E) {
Valid = false;
}
/ *
Responseutils.write (PageContext, STR);
Responseutils.write (PageContext, "
p>");
Responseutils.write (pageContext, getusername);
Responseutils.write (PageContext, "
p>");
ResponseUtils.write (pageContext, getrole);
Responseutils.write (PageContext, "
p>");
Responseutils.write (PageContext, Role);
* /
}
// Return Skip_body;
// 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
);
}
}
/ **
* Release Any acquired resources.
* /
Public void release () {
Super.release ();
THIS.NAME = Constants.user_
Key
;
THIS.PAGE = "/logon.jsp";
THIS.ROLE = "";
}
Public Boolean Checkrole (String Role, String Getrole)
{
Getrole = getrole.trim () ;;
Role = role.trim ();
//if (""".equals(Getrole ))Return False;
String thisrole;
While (Getrole.Indexof (";")> 1)
{
Thisrole = getrole.substring (0, getrole.indexof (";")). TRIM ();
Getrole = getrole.substring (Getrole.Indexof (";") 1, getrole.length ()). Trim ();
IF (Role.Equals (thisrole))
{
Return True;
}
}
Thisrole = getrole;
IF (Role.Equals (thisrole))
{
Return True;
}
Return False;
}
}
[Extension]
The above is the
1, the label uses
2. Change the checkrole () function of the checklogontag.java file as follows:
Package EmptyPRJ;
Import java.io.ioException;
Import javax.servlet.servletException;
Import javax.servlet.http.httpsession;
Import org.apache.struts.util.RequestUtils;
Import org.apache.struts.util.responseutils;
Import javax.servlet.jsp.jspexception;
Import javax.servlet.jsp.tageXt.tagsupport;
Import org.apache.struts.config.moduleconfig;
Import org.apache.struts.global;
Import org.apache.struts.util.MessageResources;
Import org.apache.struts.Action.Actionerror;
Import org.apache.struts.Action.Actionerro;
Public final class checklogontag outs tagsupport {
Private string role = "";
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 void setrole (String newrole)
{
Role = newrole;
}
Public String getRole ()
{
Return role;
}
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)) {
String str = "null";
String getUsername = "null"; string getrole = "null";
Try
{
Str = (string) session.getattribute (name);
GetUsername = str.substring (0, str.indexof (";"));
Getrole = str.substring (Str.Indexof (";") 1, str.length ()). Trim ();
If (checkrole (role, getrole) // role is the role specified by the label, GETROLE is the user role read from the database.
{
VALID = TRUE;
}
}
Catch (Exception E) {
Valid = false;
}
/ *
Responseutils.write (PageContext, STR);
Responseutils.write (PageContext, "
p>");
Responseutils.write (pageContext, getusername);
Responseutils.write (PageContext, "
p>");
ResponseUtils.write (pageContext, getrole);
Responseutils.write (PageContext, "
p>");
Responseutils.write (PageContext, Role);
* /
}
// Return Skip_body;
// forward control based on the results
IF (Valid) {
Return (EVAL_
Page
);
} else {
ActionerroS Errors = new actionerrors ();
Errors.Add (actionerroS.Global_ERROR,
New ActionError ("Error.Password.mismatch))));
PageContext.getRequest (). SetAttribute (Globals.Error_
Key
, Errors); // Save an error message
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
);
}
}
/ **
* Release Any acquired resources.
* /
Public void release () {
Super.release ();
THIS.NAME = Constants.user_
Key
;
THIS.PAGE = "/logon.jsp";
THIS.ROLE = "";
}
Public Boolean Checkrole (String Role, String Getrole) // Role is the role specified by the label, and getRole is the user role that is read from the database. {
Getrole = getrole.trim () ;;
Role = role.trim ();
//if (""".equals(Getrole ))Return False;
String thisrole;
Role = ";" Role ";";
While (Getrole.Indexof (";")> 1)
{
Thisrole = getrole.substring (0, getrole.indexof (";")). TRIM ();
Getrole = getrole.substring (Getrole.Indexof (";") 1, getrole.length ()). Trim ();
Thisrole = ";" THISROLE ";";
IF (Role.Indexof (thisrole, 0)> - 1)
{
Return True;
}
}
Thisrole = getrole;
Thisrole = ";" THISROLE ";";
IF (Role.Indexof (thisrole, 0)> - 1)
{
Return True;
}
Return False;
}
}