Transform jsp to java code - java

I need java code for this jsp line code.
I know how to make it for scope "page" or "application" but i really dont know how it works with "session"
<jsp:useBean id=”pera” class=”beans.User” scope=”sesion”>

This is Solution.
beans.User user = null;
synchronized (application) {
user = (beans.User) _jspx_page_context.getAttribute("user",
PageContext.APPLICATION_SCOPE);
if (user == null){
user = new beans.User();
_jspx_page_context.setAttribute("user", user,
PageContext.APPLICATION_SCOPE);
}
}

Related

JSP - Separating HTML forms in JSP Functions

I have my JSP that controls the frame behavior of my page as the following:
<%
print_header();
String especialidade = request.getParameter("especialidade");
String medico = request.getParameter("medico");
String paciente = request.getParameter("paciente");
String data_consulta = request.getParameter("data_consulta");
String convenio = request.getParameter("convenio");
if (especialidade == null) {
print_especialidade_form();
} else if(paciente == null) {
print_agendamento_form();
}
print_footer();
%>
I have the definition of the functions defined in the same JSP, delimited by <%! and %> tags, but the creation of the form, that happens inside of those functions, get executed even if the function isn't called like print_footer(); for instance.
I 'm used to programming in ASP and I could easily do these there, but I'm having a hard time migrating to JSP. What am I doing wrong?

"Cast" a String Attribute to String Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have a little problem with Attributes. I am currently working on a project that parses emails from an LDAP server into the Java application that will be doing some interesting stuff with emails in the future.
I am currently having this code that takes emails from users on LDAP and it needs to put emails in the User class as seen in my code:
[some code here, TRY CATCH is also included]
LdapContext ctx = new InitialLdapContext(env, null);
ctx.setRequestControls(null);
NamingEnumeration<?> namingEnum2 = ctx.search("[path to the server]", "(objectClass=user)", getSimpleSearchControls());
System.out.println("Test: print emails from whole DIRECOTRY: \n");
while (namingEnum2.hasMore()) {
SearchResult result = (SearchResult) namingEnum2.next();
Attributes attrs = result.getAttributes();
System.out.println(attrs.get("mail"));
/** This line above works fine, but every time there is no email
in User info, it prints "null" in some cases when there is
no email, which is not perfect. But this is just here to see
if everything works and indeed it does.**/
/**User Class accepts a String parameter, checks if it's empty
and all that, does some checking and etc... BUT! attrs.get("mail")
is an Attribute, NOT a String. And I need to somehow "cast" this
attribute to a String, so I can work with it.**/
User user = new User(attrs.get("mail")); //error yet,because the parameter is not a String.
User user = new User(attrs.get("mail").toString());//gives an expeption.
/** And I know that there is a toString() method in Attribute Class,
but it doesn't work, it gives an "java.lang.NullPointerException"
exception when I use it as attrs.get("mail").toString() **/
}
Here is User class's constructor:
public User(String mail){
eMail = "NO EMAIL!";
if (mail != null && !mail.isEmpty()){
eMail = mail;
}
else
{
eMail = "NO EMAIL!";
}
}
try this
User user = new User(attrs.get("mail")!=null?attrs.get("mail").toString():null);
First you need to check that given attribute exists by using != null (e.g. using Objects.toString which does that inside, or manual if) check, and then use either toString on the Attribute, just like println does inside:
User user = new User(Objects.toString(attrs.get("mail")));
Or you can also use (to retrieve a single value in the attribute, if you have many you need to use getAll):
Object mail = null;
if (attrs.get("mail") != null) {
mail = attrs.get("mail").get();
}
User user = new User(mail.toString());

If session exist or not

I am trying to write my first app on Google App Engine, I was trying to maintain a session, I created a login page on submit, it call to a servlet, servlet validates the user and create a new session using the following code.
void createSession(String Username) {
getThreadLocalRequest().getSession(true).setAttribute("Username", Username);
}
login page after calling the servlet redirects to some page i.e. abc.jsp, my abc.jsp page contains
<body><%
try {
if (request.getSession(false) == null) {
} else {
%>
Welcome to
<%=session.getAttribute("Username")%>
<%
if (session.getAttribute("Username").equals("")) {
%>
<b>Login </b>
<%
} else {
%>
<b>Logout</b>
<%
}
}
} catch (Exception e) {
}
%></body>
it works fine, but when I access abc.jsp without creating a session it is throwing an exception at this if (session.getAttribute("Username").equals("")) line, I dunno why kindly help me. I think it dont detect if session exists. but I have read so many threads like this It gave me this solution, I dunno what I am doing wrong.
As far as I remember
session.getAttribute("xyz")
returns null if the attribute does not exist...
so your NullPointerException occurs because you try to call equals on null.
I suggest to do a check on your attribute itself before validating its content:
if (session.getAttribute("Username") == null || session.getAttribute("Username").equals(""))
<%
if (session.getAttribute("Username") != null) {
…
}
%>
Before to check session's attributes, you have to see the session itself.
So, first:
HttpSession session = request.getSession(false);
if(session != null){...}
and then,
if(session.getAttribute("xyz") != null){...}
Better solution might be both in one line:
if(session != null && session.getAttribute("xyz") != null)
returns null if the attribute does not exist... so your
NullPointerException occurs because you try to call equals on null.
Obviously, it's strictly recommended to check your attribute, before validating its content (as above).
It Worked For me. Try This
String userName;
userName = (String)session.getAttribute("uname");
if (session.getAttribute("userName").equals(""))

creating login and welcomenpages using JSP

I want to create a login page thats when the user select either remember username or remember me check box, a cookie should be generated, when the remember username checkbox is selected, it should store the username, when the remember me checkbox is selected it should store both the username and password to avoid retyping whena user returns to the login page.
I wrote the preceeding code to incorporate the functionality but on testing the page the user has to retype the username each time the login page is loaded. I am not able to identify the cause of the problem, can someone help me with this?
<%
String userName = request.getParameter("username");
String password = request.getParameter("password");
String rm_me = request.getParameter("rm_me");
String rm_uname = request.getParameter("rm_uname");
if (userName != null && password != null) {
if (rm_me != null) {
Cookie ckU = new Cookie("username", userName);
Cookie ckP = new Cookie("password", password);
response.addCookie(ckP);
} else {
if (rm_uname != null) {
Cookie ckU = new Cookie("username", userName);
}
}
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("username")) {
userName = cookies[i].getValue();
}
if (cookies[i].getName().equals("password")) {
password = cookies[i].getValue();
}
}
}
%>
You shouldn't be doing this kind of stuff in a JSP. You should use do it in a "controller" servlet and then forward the outcome to a JSP to (just) format the HTML response.
And I think your problem is most likely to be related to that. Specifically, I suspect that the response will already have been committed by the time that the scriptlet code executes. This means that your response.addCookie(...); call will be too late to add a SetCookie header to the response.
You should be able to confirm this by dumping the response headers when they leave the server or when they reach your browser ... or (less directly) by looking in the browser cookie store.
Pretty much any introductory book or tutorial on JSP would include examples of everything you want.
Any reasonably recent one will also tell you that using Java code in a JSP is very bad indeed, just don't do it.
Use JSTL instead.

Grails AddTo in for loop

Merged with Grails addTo in for loop.
I am facing a problem due to that i'm newbie to grails
i'm doing a website for reading stories and my goal now is to do save the content of the story into several pages to get a list and then paginate it easily .. so i did the following.
in the domain i created two domains one called story and have this :
class Story {
String title
List pages
static hasMany=[users:User,pages:Page]
static belongsTo = [User]
static mapping={
users lazy:false
pages lazy:false
}
}
and have of course domain called page have this :
class Page {
String Content
Story story
static belongsTo = Story
static constraints = {
content(blank:false,size:3..300000)
}
}
and the controller saving method gone like this:
def save = {
def storyInstance = new Story(params)
def pages = new Page(params)
String content = pages.content
String[] contentArr = content.split("\r\n")
int i=0
StringBuilder page = new StringBuilder()
for(StringBuilder line:contentArr){
i++
page.append(line+"\r\n")
if(i%10==0){
pages.content = page
storyInstance.addToPages(pages)
page =new StringBuilder()
}
}
if (storyInstance.save(flush:true)) {
flash.message = "${message(code: 'default.created.message', args: [message(code: 'story.label', default: 'Story'), storyInstance.id])}"
redirect(action: "viewstory", id: storyInstance.id)
}else {
render(view: "create", model: [storyInstance: storyInstance])
}
}
i know it looks messy but it's a prototype..any way.. the problem is that i'm waiting from "storyInstance.addToPages(pages)" line to add to the set of pages an instance of the pages every time the condition is true..but what actually happen that it's give me the last instane only with the last page_idx while i thought it should save the pages one by one and so i can get a list of pages to every story..
why this happen and is there a simpler way to do it than what i did..
i'm waiting for any help here that is appreciated

Categories