messy code about java web application - java

Recently, I use idea with tomcat to start my first java web application (Servlet+JSP+MySql), After I finish all the code part, I try to query some data after I add them in the application, when I use English, it's fine, when I use Chinese, there are messy code in the console, I have done everything to change the
encoding become "utf-8", but I can't solve it, help me, pleaseļ¼
public String query(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
Product product = CommonUtils.toBean(request.getParameterMap(), Product.class);
product = encoding(product);
int pageCode = getPageCode(request);
int pageRecord = 10;
PageBean<Product> pageBean = productService.query(product, pageCode, pageRecord);
pageBean.setUrl(getUrl(request));
System.out.println(pageBean.getUrl());
request.setAttribute("pageBean",pageBean);
return "/content.jsp";
}
private Product encoding(Product product) throws UnsupportedEncodingException{
String name = product.getName();
if(name != null && name.trim().isEmpty()){
name = new String(name.getBytes("ISO-8859-1"),"utf-8");
product.setName(name);
}
return product;
}
the result when I was query is this:
/ProductServlet?method=query&barcode=&name=%E5%B8%85&units=&purchasePrice=&salePrice=&inventory=&%E6%90%9C%E7%B4%A2=%E6%8F%90%E4%BA%A4
the name is Chinese, but it becomes messy code

First: name = new String(name.getBytes("ISO-8859-1"),"utf-8"); should not ever be done; then something else went wrong prior to that moment.
There are the following points where an encoding/charset can be set:
In the html <form accept-encoding="UTF-8"...> to indicate that the generated form field values should not be url-encoded as for instance %E5%B8%85.
On the request.setEncoding("UTF-8"); to tell that the request is in that encoding.
On the response.setEncoding("UTF-8"); for outgoing text.
There are many technologies that can be applied, and the settings above in reality can be done in numerous ways, as application settins, or in your case in the JSP as <%#page pageEncoding="UTF-8" %>.
If you are using a /WEB-INF/web.xml setting the pageEncoding for all JSPs would be:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>

Related

Accessing SpringMVC model key value inside java code

#RequestMapping(value = "",method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", doctorDetails);
return "doctorchannelling/index";
}
I have added this controller in my SpringMVC project now I need to access the element doctorDetails in a java code which is inside a jsp
how can I call this doctorDetails inside <% %> Mark
Something like below
<% String message = (String)request.getAttribute("message"); %>
or
<%
String message = ${message};
%>
You can simply use the EL to print them as,
${message}
If it is a String set in the request. For Model objects use ,
${message.fieldName}
See Also
How to avoid Java code in JSP files?
printing servlet request attributes with expression language

Tomcat response mix-up

Have been seeing a very unique situation. Need some input.
Background: We have tomcat servers on ec2 instances with ELB. Our application is a spring application which does not use sessions cause we didn't want the load balancer to track sessions. We use cookies to identify the user. We use Memcache to store some basic session information. For the most part everything works great.
Problem: In some remote cases 0.01% of the time (we analyzed) the response is getting mixed up between the users. And the users are usually coming from the same clientIP. We know this because our application is being used extensively by schools. The client cookie and the cookie we read in the servlet matches. We are positive our application is not looking up the wrong info in the DB. But the response (the view) that is getting rendered is for another user. We know both users are logged in at the same time.
Is this something Tomcat related? Or Network related?
Controller Code:
#RequestMapping("/kids")
public ModelAndView kids(HttpServletRequest request, HttpServletResponse response) {
StudentUserSession studentUserSession = BaseController.getStudentUserSession(request);
if(studentUserSession != null) {
ModelAndView mv = new ModelAndView("kids");
mv.addObject("studentUserSession", studentUserSession);
return mv;
} else {
return new ModelAndView("redirect:/signin");
}
}
JSP Code:
var acookie = readCookie("sp_utkn");
var studentId = ${studentUserSession.studentId};
$.getJSON("/getStudentProfile", function(data){
var sId = -1;
$.each(data, function (key, value) {
if(key == 'studentId'){
sId = value;
}
});
dojo.xhrGet({
url:"/logStudentEvent?cookie=" + acookie+"&stuId="+studentId+"&aId="+sId+"&ref="+otherInfo.join(','),
});
});
The JSON Get Call is getting the same object . aId matches with the cookie but studentId doesn't. The other data on the page are also for another user. But the cookies are consistent and accurate.

Handling non-english URL with Spring and App Engine Task Queue

I have this problem where I need to queue a page link with TaskQueue:
Queue queue = QueueFactory.getDefaultQueue();
for (String href : hrefs){
href = baseUrl + href;
pageLinks = pageLinks + "\n" + href;
queue.add(TaskOptions.Builder
.withUrl("/crawler")
.param("url", href));
l("Added to queue url=["+href+"]");
}
The problem here is that, I think the URL that gets passed into the queue contains ?'s for Arabic characters. As it keeps on rescheduling.
The String pageLinks however is outputed in the browser through Spring MVC, and I can properly see the Arabic character being displayed. So I'm pretty the links are ok.
If I copy one of the links output on the browser, and paste it to the browser URL it works fine. So I'm pretty sure that the reason that the queue keeps on recheduling because it gets the wrong URL.
What could I be missing here? Do I need to convert the String href before passing it into the queue?
The crawl service looks like this:
#RequestMapping(method = RequestMethod.GET, value = "/crawl",
produces = "application/json; charset=iso-8859-6")
public #ResponseBody String crawl(HttpServletRequest req, HttpServletResponse res,
#RequestParam(value="url", required = false) String url) {
l("Processs url:" + url);
}
Also do I need to convert the #QueryParam String url here to Arabic or not?
You must Url-encode the parameters. See this question: Java URL encoding of query string parameters

How do I send data from Struts action to javascript?

I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.
This is the list I'm trying to send/access:
List<MarkerClass> markers;
MarkerClass is defined acoprding to belove:
final class MarkerClass
{
public Integer objectId;
public String street;
public String streetNumber;
public String zip;
public String city;
public Integer statusId;
public Float lattitude;
public Float longitude;
}
The action also includes a getter for markers:
public List<MarkerClass> getMarkers()
{
return markers;
}
In my jsp-file I have tried doing this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ "${markers[i].street}";
}
}
The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass#37a4, se.fubar.test.MarkerClass#9ad97c]"
I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.
You cannot just use a struts variable in a javascript function and expect it to work. Remember that the ${...} stuff gets processed before the HTML for the page is sent to the browser. By the time the javascript is rendered at the browser, you are only left with the textual representations. What you will need to do is something like (check the syntax, I haven't used this stuff i a while):
function initialize() {
var title = "";
<c:foreach var="marker" list="${markers}">
title = title + "${marker.street}";
</c:foreach>
}
Something along those lines anyway... Basically the Javascript seen by your browser will look like
function initialize() {
var title = "";
title = title + "Street1";
title = title + "Street2";
title = title + "Street3";
title = title + "Street4";
}
I hope that makes sense and is related to what you were asking.
By the way, there are usually better ways of accomplishing this functionality that building dynamic js etc. Probably there are built in Struts 2 components that you can use?
you would have to set that variable in request or in session and then access it using a <c:out jsp tag like so
var myVar= '<c:out value="${requestScope.myVar}"/>';
then use the var inside your js.
In case you set an object in request or session you have to use the get method to access the value of an attribute then use it like so:
var myVar= '<c:out value="${requestScope.myObj.attribute}"/>';
(assuming you getter method is getAttribute)
it is not possible to access data in session or request directly from js
hope this helps
You could convert the object to json on the server (see http://www.json.org/java/index.html ) and then call eval() on the string to get a javascript representation of your object.
you can try accessing it something like this.
but you have to use a loop to fetch each object from the list place it on the value stack and than fetch each object of it.else you can ask ognl to do it for you.something like
<script type="text/javascript">
function initialize()
{
var titel = "";
for(var i, "${markers}")
{
titel = titel+ <s:property value="%{markers.get(i).street}">;
}
}
just try it since OGNL has capacity to access the object on the value stack

Java Webservice URL in JSF

I created a JSF application which also offers some Webservices. The webservices are created via annotations.
Now I want to create a webserviceInfo.xhtml Page , where I get all the needed webservice Information.
When I go to the address http://our.server.com/application/OurWebserviceName, I get all the information needed to access the webservice (this info page is generated automatically by Glassfish ).
To include this page, I did the following in the webserviceInfo.xhtml:
<iframe scrolling="automatic" width="971" height="1000" src="#{myBean.generateUrlToWebservice()}/OurWebserviceName"/>
Where:
public String generateUrlToWebservice(){
FacesContext fc = FacesContext.getCurrentInstance();
String servername = fc.getExternalContext().getRequestServerName();
String port = String.valueOf(fc.getExternalContext().getRequestServerPort());
String appname = fc.getExternalContext().getRequestContextPath();
return "http://"+servername+":"+port+appname;
}
Is there a more elegant solution to this?
BR, Rene
Use a page-relative URL.
<iframe src="OurWebserviceName"></iframe>
Or make use of <base> tag with little help of JSTL functions taglib.
<html xmlns:fn="http://java.sun.com/jsp/jstl/functions">
...
<base href="#{fn:replace(request.requestURL, request.requestURI, '')}#{request.contextPath}"></base>
This way any URL which doesn't start with scheme or / is always relative to this URL.
Or if you really need to do it in JSF the following gives less headache with scheme and port.
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
return request.getRequestURL().toString().replace(request.getRequestURI, "") + request.getContextPath();
Better will be if you gets all parameters dynamically like protocol (http,https..) and pages (after app name)
public String generateUrlToWebservice(){
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext exContext = fc.getExternalContext();
String servername = exContext.getRequestServerName();
String port = String.valueOf(exContext.getRequestServerPort());
String appname = exContext.getRequestContextPath();
String protocol = exContext.getRequestScheme();
String pagePath = exContext.getInitParameter("pagePath"); //read it from web.xml
return protocol +"://"+servername+":"+port+appname+pagePath;
}

Categories

Resources