我正在尝试获取用户区域设置语言,当他访问我的网站并以该语言显示网站时。如何检测用户区域设置并附加到浏览器网址,就像我们从印度访问http://www.microsoft.com时那样它会自动显示网址为http://www.microsoft.com/en-in/default.aspx所以我的网站名称为http://www.myweb.com,那么如何在网页加载时将网址设为http://www.myweb.com?language=en ..? 因为我在我的web.xml中将home.jsp设置为欢迎文件所以当我从netbeans运行我的web应用程序时它显示localhost:8080 / Myweb / so如果我想发送页面,用户如何知道该页面是英文或荷兰语链接到我在荷兰的朋友?总之,我想在用户打开我的网站时显示URL中的语言参数,如http://www.myweb.com?language=nl,即自动检测用户区域设置并将该语言设置为参数
这是我的代码......
<%@page import="java.util.Locale"%>
<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String userLocale = request.getHeader("Accept-Language");
//out.println(userLocale);
Locale locale = request.getLocale();
String userlanguage = locale.getDisplayLanguage();
out.println("LANG :" + locale.getLanguage());
%>
<c:set var="language" value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale.language}" scope="session" />
<fmt:setLocale value="${language}" />
// here depending on user locale i am setting basename is this good approach?
<c:choose>
<c:when test="${language == 'nl'}">
<fmt:setBundle basename="com.example.i18n.text_nl" />
</c:when>
<c:otherwise>
<fmt:setBundle basename="com.example.i18n.text" />
</c:otherwise>
</c:choose>
<html lang="${language}">
<nav>
<ul>
<li>
<a href="<c:url value='Aboutus.jsp?language=${language}'/>"
title="<fmt:message key="nav.label.aboutus" />">
<fmt:message key="nav.label.aboutus" />
</a>
</li>
<li class="shad">
<a href="<c:url value='Contactus.jsp?language=${language}'/>" // and also is this good way to append language as parameter to url here ?
title="<fmt:message key="nav.label.contactus" />">
<fmt:message key="nav.label.contactus" />
</a>
</li>
</ul>
</nav>
</html>
答案 0 :(得分:3)
编写一个HttpFilter来处理它并将其映射到web.xml中。
if(request.getParameter("language")==null) {
String userLocale = request.getHeader("Accept-Language");
Locale locale = request.getLocale();
if(req.getRequestUrl().contains("?")) {
response.sendRedirect(req.getRequestUrl()+"&language="_locale.getLanguage());
} else {
response.sendRedirect(req.getRequestUrl()+"?language="_locale.getLanguage());
}
}
答案 1 :(得分:1)
没有为我工作(也许现在已经过时了?)
这是我的更新版本:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (request.getParameter("language") == null) {
Locale locale = request.getLocale();
String qs = req.getQueryString();
if (qs == null || qs.isEmpty()) {
res.sendRedirect(req.getRequestURI() + "?language=" + locale.getLanguage());
} else {
res.sendRedirect(req.getRequestURI() + "?" + qs + "&language=" + locale.getLanguage());
}
}
}
chain.doFilter(request, response);
}