How to achieve struts2 and spring integration

Source: Internet
Author: User

The first step is to create the spring configuration file applicationcontext.xml. This configuration is responsible for importing the configuration that handles business beans and persisted beans, and adds support for action Bean management for the controller layer. This file is typically placed under the Web-inf folder, as follows:

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"Xmlns:context="Http://www.springframework.org/schema/context"Xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://www.springframework.org/schema/beanshttp//www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/contexthttp//www.springframework.org/schema/context/spring-context.xsd "><!--import Spring configuration--<import resource="Spring-service.xml"/> <import resource="Spring-dao.xml"/> <!--Open the component Scan controller to manage the Action object-<context:component-scanBase-package="com.entor.rams.actions"> <!--only @controller to <context:include-filter type="annotation"expression="Org.springframework.stereotype.Controller"/> </context:component-scan></beans>

The second step is to configure the core configuration of the Struts2 Struts.xml, the action bean that handles the controller layer and the front-end control function, which declares that the action object is administered to the spring container.

<?xml version="1.0"encoding="UTF-8"? ><!DOCTYPE Struts public"-//apache software foundation//dtd Struts Configuration 2.5//en""HTTP://STRUTS.APACHE.ORG/DTDS/STRUTS-2.5.DTD"><struts> <!--Constants--<!--development mode open-<constant name="Struts.devmode"Value="true"/> <!--declares the management of the action object to the spring container--<constant name="struts.objectfactory"Value="Spring"></constant> <!--resulting page path by action limit--<constant name="Struts.convention.result.path"Value="/web-inf/jsps/"></constant> <!--action Configuration: Package namespace action, result, and <!--<package Name="zijiding"extends="Struts-default" namespace="/">name indicates the requested URL:/rams/user_*class represents the processing of the requested action object method, which represents the process name of the request, {1} is associated with the first occurrence of a wildcard character in name<action name="user_*" class="useraction"Method="{1}">Result indicates the outcome of the response, which responds to the Index.jsp page under the WebApp root directory<result name="Success">/WEB-INF/jsps/result.jsp</result> </action> <!--</package>--></struts&gt ;

The third step configures the Struts-spring integration Settings Web. XML, which is primarily

1. Configure the Web listener Contextloaderlistener to listen to the spring context object;

2. Initialize the spring container and load the spring core configuration file;

3. Configure the struts filter to take over all requests. As shown below:

<?xml version="1.0"encoding="UTF-8"? ><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://java.sun.com/xml/ns/javaee"xsi:schemalocation="Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"ID="webapp_id"version="3.0"> <display-name>RAMSMY</display-name> <!--home--<welcome-file-list> <welco        Me-file>/index</welcome-file> </welcome-file-list> <!--web Monitoring--<listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!--Initialize spring container, load Spring core configuration file--<context-param> <param-name& Gt;contextconfiglocation</param-name> <param-value>/web-inf/configs/applicationcontext.xml</ Param-value> </context-param> <!--Configure the Struts filter to take over all requests--<!--load the STRUTS.XM under the Classpath path by default L-<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.strutsprepareandexecutefilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pat Tern>/*</url-pattern> </filter-mapping></web-app>

When the primary profile is complete, create a new User.java class that provides the Get set method.

Then write the DAO Layer and service layer. Create a new action class Useraction.java, as follows:

Package Com.entor.rams.actions;import Java.io.serializable;import javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.httpsession;import Org.apache.struts2.servletactioncontext;import Org.apache.struts2.convention.annotation.action;import Org.apache.struts2.convention.annotation.result;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Com.entor.rams.domain.user;import Com.entor.rams.service.userservice;import Com.entor.rams.utils.common.ramsconstants;import Com.opensymphony.xwork2.actionsupport;import Com.opensymphony.xwork2.ModelDriven; @Controller Public classUseraction extends Actionsupport implements Modeldriven<user>, serializable{Private StaticFinalLongSerialversionuid =483187020462134967L; @AutowiredPrivateUserService UserService; Privateuser User;  PublicUser GetUser () {returnuser; } @Override PublicUser Getmodel () {if(User = =NULL)             This. user =NewUser (); returnuser; }    /** * Processing Request Home * @return*/@Action (Value="Index", ClassName ="useraction", results =//@Result (name ="Success", location ="index.jsp"))     PublicString Index () {returnSUCCESS; }        /** * Processing Login Request * @return*/@Action (Value="User_login", classname="useraction", results={@Result (name="Success", location ="result.jsp"),//@Result (name ="fail", location ="index.jsp")})     PublicString Login () {//Take out requests and session objectsHttpServletRequest request =servletactioncontext.getrequest (); HttpSession Session= Request.getsession (false); User u= Userservice.fingbyloginnameandpassword ( This. User.getloginname (), This. User.getpassword ()); //User Login Successful        if(U! =NULL){             This. user =u;            Session.setattribute (Ramsconstants.user_session, USER); returnSUCCESS; }        //User Login failed        Else{String errormsg="incorrect user name or password"; Request.setattribute ("errormsg", errormsg); returnRamsconstants.fail; }    }}

The final test results are as follows:

How to achieve struts2 and spring integration

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.