使用jsp标签和java资源管理实现jsp支持多语言

  1.编写一个Serverlet并设置服务器启动是初始化该Servlet,并在初始化方法中实现对java的资源加载;

DispatcherServlet.java

1 package mypack; java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; javax.servlet.RequestDispatcher; 8 import javax.servlet.ServletConfig; 9 import javax.servlet.ServletContext;10 import javax.servlet.ServletException;11 import javax.servlet.http.HttpServlet;12 import javax.servlet.http.HttpServletRequest;13 import javax.servlet.http.HttpServletResponse;DispatcherServlet extends HttpServlet{String target=”/hello.jsp”; init(ServletConfig config)19throws ServletException {20System.out.println(“服务器启动时设置初始化servlet并且加载java资源”);21super.init(config);22try {23Properties ps=new Properties();24Properties ps_ch=new Properties();25ServletContext cxt=config.getServletContext();26InputStream in=cxt.getResourceAsStream(“/WEB-INF/messageresource.properties”);27 ps.load(in);28InputStream in_ch=cxt.getResourceAsStream(“/WEB-INF/messageresource_ch.properties”);29 ps_ch.load(in_ch);30cxt.setAttribute(“ps”,ps);31cxt.setAttribute(“ps_ch”,ps_ch);32} catch (IOException e) {e.printStackTrace();35 }36 }3738 @Override doDelete(HttpServletRequest req, HttpServletResponse resp)40throws ServletException, IOException {.doDelete(req, resp);43 }44 45 @Override doGet(HttpServletRequest req, HttpServletResponse resp)47throws ServletException, IOException {.doGet(req, resp);50this.doPost(req, resp);51 }52 53 @Override doPost(HttpServletRequest request, HttpServletResponse resp)55throws ServletException, IOException {56 57String username = request.getParameter(“username”);String password = request.getParameter(“password”);60 61request.setAttribute(“USER”, username);62request.setAttribute(“PASSWORD”, password);63ServletContext context = getServletContext();64 65System.out.println(“Redirecting to ” + target);66RequestDispatcher dispatcher =67 context.getRequestDispatcher(target);68 dispatcher.forward(request, resp); } destroy() {72 }73 74 }

View Code

  2.资源的具体内容

messageresource.properties

1 hello.title = helloapp2 hello.hello = Hello3 login.title = helloapp4 login.user = User Name5 login.password = Password6 login.submit =Submit

View Code

messageresource_ch.properties

1 hello.title = helloappµÄhelloÒ³Ãæ2 hello.hello = ÄãºÃ3 login.title = helloappµÄµÇ¼ҳÃæ4 login.user = Óû§Ãû5 login.password = ¿ÚÁî6 login.submit =\u00CC\u00E1\u00BD\u00BB

View Code

  3.主页为语言选择页面

index.html

没有什么可凭仗,只有他的好身体,没有地方可去,只想到处流浪。

使用jsp标签和java资源管理实现jsp支持多语言

相关文章:

你感兴趣的文章:

标签云: