Example of getting started with SSH

Source: Internet
Author: User

Because the company uses SSH for projects, to understand how SSH is built and how it works, we have built one by ourselves.

Build a simple struts2 + spring + hibernate environment using the minimal jar package as much as possible. I hope that anyone like me can understand it. If you have used similar MVC patterns such as Microsoft MVC, it is much easier to understand.

First, I am using myeclipse 9 + Tomcat 6 (it is said that Tomcat and struts are incompatible, but I did not meet it, I do not know if it is true ).

I downloaded the struts2.3.15.1 jar package (including spring) on the official website:Http://struts.apache.org/download.cgi#struts23151

Hibernate has been released to hibernate4 on the official website and is worried about incompatibility. Therefore, go to Sina to share and download hibernate3.3.2,Http://ishare.iask.sina.com.cn/f/33704027.html

After the download is complete, start building.

Step 1: Use struts2.

Import the required struts package:

Strust-core-xxx.jar xwork-core-xxx.jar commons-io-xxx.jar

Commons-fileupload-xxx.jar commons-lang-xxx.jar commons-logging-xxx.jar

Freemarker-xxx.jar javassist-xxx.GA.jar ognl-xxx.jar

There are many ways to import packages. You can add extenal jars in build path. You can create a custom librariy to add these packages and then import the library. I copied these packages to the project's webroot-> WEB-INF-> Lib in the simplest way, so that the project will automatically import the package to referenced libraries.

Compile the package and run Tomcat smoothly. Then we can test struts. Create a new struts. xml file in the src directory. The content is as follows:

<? 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> <! -- Add spring when needed --> <! -- <Constant name = "struts. objectfactory "value =" Spring "/> --> <package name =" default "extends =" struts-Default "> <action name =" login "class =" com. struts2test. action. loginaction "method =" execute "> <result name = 'success'>/index. JSP </result> <result name = 'login'>/login. JSP </result> </Action> </package> </struts>

As shown above, the "default" package is a Web request to struts. It will first enter here to find our action path.

To support struts, we also need to modify web. xml under the webroot-> WEB-INF, the content is as follows:

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"  xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <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.jsp</welcome-file>   </welcome-file-list></web-app>

The added filter and filter-mapping are filters. All client Web requests first enter this web. XML is the most basic configuration file for web projects. Other files are in the past of this XML navigation. The traditional method is to directly use servlet to directly navigate to the method, so that there are few project layers, and everyone should know that it is more difficult to develop at a lower level for easy maintenance, more layers of development will be troublesome, but maintenance is much easier. Struts actually encapsulates the servlet method.

Create a com. struts2test. action package and put all the action methods. Create a class under this package. For example, name it loginaction in struts. xml. The content is as follows:

Package com. struts2test. Action; import com. opensymphony. xwork2.actionsupport; public class loginaction extends actionsupport {// This class inherits the actionsupport class. In this way, you can directly use variables such as success, // login, and methods such as private string username; private string password; Public String GetUserName () {return username ;} public void setusername (string username) {This. username = username;} Public String GetPassword () {return password;} public void setpassword (string password) {This. password = password;} @ override Public String execute () throws exception {If (username. equals ("admin") & password. equals ("123") // return success; otherwise, return login return success; return login ;}}

As shown above, we need to set a setter and getter for username and password. In this way, the page values can be received and assigned to them,It can be inferred that the page value is also injected.

With this method, we can determine to enter the index homepage Based on the username and password submitted by login. jsp!

The content on the index homepage is as simple as login. jsp. The content is as follows:

<% @ Page Language = "Java" Import = "Java. util. *" 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>

After passing basic HTML values, you should know that the name attribute of input is used for passing values. Therefore, it should be the same as the username and password name of the above loginaction method. Otherwise, the passing of values will fail.

Everything is ready and released to Tomcat for compilation and running. You can access our website through http: // localhost: 8080/project name/login. jsp. Enter admin/123 to enter index. jsp!

Step 2: Use Spring Based on struts.

Package required for importing spring:

Strus2t-spring-plugin-xxx.jar spring-core-xxx.jar spring-context-xxx.jar

Spring-bean-xxx.jar spring-web-xxx.jar spring-asm-xxx.jar spring-expression-xxx.jar

Spring is mainly used for dependency injection and aspect programming. Here we use spring to inject username and password to loginaction, so that no matter what input on the interface, the program uses the username and password I injected.

To make struts support spring (when struts finds action and injects bean with spring), add the following statement in struts. xml:

<constant name="struts.objectFactory" value="spring" />

You have already written it. Just cancel the annotation.

Create applicationcontext. XML in the src directory. The content is as follows:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">        <bean id="LoginAction" class="com.struts2test.action.LoginAction">        <property name="username" value="admin">        </property>        <property name="password" value="123">        </property>    </bean></beans>

In this case, restart tomcat to start. We can jump to index. jsp no matter what we enter in login. jsp. Because spring has injected a fixed value for us.

Here we can see that we need to configure as many beans as we use here, which is actually troublesome, similar to the traditional servlet configuration. In fact, we can use a spring automatically scan bean function, we imported above the spring-context-xxx.jar with this function, in applicationcontext. XML to add:

<Context: annotation-config/> <! -- Let spring automatically scan the annotation @ controller, @ service, @ resposity, @ comopnent --> <context: component-scan base-package = "com. struts2test"/>

In this way, we only need to identify @ respository on the class, and the project will scan to recognize it as bean, just like the explicit handwriting. To call this bean, use @ resource to identify the variable. In this way, you can not write setter or getter, which is convenient and the code is concise. You can search for the specific usage on the Internet. I haven't used many other functions, so I won't talk about them more.

Step 3: Use hibernate.

If you have been familiar with Microsoft MVC, you should know that it is similar to LINQ. After all, many Microsoft products are similar to others, but they are encapsulated and easy to use. There is a good official document using hibernate, which has a Chinese version. I also refer to the document to write the hibernate configuration. We suggest you read the document:Http://docs.jboss.org/hibernate/core/3.5/reference/zh-CN/html_single/

Before using hibernate, we also need to use the database to connect to the jar package and download the jar package as you want to use it. I used MySQL and downloaded a mysql-connetor-java-5.1.12.jar online.

Then, import the hibernate jar package:

Hibernate3.jar commons-collections-xxx.jar cglib-xxx.jar jta-xxx.jar

Antlr-xxx.jar dom4j-xxx.jar slf4j-api-xxx.jar slf4j-log4j12-xxx.jar

Create COM. struts2test. in the VO package, place the corresponding class and ing file of the database, and create a new users class as the Login User class, which includes the username and password attributes. Remember to give them setter and getter.

After OK, we need to create a database ing for this class. We must tell the database which table corresponding to the class and which attribute corresponds to which field. Create a new users. HBM. xml file under the com. struts2test. VO package. The content is as follows:

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

The username shown above is <ID>, indicating that username is the primary key. When creating a table in our database, you must set the username field of the users table as the primary key. It seems that no primary key is acceptable-of course, it is a good habit to create a primary key for each table, even if it is not used.

Finally, create a new hibernate database connection configuration file hibernate. cfg. XML in the src directory. The content is as follows:

<? XML version = '1. 0' encoding = 'utf-8'?> <! Doctype hibernate-configuration public "-// hibernate/hibernate configuration DTD 3.0 // en" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 

There are a lot of property parameters here. You can refer to the document or search for them online. The most important thing is the <Mapping Resource> line. The Hibernate ing files should all be written here, that is, the tables used should all be mapping here.

This completes the database ing.

However, for our login, we still need to select the database ing data to check whether the value passed on the page corresponds to the database ing data. Create a com. struts2test. Dao package and create a userdao class under the package. The content is as follows:

package com.struts2test.dao;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import com.struts2test.vo.Users;public class UserDao {    public boolean Login(Users login){        Configuration cfg = new Configuration();        SessionFactory factory = cfg.configure().buildSessionFactory();        Session session = factory.openSession();        Query q = session.createQuery("from Users where 1 = 1 and username = ‘" + login.getUsername() + "‘ and password = ‘" + login.getPassword() + "‘");        User user = (User)q.uniqueResult();        if(user != null)            return true;        return false;    }}

The Hibernate query method is roughly as shown above: configuration-> sessionfactory-> session-> query. It is a fixed method. Refer to the hibernate document.

In the preceding SQL-like query statement, the users from users does not refer to the database table, but the users class. In the past, I made an error defining the class name as a user, but users in the database, the ing is correct, but it cannot be queried. The main reason is that after hibernate completes the ing, the query will face the object.

We use this method, so we need to modify the loginaction judgment method. The loginaction method needs to call the login method of userdao to determine. This userdao can be new or spring injected, because I just learned spring and tried to use spring for injection. Successful!

 

The directory tree of the entire project is included:

 

As mentioned above, we have imported many packages. In fact, I do not know whether the imported packages are necessary. They are recommended on the Internet. In fact there is a relatively stupid package method, we first import the core package in the empty project, such as struts-core-2.3.15.1.jar, spring-core.jar, hibernate3.jar, directly compiled will prompt error, we can guess which package is missing after reading the error. I read a lot of online statements when I set up it. It is not necessarily the package I need. For example, many users say that log4j is required to provide the log reading and writing function. The log function is not used in the project I set up, and compilation is successful without adding this package.

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.