Invoking a JSP Page from a Servlet - java

Can anyone tell me if there exists any method other than RequestDispatcher, to invoke a jsp page from my servlet? Because i have tried a lot without success.
My servlet works normally and recovred all the data from jsp. All that I need is to be redirected to another page when the user enters the username and password correctly.
my code :
first my servlet " login"
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String user = request.getParameter("username");
String pass = request.getParameter("password");
System.out.println(" le user est "+user+ " le mot de passe est " + pass);
String query = "SELECT * FROM users WHERE username = '"+user+"' and password='"+pass+"'";
dbconn = new DBAccess();
Connection conn = dbconn.connect();
stmt = conn.createStatement();
ResultSet res = stmt.executeQuery(query);
if(res.next()){
ServletContext sc = this.getServletContext();
RequestDispatcher rd =sc.getRequestDispatcher( "inscreption.jsp");
rd.forward(request, response);
System.out.println(" il existe");
}else {
ServletContext sc = this.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("index.jsp");
// RequestDispatcher rd =request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
System.out.println("not found");
}
} catch (SQLException ex) {
Logger.getLogger(login.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
System.out.close();
}
}}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
/* #Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
my jsp that i would to be redirected for
<html>
<head>
<!--local jquery-->
<script src="jQuerys/jquery-1.9.1.min.js"></script>
<script src="jQuerys/jquery.mobile-1.3.1.min.js"></script>
<link rel ="stylesheet" type="text/css" href="css/jqueryMobile-1.3.1.css"/>
<!--/local jquery-->
</head>
<body>
<div data-role="page" id="inscription">
<div data-role="header" data-theme="b">
<center>CERIST</center>
</div>
<form id="insc" method="post" action="login">
<div data-role="content">
<div data-role="fieldcontain">
<label for="identifiant">Identifiant </label>
<input type="text" id="identifiant"/>
</div>
<div data-role="fieldcontain">
<label for="password1">Mot de passe </label>
<input type="password" id="password1"/>
</div>
<div data-role="fieldcontain">
<label for="password2">Confirmation</label>
<input type="password" id="password2"/>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Vous êtes :</legend>
<input type="radio" name="profil" id="radio-choice-1" value="Candidat" />
<label for="radio-choice-1">Utilisateur</label>
<input type="radio" name="profil" id="radio-choice-2" value="Entreprise" />
<label for="radio-choice-2">Administrateur</label>
</fieldset>
</div>
<br/>
S'inscrire
</form>
</div>
</div>
</body>
</html>

index.jsp :
<form action="Myservlet" method="post"><br>
User name`<`input type="text" name="username"`>`<br>
Password `<`input type="password" name="password"><br>
`<`input type="submit" value="Submit" `>`
</form>
Myservlet.java:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("Oppos!!!");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
RequestDispatcher rd;
if (user.equals("username") && pass.equals("password")) {
rd = request.getRequestDispatcher("/inscreption.jsp");
rd.forward(request, response);
} else {
rd = request.getRequestDispatcher("/wrong.jsp");
rd.forward(request, response);
}
}
You can create more than two pages where you want to dispatch your request so here I created more than two jsp page names: right.jsp and wrong.jsp. If the username and password is correct then it frowards to right.jsp page if it's wrong, it frowards the request to wrong.jsp page.

Related

request.getParameter is returning null ,I have surfed a lot for this but i didn't got the proper solution

So basically, when I try submitting my jsp, the control wents to the servlet , but the values of all the control in jsp becomes null
"ViewBook.jsp"
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#include file="Header_1.jsp" %>
<form action="<%=request.getContextPath()%>/BookServlet" method="post"
enctype="multipart/form-data">
<table>
<th colspan="2"></th>
<tr>
<td>
ID:
</td>
<td>
<input type="number" name="id">
</td>
</tr>
<tr>
<td>
Title:
</td>
<td>
<input type="text" name="title">
</td>
</tr>
<tr>
<td>
Author
</td>
<td>
<input type="text" name="author">
</td>
</tr>
<tr>
<td>
Price:
</td>
<td>
<input type="number" name="price">
</td>
</tr>
<tr>
<td>
Book image:
</td>
<td>
<input type="file" name="book_img">
</td>
</tr>
<tr>
<td>
Publish date:
</td>
<td>
<input type="date" name="pub_date">
</td>
</tr>
<tr>
<td>
<input type="submit" value="add" formaction="
<%=request.getContextPath()%>/BookServlet?action=add">
<input type="submit" value="delete"
formaction="G:\sem5\AJT\Q-4\src\java\BookServle?action=delete">
<input type="submit" value="update" formaction="
<%=request.getContextPath()%>/BookServlet?action=update">
<input type="submit" value="view" formaction="
<%=request.getContextPath()%>/BookServlet?action=view">
</td>
</tr>
</table>
</form>
<%#include file="Footer.jsp" %>
"BookServlet.java"
#WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
}
}
// processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String title=request.getParameter("title");
String author=request.getParameter("author");
String price=request.getParameter("price");
System.out.println("price=="+price);
String book_img=request.getParameter("book_img");
System.out.println("book:imagre===="+book_img);
String pub_date=request.getParameter("pub_date");
String action=request.getParameter("action");
SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
Date d = null;
try {
d = (Date) sdf.parse(pub_date);
} catch (Exception ex) {
System.out.println("Exception ex="+ex);
}
Part filepart=request.getPart("book_img");
System.out.println("part====="+filepart);
InputStream is=filepart.getInputStream();
BookBean bb=new BookBean();
// ResultSet rs=bb.ViewAllBooks();
if(action.equals("add"))
{
Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
bb.add(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
// processRequest(request, response);
}else if(action.equals("update"))
{ Book b=new
Book(0,title,author,Integer.parseInt(price),d,is);
// boolean flag= bb.update(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
}else if(action.equals("delete")){}
else if(action.equals("view")){}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This is what I got in my catch block
-Exception ex=java.lang.NullPointerException
StackTrace:
java.lang.NullPointerException
at BookCrud.BookServlet.doPost(BookServlet.java:136)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke
(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke
(AuthenticatorBase.java:491)
at org.apache.catalina.core.StandardHostValve.invoke
(StandardHostValve.java:139)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke
(AbstractAccessLogValve.java:668)
at
org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service
(CoyoteAdapter.java:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process
(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process
(AbstractProtocol.java:764)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun
(NioEndpoint.java:1388)
at
org.apache.tomcat.util.net.SocketProcessorBase.run
(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1149)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run
(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
any help from your side
also, I have surfed a lot for this on StackOverflow and other websites but
I didn't get any proper solution for this.......
For all those who are facing the same error ::You can use jar files as mentioned by #secret super star ,But if you dont want to do so here is a tip :
Just
import javax.servlet.annotation.MultipartConfig;
in your servlet and add
#MultipartConfig(maxFileSize = 16177215) //Length of the file
annotation ,That's it
Note: In my case following will be my servlet
#WebServlet (name="BookServlet", urlPatterns = {"/BookServlet"})
#MultipartConfig(maxFileSize = 16177215)
public class BookServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
try (PrintWriter out = response.getWriter()) {
}
}
// processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String title=request.getParameter("title");
String author=request.getParameter("author");
String price=request.getParameter("price");
System.out.println("price=="+price);
String book_img=request.getParameter("book_img");
System.out.println("book:imagre===="+book_img);
String pub_date=request.getParameter("pub_date");
String action=request.getParameter("action");
SimpleDateFormat sdf=new SimpleDateFormat("mm/dd/yyyy");
Date d = null;
try {
d = (Date) sdf.parse(pub_date);
} catch (Exception ex) {
System.out.println("Exception ex="+ex);
}
Part filepart=request.getPart("book_img");
System.out.println("part====="+filepart);
InputStream is=filepart.getInputStream();
BookBean bb=new BookBean();
// ResultSet rs=bb.ViewAllBooks();
if(action.equals("add"))
{
Book b=new Book(0,title,author,Integer.parseInt(price),d,is);
bb.add(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
// processRequest(request, response);
}else if(action.equals("update"))
{ Book b=new
Book(0,title,author,Integer.parseInt(price),d,is);
// boolean flag= bb.update(b);
HttpSession s=request.getSession(true);
// s.setAttribute("rs", rs);
RequestDispatcher
rd=request.getRequestDispatcher("ViewAllBooks.jsp");
rd.forward(request, response);
}else if(action.equals("delete")){}
else if(action.equals("view")){}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
you can not directly get parameters by using request.getParameter(name);. While using it, form fields aren't available as parameter of the request, they are included in the stream, so you can not get it the normal way.
Refer this: http://commons.apache.org/proper/commons-fileupload//using.html, under the section Processing the uploaded items.

Java servlet doPost method not working

Edit:
I pointed the post request to /vault/Login but the servlet was on /vault/index and vault/login
when pointing it towards index it worked.
I'm trying to make a login system.
I have an html file which a post method is requested from but the doPost method is never fired when requested.
When the submit button is clicked the url changes with the parameters in it but nothing happens.
Every time the doPost() is executed the first statement writes something to the console but neither does that happen.
public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
System.out.println("fired");
HttpSession session = request.getSession();
session.setAttribute("loginFailed", false);
RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
rd.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("this is another test");
HttpSession session = request.getSession();
String username = (String)session.getAttribute("username");
String password = (String)session.getAttribute("password");
System.out.println(username + " " + password);
boolean succes = false;
if (!"".equals(username) && !"".equals(password)){
try {
succes = Authentication.checkCredentials(username, password);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
switch ((String)session.getAttribute("platform")){
case "browser":
RequestDispatcher rd = request.getRequestDispatcher("Lobby.jsp");
rd.forward(request, response);
break;
case "desktop":
int id = Tracker.getIdByUsername(username);
List vaults = (List)VaultManagement.getVaultsByUserId(id);
int[] vaultIds = new int[vaults.size()];
if (vaults.isEmpty()){
vaultIds[0] = -1;
}else{
int x = 0;
for (Object vault : vaults){
Vault v = (Vault)vault;
vaultIds[x] = v.getId();
x++;
}
}
DAL.Entities.Account account = AccountManagement.getAccountByUsername(username);
LoginPackage pack = new LoginPackage(username, password, account.getEmail(), vaultIds);
String json = JSON.dataPackageToJson(pack);
PrintWriter writer = response.getWriter();
writer.print(json);
break;
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Post
<div class="jumbotron" width="10%">
<form id="form" action="/vault/Login.jsp">
<h6>Username:</h6>
<input type="text" class="form-control" id="username" name="username">
<h6>Password:</h6>
<input type="password" class="form-control" id="password" name="password"><br>
<button type="button" onclick="location.href='vault/Register.jsp'" class="btn btn-secondary">Register</button>
<input type="hidden" name="platform" value="browser"/>
<input type="submit" value="Login"/>
</form>
</div>
You forgot to specify the method attribute to be post:
<form id="form" action="/vault/Login.jsp" method="post">
<!-- Here ---------------------------------^ -->

httpservlet parameter are null [duplicate]

This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}

Servlet won't redirect me

i have logout button and when its pressed i want to return to main page but it stays on current page. although i receive response in chrome developer tools.
userinfo.jsp
<input type="button" onclick="logout()" value="Logout" class="btn" style="margin-top: 10px; margin-bottom: 10px;"/>
logout.js
function logout(){
$.post("Logout");
}
Logout.java servlet
public class Logout extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = null;
try{
HttpSession sess = request.getSession();
if(sess != null){
sess.invalidate();
}
response.sendRedirect("index.html");
Use RequestDispatcher instead of using sendRedirect
For Example:
RequestDispatcher reqDispatcher = req.getRequestDispatcher("pathToResource/MyPage.jsp");
reqDispatcher.forward(req,res);
Read why and when to use each of RequestDispatcher and sendRedirect
<input type="button" onclick="window.location.href='/path/servlet.java'" value="Logout" class="btn" style="margin-top: 10px; margin-bottom: 10px;"/>

Hang Man Game in MVC with JSP

I want to create Hang man game, but I need to save the session and the username, but I have problems for pass the username. I wrote the JSP, servlet and Javabean, but after the login my user, in the next view I only have Welcome + NULL. Help me please. thanks for the help.
I don't know how Can I pass the name to the next view.
enter code here
this is the JavaBean(Userdata.java):
public class Userdata {
String userName;
public Userdata() {
}
public Userdata(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
This is the servlet, in this code I need to use a session, but I want to that, in all the time that the user is logging, cans see his/her name
loginServlet.java
public class loginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata = new Userdata(usuari);
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", username);
RequestDispatcher view = request.getRequestDispatcher("juego.jsp");
view.forward(request, resp);
}
}
Finally the Views in JSP, The first view is the login
Nom de jugador:
Contrasenya:
And this is the response of servlet -> juego.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Penjat</title>
</head>
<h2>Benvingut</h2>
<%=request.getAttribute("usuari")%>
<div align="center">
<h1>Joc del Penjat</h1>
</div>
<div align="center">
<!--Delaració d'imatges-->
<img src="Imatges/p_JEE_3.png">
</div>
<div align="center">
<!--Declaració de les lletres-->
Lletra:
<input type="text" name="lletra" size="1" maxlength="1">
<br/>
<p>
<input type="hidden" name="id" value=""/>
<input type="hidden" name="vegades_jugades" value=""/>
<input type="hidden" name="pistes" value=""/>
<input type="submit" name="boto_jugar" value="Jugar">
</p>
</div>
First you have to put username in request, in your servlet use request.setAttribute in the following manner
request.setAttribute("username", value);
where value happens to be the object you want to read later.
Use it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("username")
or
<%= request.getAttribute("username")>
Thanks for your help, now I understand, I modificated and now I can get the username.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata usuari = new Userdata();
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", usuari);
RequestDispatcher view = request.getRequestDispatcher("juegoOriginal.jsp");
view.forward(request, resp);
}

Categories

Resources