Struts small project under myeclipse-follow the tutorial (1)

Source: Internet
Author: User
Tags mysql command line
 

Users can access the Forum and register as members. Forum members can log on to the Forum to post and reply to others' posts. forum administrators can log on to the background to manage Forum users, posts, and post categories. This instance is developed using myeclipse8.6, the database uses MySQL, and finally the program is deployed to the tomcat5.5 server. The instance database mybbs contains six tables: Admin, answer, item, subitem, topic and userinfo. We will introduce the structure of each table to the students one by one in the appropriate chapters.

1. In the computer running, press cmd to open the control panel, enter Net start MySQL, and then enter. Your MySQL server starts.

2. Create a folder bbs_ SQL on a disk. For example, E: \ bbs_ SQL. Create the userinfo. SQL file in the folder as follows:

Create a mybbs database in MySQL and create a userinfo table in the database.

create database mybbs; use mybbs; create table `mybbs`.`userinfo`(         `userid` int not null auto_increment,        `username` varchar(20) default '' not null,        `userpwd` varchar(20) default '' not null,        `userques` varchar(50) default '' not null,       `userans` varchar(50) default '' not null,        `integral` int not null,        `grade` varchar(20) default '' not null,        `useremail` varchar(20) default '' not null,        `sex` bit,         primary key (`userid`)     )TYPE=INNODB,           default character set gbk;

3. Open the MySQL command line client control panel and enter your database password. That is, the password you changed when installing the MySQL database. The original account password is root and root. See mysql->

Enter source E: \ bbs_ SQL \ userinfo. SQL (no extra points are required here;) and enter. Check whether the creation is successful. If it succeeds, the next step is 4th.

4. Open your myeclipse software, file-> New-> Web project, and enter the project name mybbs. Then add struts support to the project, right-click the project root node [mybbs] development [myeclipse] development [add struts capabilities], and click [finish ]. In this way, a project supporting struts is created. We can see that the struts 1.2 libraries class library is added to the project to open the web. XML shows that the following information is added to the web-app node:

  <servlet>    <servlet-name>action</servlet-name>    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>    <init-param>      <param-name>config</param-name>      <param-value>/WEB-INF/struts-config.xml</param-value>    </init-param>    <init-param>      <param-name>debug</param-name>      <param-value>3</param-value>    </init-param>    <init-param>      <param-name>detail</param-name>      <param-value>3</param-value>    </init-param>    <load-on-startup>0</load-on-startup>  </servlet>  <servlet-mapping>    <servlet-name>action</servlet-name>    <url-pattern>*.do</url-pattern>  </servlet-mapping>

5. Create a JSP folder under the webroot directory and create four JSP documents respectively.

Login. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" gb2312 "%> <form action =" <% = request. getcontextpath () %>/loginaction. do "> Username: <input type =" text "name =" name "size =" 35 "maxlength =" 35 "/> password: <input type = "password" name = "password" size = "35" maxlength = "35"/> Verification Code: <input type = "text" name = "RAND" size = "20" maxlength = "20"> /JSP/image. JSP "/> <input type =" Submit "value =" Submit "/> <input type =" reset "value =" reset "/> </form>

Image. jsp Verification Code Generation

<% @ Page contenttype = "image/JPEG" Import = "Java. AWT. *, Java. AWT. image. *, Java. util. *, javax. imageIO. * "pageencoding =" gb2312 "%> <%! Color getrandcolor (int fc, int BC) {// obtain the random color random = new random (); If (FC> 255) fc = 255; if (BC> 255) BC = 255; int r = FC + random. nextint (BC-Fc); int G = FC + random. nextint (BC-Fc); int B = FC + random. nextint (BC-Fc); return new color (R, G, B) ;}%> <% // set the page to not cache response. setheader ("Pragma", "No-Cache"); response. setheader ("cache-control", "No-Cache"); response. setdateheader ("expires", 0); // create an image in the memory int width = 60, Height = 20; bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb); // obtain the image context graphics G = image. getgraphics (); // generate random class random = new random (); // set the background color G. setcolor (getrandcolor (200,250); G. fillrect (0, 0, width, height); // set the font G. setfont (new font ("Times New Roman", Font. plain, 18); // generates 155 random interference lines, making the identification code in the image hard to be detected by other programs. setcolor (getrandcolor (160,200); For (INT I = 0; I <155; I ++) {int x = random. nextint (width); int y = random. nextint (height); int XL = random. nextint (12); int yl = random. nextint (12); G. drawline (X, Y, x + XL, Y + yl);} // obtain the random ID code (4 digits) string srand = ""; for (INT I = 0; I <4; I ++) {string Rand = string. valueof (random. nextint (10); srand + = rand; // display the authentication code to the image G. setcolor (new color (20 + random. nextint (110), 20 + random. nextint (110), 20 + random. nextint (110); // The color from the call function is the same, probably because the seed is too close, so you can only generate G directly. drawstring (RAND, 13 * I + 6, 16);} // Save the authentication code to the session. setattribute ("RAND", srand); // image effective G. dispose (); // output the image to the ImageIO page. write (image, "Jpeg", response. getoutputstream (); out. clear (); out = pagecontext. pushbody (); %>

Error. jsp account password verification error page displayed

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" gb2312 "%> <font face =" "size =" 4 "color =" red "> your username or password is incorrect </font>

Page displayed after success. jsp account and password verification is successful

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" gb2312 "%> <font face =" "size =" 4 "> logon successful </font>

Note: It is best to add the following sentence to the content of each JSP document:

<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%>

This ensures the unified encoding of the encoding file. In addition, projects under myeclipse also need to check whether the file encoding is GBK on the properties of the project. The two must be consistent, otherwise garbled code will be generated. It is better to be consistent with the database encoding.

6. Create a com. mybbs. pojo package in SRC and create a pojo class named userinfo under the package. The content is as follows:

// User ID private int userid; // user name private string username; // password private string userpwd; // password retrieval private string userques; // password retrieval answer private string userans; // user points Private int ntegral; // user level private string grade; // user email private string useremail; // gender private byte sex;

Use myeclipse to produce accessors.

The production accessors are operated as follows: In the pojo class of userinfo, click Generate getters setters under source in the menu bar... in this case, select the property (variable) -- OK OF THE accessor to be generated.

7. Create a com. mybbs. Dao package and create a jdbcdao. Java and userinfodao. Java class under the package to access the database. In the class, type the following code:

Package COM. mybbs. dao; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. SQL. statement; public class jdbcdao {// database connection object protected connection conn = NULL; // defines the statement variable protected statement stmt = NULL; // defines the preparedstatement variable protected preparedstatement pstmt = NULL; // result set protected result Set rs = NULL; // MySQL database driver private string driverclass_name = "com. mySQL. JDBC. driver "; // MySQL Database URL private string url =" JDBC: mysql: // localhost: 3306/mybbs? User = root & Password = root "; // default constructor public jdbcdao () {}// obtain the public void getconnection () {connection conn = NULL for the database connection; try {// JDBC connection class. forname (driverclass_name); Conn = drivermanager. getconnection (URL); this. conn = conn;} catch (sqlexception ex) {ex. printstacktrace ();} catch (classnotfoundexception ex) {ex. printstacktrace () ;}}// close the database connection public void closeconnction () {If (RS! = NULL) {try {Rs. Close () ;}catch (sqlexception ex) {ex. printstacktrace () ;}} if (stmt! = NULL) {try {stmt. Close () ;}catch (sqlexception ex) {ex. printstacktrace () ;}} if (pstmt! = NULL) {try {pstmt. Close () ;}catch (sqlexception ex) {ex. printstacktrace () ;}} if (Conn! = NULL) {try {conn. Close () ;}catch (sqlexception ex) {ex. printstacktrace ();}}}}

Package COM. mybbs. dao; import Java. SQL. connection; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. util. list; import Java. util. arraylist; import COM. mybbs. pojo. userinfo; public class userinfodao extends jdbcdao {// define its own variable Private Static userinfodao = NULL; // define its own private constructor private userinfodao (){}; // return userinfodao to the public synchronized static user on the client in simple single-Profit Mode Infodao getuserinfodao () {If (userinfodao! = NULL) {return userinfodao;} userinfodao = new userinfodao (); Return userinfodao;} // get user information, return the public list <userinfo> getperson (userinfo user) {// Declaration of the set list <userinfo> List = new arraylist () used to store user information in the form of a list (); // obtain the database connection super. getconnection (); // define the SQL statement to be executed string sqlstring = "select * From userinfo where username =? And userpwd =? "; Try {// pre-compiled SQL returns a preparestatement object pstmt = Conn. preparestatement (sqlstring); // input the pstmt parameter. setstring (1, user. getUserName (); pstmt. setstring (2, user. getuserpwd (); // execute the SQL statement and return the result set rs = pstmt.exe cutequery (); // cyclically traverse the result set if (RS. next () {userinfo myuser = new userinfo (); myuser. setusername (RS. getstring (2); myuser. setuserpwd (RS. getstring (3); list. add (myuser) ;}} catch (exception ex) {ex. printstacktrace ();} finally {super. closeconnction () ;}return list ;}}

8. Create a com. mybbs. service package and create a userinfoservice. Java class under the package to determine user login. type the following code:

Import COM. mybbs. pojo. userinfo; import COM. mybbs. dao. userinfodao; import Java. util. list; import Java. util. iterator; public class userinfoservice {// Dao private userinfodao = userinfodao that obtains user information for operations. getuserinfodao (); // verify the user logon information. If the user name and password are correct, true public Boolean userlogin (userinfo user) {Boolean islogin = false; // query the result set list = userinfodao from the database based on the input user object. getperson (User); iterator it = List. iterator (); // If the set contains data, you can log on to If (it. hasnext () {islogin = true;} return islogin ;}}

9. Create a com. mybbs. actionform package and create a loginactionform. Java class under the package. type the following code:

Package COM. mybbs. actionform; import javax. servlet. HTTP. httpservletrequest; import Org. apache. struts. action. actionerrors; import Org. apache. struts. action. actionform; import Org. apache. struts. action. actionmapping; public class loginactionform extends actionform {// User Password private string password; // user name private string name; // Verification Code private string rand; Public String getrand () {return rand ;} public void setrand (string rand) {This. rand = rand;} Public String GetPassword () {return password;} public void setpassword (string password) {This. password = password;} Public String getname () {return name;} public void setname (string name) {This. name = Name;} // actioform-specific verification method public actionerrors validate (actionmapping mapping, httpservletrequest request) {return NULL ;} // actionform-specific reset method public void reset (actionmapping mapping, httpservletrequest request ){}}

10. Create a com. mybbs. action package and create a loginaction. Java class under the package. type the following code:

Package COM. mybbs. action; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import Org. apache. struts. action. action; import Org. apache. struts. action. actionform; import Org. apache. struts. action. actionforward; import Org. apache. struts. action. actionmapping; import COM. mybbs. actionform. loginactionform; import COM. mybbs. pojo. userinfo; import COM. mybbs. service. use Rinfoservice; import javax. servlet. HTTP. httpsession; public class loginaction extends action {string scriptstr = NULL; Public actionforward execute (actionmapping mapping, actionform form, httpservletrequest request, httpservletresponse response) {// obtain the loginactionform object loginactionform = (loginactionform) form; // obtain the session object httpsession session = request. getsession (); // determines whether the verification code is entered correctly. F (! Session. getattribute ("RAND "). tostring (). equals (loginactionform. getrand () {// page Jump Return Mapping. findforward ("self");} // instantiate the user bean userinfo user = new userinfo (); // obtain the user name entered by the user. setusername (loginactionform. getname (); // obtain the user's password. setuserpwd (loginactionform. getPassword (); // declare the business logic object userinfoservice = new userinfoservice (); // If the username and password are entered correctly, log on successfully if (userinfoservice. userlogin (User) {Return Mapping. findforward ("success");} // if an error is prompted, else {Return Mapping. findforward ("error ");}}}

11. Open the WEB-INF, struts-config.xml file, replace the content in <Struts-config> </Struts-config>:

<struts-config>   <form-beans >       <form-bean name="LoginActionForm"            type="com.mybbs.actionform.LoginActionform" />       </form-beans>   <action-mappings >    <action       input="/jsp/login.jsp" attribute="LoginActionForm"       name="LoginActionForm" path="/LoginAction"       scope="request" type="com.mybbs.action.LoginAction" >             <forward name="self" path="/jsp/login.jsp"></forward>             <forward name="success" path="/jsp/success.jsp"></forward>             <forward name="error" path="/jsp/error.jsp"></forward>      </action>    </action-mappings> </struts-config> 

Deploy and run the program. Enter http: // localhost: 8080/mybbs/JSP/login. jsp in the address bar to open the logon page.
If the opened interface is not a login interface, but a text prompt: This is a JSP page. Remember to delete the index. jsp file under webroot.
If the login. jsp opened in the browser is 404, remember to check whether your address is correct. My computer requires localhost to be my host name. If it is replaced, it will be 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.