Struts simple instance

xiaoxiao2021-03-06  15

Contains content:

Table authentication using regular expressions

Message file binding

Error message display

Web.xml

action org.apache.struts.Action.Ame> Config /web-inf/struts-config.xml 2 action *. do / Web-inf / struts-bean.tld /web-inf/struts-bean.tld / web -Inf / struts-html.tld /web-inf/struts-html.tld / web- INF / STRUTS-LOGIC.TLD /web-inf/struts-logic.tld

Struts-config.xml

< / action-mapings> // message file Bind Hellobean.java

Package test;

Import org.apache.struts.Apache.struts.util. *; import javax.servlet.http. *; import java.util.regex. *;

public class HelloBean extends ActionForm {private String word; public void setWord (String word) {this.word = word;} public String getWord () {return this.word;} public void reset (ActionMapping mapping, HttpServletRequest request) {this. Word = null;} private bolean match (string str) {pattern p = pattern.compile ("[^ 0-9] "); // Use regular expressions to verify Matcher M = P.matcher (STR); return m.matches ();} public ActionErrors validate (ActionMapping mapping, HttpServletRequest request) {ActionErrors errors = new ActionErrors (); if (word == null || match (word)!) {errors.add ( "word", New ActionMessage ("Error.Key"));} Return Errors;}}

HelloAction.java

Package test;

Import org.apache.struts.action. *; import javax.servlet.http. *; import javax.servlet. *; import org.apache.struts.UTIL. *;

public class HelloAction extends Action {public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {MessageResources mess = getResources (request); String wordKey = mess.getMessage ( "word.key"); String helloKey = Mess.getMessage ("Hello.Key"); System.Out.println (WordKey "," HelloKey); String Word = Request.GetParameter (WordKey); System.Out.println (Word); Hellobean MyForm = (Hellobean ) form; myform.SetWord (Word); MyForm.SetWord (HelloKey ", MyForm.GetWord ()); return maping.findforward (" Sayhello ");}}

Hello.jsp

<% @ Page ContentType = "Text / HTML; Charset = GBK"%> <% @ 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 "%>

Error.jsp

<% @ Page ContentType = "Text / HTML; Charset = GBK"%> <% @ Taglib URI = "/ Web-INF / STRUTS-HTML.TLD" prefix = "html"%> // Error message display /Web-inf/classes/test/application.properties

Word.key = wordhello.key = helloaaaa.key = this bean is present.bbb.key = this bean isn't present.error.key = raise a error, please check!

result:

http: // localhost: 2000 / test3 / helloaction.do? word = bitan

This bean is present. Hello, Bitan

Http: // localhost: 2000 / test3 / helloaction.do? word = b123n

Raise a Error, please check!

转载请注明原文地址:https://www.9cbs.com/read-45748.html

New Post(0)