Struts2 supports a stream type of result, which can directly respond to binary and text in the client browser,
We can generate a text response in the action, and then dynamically load the response on the client page.
Let's look at the example:
Public class loginaction {private string user; private string pass; private inputstream; Public inputstream getinput () {return inputstream;} Public String getuser () {return user ;} public void setuser (string user) {This. user = user;} Public String getpass () {return pass;} public void setpass (string pass) {This. pass = pass;} Public String login () throws unsupportedencodingexception {inputstream = u Ser. Equals ("zhangsan") & pass. Equals ("123 ")? New bytearrayinputstream ("congratulations, logon successful ". getbytes ("UTF-8"): New bytearrayinputstream ("Logon Failed ". getbytes ("UTF-8"); Return "success ";}}
The core of this action is the getinput method. The binary stream returned by this action will be directly output to the viewer. This will be accomplished using stream-type results. Note: The getinput method name can be changed as needed, but it must be this type of get + "XXX" (it should be used by the reflection mechanism). This "XXX" must correspond to the value of param as inputname !!!!
Next, let's look at the Struts. xml configuration:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN""http://struts.apache.org/dtds/struts-2.1.7.dtd"><struts> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <package name="user" extends="struts-default"><action name="loginAction" class="com.sinosoft.epicc.action.LoginAction" ><result name="success" type="stream"><param name="contentType">text/html</param><param name="inputName">input</param></result></action></package></struts>
Then use the Ajax call encapsulated by jquery:
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" C "uri =" http://java.sun.com/jsp/jstl/core "%> <% @ taglib prefix =" FN "uri =" http://java.sun.com/jsp/jstl/functions "%> <% @ taglib prefix = "FMT" uri = "http://java.sun.com/jsp/jstl/fmt" %> <% string Path = request. getcontextpath (); string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverpor T () + path + "/"; %> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <HTML>
The running result is as follows:
Relatively simple ~~~~ I also used a method returned by Ajax, Which is direct response. Write, which is also commonly used.